search

Home  >  Q&A  >  body text

How to dynamically change the number of posts per page in WordPress

<p>I would like to change the number of posts displayed on certain pages on my WordPress site. </p> <p>I found the following code snippet here: </p> <pre class="brush:php;toolbar:false;">$postsPage = $settings["postspage"]; query_posts('posts_per_page='.$postsPage);</pre> <p>Call before <code>if (have_posts()) while (have_posts()) the_post()</code></p> <p>I'm very new to php, but what I'm trying is this</p> <pre class="brush:php;toolbar:false;">... if ( is_front_page()) { $postsPage = $settings["postspage"] 1; }elseif ( is_tag()) { $postsPage = $settings["postspage"] - 2; } else { $postsPage = $settings["postspage"]; } query_posts('posts_per_page='.$postsPage); ...</pre> <p>But unfortunately it doesn't work. Instead, it only returns 1 post from the homepage instead of 1 of 5 set in the WP menu. I can hardcode the desired value like $postPage = 6; </code> for is_front_page and it works fine. For some reason I can't add/subtract anything from the value given by <code>$settings["postspage"]</code>. It also works if I don't change the value (else-clause). What did I miss? </p> <p>I've tried converting the value of <code>$settings["postspage"]</code> to an integer because I thought it might be returned as a string. I use: <code>$postsPage = (int)$settings["postspage"] 1;</code> or <code>$postsPage = intval($settings["postspage"]) 1;</ code>But without success. Since I'm not very familiar with wordpress functions and their variables, I was looking for the reason why I can't modify the number of posts. I'd appreciate any tips! </p>
P粉256487077P粉256487077438 days ago414

reply all(1)I'll reply

  • P粉153503989

    P粉1535039892023-09-03 00:44:13

    It's not clear where you put this code and how to find $settings, but this should work.

    add_action( 'pre_get_posts', 'alter_number_of_posts' );
    
    function alter_number_of_posts( $query ) {
    
        if ( !$query->is_main_query() ){
            return;
        }
    
        $posts_per_page = get_option( 'posts_per_page' );
    
        if ( is_front_page() ) {
            $query->set( 'posts_per_page', $posts_per_page + 1 );
            return;
        }
        if ( is_tag() ) {
            $query->set( 'posts_per_page', $posts_per_page - 2 );
            return;
        }
    }

    $query is passed by reference, so any changes you make to it will be reflected in the global query object. You don't need to return it, which means you can safely return from a function within each condition instead of using elseif.

    reply
    0
  • Cancelreply