0

I am trying to make a custom search plugin but pagination does not work (it shows up with the correct number pages but does not function properly).

Relevant part of the search plugin (from the main function)

    $blog_url = get_bloginfo('url');

    $form = <<<EOH
    <div id="sbc">
    <form method="get" action="{$blog_url}" id="ss-search">
        <input type="text" value="{$search_text}" name="supers" onblur="if (this.value == '') { this.value = '{$search_text}';}" onfocus=if (this.value == '{$search_text}') { this.value = '';}" />
        {$list}
        <input type="submit" id="sbc-submit" value="Search" />
    </form>
    </div>
EOH;

///////////////////////////////////

    if (isset($_GET['supers'])) {

        global $q;
        // global $q;
        $args = array(
            // 'category__not_in' => 1,
            's' => $_GET['supers']
        );

        $q = new WP_Query($args);

        if ( $q->have_posts() ) {
                echo '<ul>';
            while ( $q->have_posts() ) {
                $q->the_post();
                echo '<li>' . get_the_title() . '</li>';
            }
                echo '</ul>';
                // echo '<br>Posts found :'.$q->found_posts.'<br><br>';
                echo get_pagination_links2();
        } else {
            echo 'no posts found';

        }

        /* Restore original Post Data */
        wp_reset_postdata();
    }

    return $form;

} // end function
$q; // add ability to make it global

pagination function in the functions.php file

function get_pagination_links2() {
    global $q;
    // echo gettype($q);
    echo $q->found_posts;
    $big = 999999999;

    return paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format' => '?paged=%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $q->max_num_pages,
        'prev_next'    => true
    ) );

}

I DO get pagination links, but they don't work (for example if I click next the URL changes but the results don't).

1 Answer 1

1

And they shouldn't change. Let's take a look at your code...

Here you're creating your custom query:

$args = array(
    // 'category__not_in' => 1,
    's' => $_GET['supers']
);

$q = new WP_Query($args);

As you can see there is no pagination param passed to this query, so it will always show first page of results.

You have to add this param. Below you can find fixed part of your code:

$args = array(
    // 'category__not_in' => 1,
    's' => $_GET['supers'],
    'paged' => get_query_var('paged')
);

$q = new WP_Query($args);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.