I want to display the total number of found posts on results page in WordPress. For example "If someone searches for 'cat' it should display count for posts with the term 'cat', Right now I inserted some PHP code but it is displaying the total number of published posts and that's not I want to achieve. Please follow this link: https://bigfunx.com/?s=cats&id=1516&post_type=post
And you will clearly see that there are four articles found for cat and it is displaying 28 as count instead of 4. I hope you are understanding what I am trying to achieve. Looking forward to hearing from you soon. Thank you!
I try to enter the following code:
<?php $args = array(
'post_type' => 'post'
);
$query = new WP_Query($args);
$totalposts = $query->found_posts;
if($totalposts < 2) {
$result = "Meme";
} else {
$result = "Memes";
}
echo $totalposts . " " . $result; ?>
The above code is displaying the total number of published posts and also with singular and plural feature but I know I am missing something to properly displaying the result, Your help will be highly appreciated.
My Answer:
, if a user searches for a specific keyword and the search results in 10 posts being found, I want to display a message on the results page that says "Found 10 posts matching your search criteria."
To achieve this, you can use the following code snippet in your WordPress theme's search.php file:
php
global $wp_query;
$total_results = $wp_query->found_posts;
if ($total_results > 0) {
echo 'Found ' . $total_results . ' posts matching your search criteria.';
} else {
echo 'No posts found matching your search criteria.';
}
?>
This code snippet retrieves the total number of found posts from the global $wp_query variable and then checks if there are any posts found. If posts are found, it displays a message with the total number of found posts. If no posts are found, it displays a message indicating that no posts were found.
You can customize the message to suit your needs and styling preferences. Just make sure to place this code snippet in the appropriate location within your search.php file to display the message on the search results page.
Rate this post
5 of 5 based on 3554 votesComments