查询自定义分类法下面同分类的帖子(related products)
wptutor
2023-12-24
39 Views
// Get the current post ID
$current_post_id = get_the_ID();
// Get the terms of the custom taxonomy associated with the current post
$terms = get_the_terms($current_post_id, 'custom_taxonomy');
if ($terms && !is_wp_error($terms)) {
$term_ids = array();
foreach ($terms as $term) {
$term_ids[] = $term->term_id;
}
// Query the custom post type posts with the same taxonomy term
$related_args = array(
'post_type' => 'custom_post_type',
'tax_query' => array(
array(
'taxonomy' => 'custom_taxonomy',
'field' => 'term_id',
'terms' => $term_ids,
),
),
'post__not_in' => array($current_post_id), // Exclude the current post
'posts_per_page' => -1, // Retrieve all related posts
);
$related_query = new WP_Query($related_args);
// Output the related posts
if ($related_query->have_posts()) {
while ($related_query->have_posts()) {
$related_query->the_post();
// Display related post information here
// Example: echo '<h2>' . get_the_title() . '</h2>';
}
wp_reset_postdata();
} else {
// No related posts found
// You can output a message here if needed
}
}