Unique articles on blocks
-
Hi, is there a global custom setting to be able to remove by default duplicate posts from the page?
Examples:
– I have a homepage with many blocks (filtered on categories) and I don’t want to have blocks to display the same posts list (as a post can belong to many categories
– or a single page with sidebar showing latest posts and I don’t want the current post to be displayed. Or on related articles and so on.
Otherwise could be interesting to implment on next release for the community.
Something like (not tested):<?php // Define a global array to hold the IDs of all queried posts global $excluded_post_ids; $excluded_post_ids = array(); // Add custom attributes to the block's HTML output function add_custom_attributes($attributes, $block) { if ($block['blockName'] === 'core/latest-posts') { // Add a custom attribute to the block's HTML output with the desired post order $attributes['data-post-order'] = get_field('post_order', $block['id']); // Add a custom attribute to the block's HTML output with the desired number of posts $attributes['data-posts-per-page'] = get_field('posts_per_page', $block['id']); } return $attributes; } add_filter('block_render_attributes', 'add_custom_attributes', 10, 2); // Modify the query parameters based on the custom block attributes function modify_query($query) { global $excluded_post_ids; if (!is_admin() && $query->is_main_query() && $query->is_home()) { // Get the custom block attributes from the query string $post_order = isset($_GET['post_order']) ? sanitize_text_field($_GET['post_order']) : 'DESC'; $posts_per_page = isset($_GET['posts_per_page']) ? absint($_GET['posts_per_page']) : 10; // Capture each post's ID and add it to the global array $excluded_post_ids[] = get_the_ID(); // Modify the query parameters based on the custom block attributes $query->set('post__not_in', array_merge(get_option('sticky_posts'), $excluded_post_ids)); // exclude sticky posts and previously queried posts $query->set('orderby', 'post_date'); // sort by post date $query->set('order', $post_order); // set the post order based on the custom block attribute $query->set('posts_per_page', $posts_per_page); // set the number of posts per page based on the custom block attribute $query->set('ignore_sticky_posts', true); // ignore sticky posts } } add_action('pre_get_posts', 'modify_query'); // Add an action hook to capture each post's ID and add it to the global array function capture_post_id() { global $excluded_post_ids; $excluded_post_ids[] = get_the_ID(); } add_action('the_post', 'capture_post_id'); ?>
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘Unique articles on blocks’ is closed to new replies.