This Code will help you to show related post without any plugin on wordpress pages or post.
You can use this code on page.php or single.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php // Get the current page $current_page_id = get_the_ID(); $current_page_title = get_the_title($current_page_id); // Custom query to get related posts based on title similarity $related_args = array( 'post_type' => 'page', 'posts_per_page' => 10, 'post_status' => 'publish', 'orderby' => 'relevance', // Order by relevance based on title similarity 'order' => 'DESC', 'post__not_in' => array($current_page_id), // Exclude the current page 's' => $current_page_title, // Use page title as the search term ); $related_query = new WP_Query($related_args); // Display related posts if ($related_query->have_posts()) : echo '<div class="related-posts">'; echo '<h3>Related Pages</h3>'; echo '<ul>'; while ($related_query->have_posts()) : $related_query->the_post(); echo '<li><a href="' . esc_url(get_permalink()) . '">' . get_the_title() . '</a></li>'; endwhile; echo '</ul>'; echo '</div>'; // Restore original post data endif; ?> |