skip to Main Content

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.

2

Answers


  1. I am not sure where you add that code, but you can try this:

    $args = array( 'post_type' => 'post', 's' => isset( $_GET['s'] ) ? $_GET['s'] : '')

    Just add the ‘s’ key in you $args variable.

    This is not the best solution because you are making additional query on the search page. But given the info you have in your question that should work.

    Better solution would be in the page where you display the title (search page) you can try:

    global $wp_query; $totalposts = $wp_query->found_posts;

    Login or Signup to reply.
  2. As mentioned in the comments, use th _n() to pluralize your string.

    <?php
    $args       = array(
        'post_type' => 'post',
    );
    $query      = new WP_Query( $args );
    $totalposts = $query->found_posts;
    echo esc_attr( $totalposts . ' ' . _n( 'Meme', 'Memes', $totalposts ) );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search