WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Pagination not working with custom wp_query (3 posts)

  1. vk011
    Member
    Posted 8 months ago #

    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).

  2. bcworkz
    Member
    Posted 8 months ago #

    Your query args are not picking up the page number argument so the query can know which posts to get, thus it just keeps getting the first page's posts every time.

    The page number should be in the main query arguments, you just need to copy it to your query:
    paged => get_query_var('paged'),

  3. vk011
    Member
    Posted 8 months ago #

    that's it. thanks!

Reply

You must log in to post.

About this Topic