WordPress.org

Forums

[resolved] Using pre_get_posts Breaks Pagination (5 posts)

  1. Mark Wilkinson
    Member
    Posted 7 months ago #

    I have a site (a few actually) that stores jobs with multiple categories and locations etc. I also have a form that allows simple searching of jobs. The make this work by searching multiple things e.g. Accountants in London I have used pre_get_posts on the job post type archive page to filter the results based on search. The code used to do this is linked below:

    https://gist.github.com/wpmark/7edc5bf6b2fb8297082b

    This works great and the job archive page now shows all jobs that matched the search criteria used. However there is a problem with pagination.

    If the search results multiple pages, although the results should pagination (and they show the correct number of pages), as soon as you click on one of those pages, the pre_get_posts alterations are lost and it defaults to showing page 2 for example of all the jobs.

    It seems like I need to pre_get_posts to work on all the paginated pages too. If anyone could assist with this I would be very grateful.

    Thanks in advance.

  2. Mark Wilkinson
    Member
    Posted 7 months ago #

    Forgot to mention an example. You can see an example of the behaviour above here:

    http://www.chefsjobsuk.com/jobs/

    Search for jobs in the Midlands and it returns 3 pages of results. Click on page 2 and we just end up going back to the original post type archive query looking at page 2.

  3. Ben Huson
    Member
    Posted 7 months ago #

    Your pre_get_posts won't be working on the second page because of this:

    if( $_POST[ 'pxjn_search_form_used' ] != 'yes' )
    		return;

    The 'pxjn_search_form_used' will not be posted when clicking to the next page.

    You'll probably need to filter the pagination URLs (not sure which filter you'll need for that off the top of my head) and append the 'pxjn_search_form_used' query parameter to the link URL using add_query_arg() and change the $_POST above to use $_REQUEST.

  4. Ben Huson
    Member
    Posted 7 months ago #

    Either that, or use cookies to store the value of 'pxjn_search_form_used' but that could get messy and confusing.

  5. Mark Wilkinson
    Member
    Posted 7 months ago #

    Thanks for those suggestions Ben - you have helped a great deal in solving the problem. You are indeed correct it was the $_POST check that was the problem.

    I have now managed to get this working using $_SESSION instead. I have amended the Gist to show this:

    https://gist.github.com/wpmark/7edc5bf6b2fb8297082b

Reply

You must log in to post.

About this Topic