i want a query wp for related posts in single page
To display related posts on a single page in WordPress, you can use the following query:
<?php
// Get the current post ID
$current_post_id = get_the_ID();
// Get the categories of the current post
$categories = wp_get_post_categories($current_post_id);
if (!empty($categories)) {
// Build an array of category IDs
$category_ids = array();
foreach ($categories as $category) {
$category_ids[] = $category;
}
// Args for the query
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category__in' => $category_ids,
'post__not_in' => array($current_post_id),
'posts_per_page' => 5, // Change the number of related posts to display
);
// Query the related posts
$related_posts_query = new WP_Query($args);
// Check if there are related posts
if ($related_posts_query->have_posts()) {
echo '<h2>Related Posts</h2>';
echo '<ul>';
// Loop through the related posts
while ($related_posts_query->have_posts()) {
$related_posts_query->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
// Reset the query
wp_reset_postdata();
}
}
?>
You can place this code in your single.php file or in a custom template file if you want to display related posts on a specific page. Remember to modify the posts_per_page value to control the number of related posts to display
原文地址: https://www.cveoy.top/t/topic/iy2h 著作权归作者所有。请勿转载和采集!