Query string in URL makes main query misbehave and pagination not to work in Wor

  • Unknown's avatar

    I have archive page of movies in which I am presenting all movies paginated. On side bar I have genres(taxonomy) for movies. When user clicks on one I want results on the page to be filtered according to which genre he clicked.

    My way of thinking made me do this using query string in URL. So when user click on genre it requests same URL (archive for movies) but adds ?genre=SOMETHING. Then in pre_get_posts hook I have this if statement to modify main query:
    `
    if(
    !is_admin() &&
    $query->is_main_query() &&
    is_post_type_archive(‘movie’) &&
    get_query_var(‘genre’)
    )
    `

    Then after that I have code like this to filter movies by genre user clicked on :
    `
    $taxonomyQuery = [
    [
    ‘taxonomy’ => ‘genre’,
    ‘field’ => ‘slug’,
    ‘terms’ => get_query_var(‘genre’),
    ],
    ];
    $query->set(‘tax_query’, $taxonomyQuery);
    `

    Sidebar link are constructed like this :

    `
    <a href=”<?php echo esc_url(add_query_arg(‘genre’, $genre->slug)) ?>”>
    <?php echo $genre->name; ?>
    </a>
    `

    Taxonomy is created with name genre so that name is automatically added to query_vars.

    When I open archive page of movies /movies/ I get paginated results and everything works fine. But once I click on genre I get this path /movies/?genre=comedy.
    pre_get_posts activates and filters movies according to the genre selected but pagination doesnt work. Even if I set $query->set('posts_per_page', 1); I still get more than one result returned from query. Problem only occurs when query string ?genre=SOMETHING gets added to URL and I cannot figure out why.

    NOTE: I am relatively new to wordpress development and I do not actually know if this is the right way to do this kind of thing.

    Any help is appreciated!

    The blog I need help with is: (visible only to logged in users)

  • Unknown's avatar

    Hi there!

    It doesn’t sound like you have a website hosted here at WordPress.com.

    Because WordPress.com and WordPress.org (where you download the open-source WordPress software) are two entirely separate entities, we can only assist with sites that are hosted on our servers.

    You can find more information here about the differences between WordPress.org software and WordPress.com: https://wordpress.com/support/com-vs-org/

    If you’re new to development, the WordPress.org forums are a great resource for sites using the open source WordPress.org software, and you can find the developer forums here:

    https://wordpress.org/support/forum/wp-advanced/

    I hope that helps!

  • The topic ‘Query string in URL makes main query misbehave and pagination not to work in Wor’ is closed to new replies.