Skip to content

Commit fc74e7d

Browse files
committed
WDSBT-23 - modify query for related posts block, exclude current post from the related posts list
1 parent c5a753c commit fc74e7d

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

inc/functions/related-posts-query.php

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
/**
3+
* Related Posts Query
4+
*
5+
* @package wdsbt
6+
*/
7+
8+
namespace WebDevStudios\wdsbt;
9+
10+
/**
11+
* Modify the query variables for the related posts block to exclude the current post.
12+
*
13+
* @param array $query_vars The array of query variables.
14+
* @param WP_Block $block The current block instance being rendered.
15+
* @return array Modified query variables with the current post excluded.
16+
*/
17+
function related_posts_query( $query_vars, $block ) {
18+
19+
// Get the current post ID and its categories.
20+
$current_id = get_the_ID();
21+
$category = get_the_category();
22+
23+
// Initialize variables.
24+
$cat_id = '';
25+
26+
// Check if categories are assigned to the post.
27+
if ( ! empty( $category ) ) {
28+
if ( class_exists( '\WPSEO_Primary_Term' ) ) {
29+
// Show the post's 'Primary' category if this Yoast feature is available and one is set.
30+
$primary_term = new \WPSEO_Primary_Term( 'category', $current_id );
31+
$primary_term_id = $primary_term->get_primary_term();
32+
$term = get_term( $primary_term_id );
33+
34+
if ( is_wp_error( $term ) || ! $term ) {
35+
// Default to first category (not Yoast) if an error is returned.
36+
$cat_id = $category[0]->term_id;
37+
} else {
38+
// Set variables for cat_display & cat_slug based on Primary Yoast Term.
39+
$cat_id = $term->term_id;
40+
}
41+
} else {
42+
// Default, display the first category in WP's list of assigned categories.
43+
$cat_id = $category[0]->term_id;
44+
}
45+
}
46+
47+
// Check if the block has the class 'related-posts-query'.
48+
if ( isset( $block->parsed_block['attrs']['className'] ) && 'related-posts-query' === $block->parsed_block['attrs']['className'] ) {
49+
$query_vars['post_type'] = 'post';
50+
$query_vars['cat'] = $cat_id;
51+
$query_vars['posts_per_page'] = 3;
52+
$query_vars['post__not_in'] = array( get_the_ID() );
53+
$query_vars['orderBy'] = 'date';
54+
$query_vars['order'] = 'desc';
55+
$query_vars['nopaging'] = 'true';
56+
}
57+
58+
// Return the modified query variables.
59+
return $query_vars;
60+
}
61+
add_filter( 'query_loop_block_query_vars', __NAMESPACE__ . '\related_posts_query', 10, 2 );

0 commit comments

Comments
 (0)