SilverLink
SilverLink

Reputation: 134

How to display number of search results in WordPress (Genesis)

I'm trying to display the number of posts found by a search.

I found this code $wp_query->found_posts but can't seem to make it work, any suggestions?

<?php

add_action( 'genesis_before_loop', 'genesis_do_search_title' );

function genesis_do_search_title() {

    $title = sprintf( '<div class="archive-description"><h1 class="archive-title">%s %s %s</h1></div>',  $wp_query->found_posts, apply_filters( 'genesis_search_title_text', __( 'results for:', 'genesis' ) ), get_search_query() );

    echo apply_filters( 'genesis_search_title_output', $title ) . "\n";

}

genesis();

Documentation:

https://codex.wordpress.org/Creating_a_Search_Page#Display_Total_Results

http://my.studiopress.com/documentation/snippets/

Upvotes: 3

Views: 3665

Answers (4)

user7683419
user7683419

Reputation:

global $wp_query; needs to be present. The syntaxe used shoud be:

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

Upvotes: 7

SilverLink
SilverLink

Reputation: 134

Got it working after further reviewing the documentation and adding:

global $wp_query;

So the code is:

<?php

add_action( 'genesis_before_loop', 'genesis_do_search_title' );

function genesis_do_search_title() {

    global $wp_query;

    $title = sprintf( '<div class="archive-description"><h1 class="archive-title">%s %s %s</h1></div>',  $wp_query->found_posts, apply_filters( 'genesis_search_title_text', __( 'results for:', 'genesis' ) ), get_search_query() );

    echo apply_filters( 'genesis_search_title_output', $title ) . "\n";

}

genesis();

Thank you everyone!

Upvotes: 0

Suraj Menariya
Suraj Menariya

Reputation: 546

Sorry didn't understand code but if you want to count search result through wp_query, so you can use a counter within the loop and display it outside the loop.

Hope it will help you :)

Upvotes: 0

L L
L L

Reputation: 1470

I cannot really find the documentation for genesis hooks so this might not work, but it might be that your action 'genesis_before_loop' is executed before the loop variables are set. Try using 'loop_start' instead.

<?php

add_action( 'loop_start', 'genesis_do_search_title' );

function genesis_do_search_title() {

    $title = sprintf( '<div class="archive-description"><h1 class="archive-title">%s %s %s</h1></div>',  $wp_query->found_posts, apply_filters( 'genesis_search_title_text', __( 'results for:', 'genesis' ) ), get_search_query() );

    echo apply_filters( 'genesis_search_title_output', $title ) . "\n";

}

genesis();

Let me know if this works!

Upvotes: 0

Related Questions