• Resolved Jo Batkin

    (@jobatkin)


    I’m trying to get a list of all posts within a category.
    From the looks of things I should be using get_posts to do this, but it simply will not let me specify both numberofposts and the category.

    Here’s my code:

    $args = array('numberposts' => -1, 'category' => 5);
    $catPosts = get_posts( $args );
    echo count($catPosts); // -> 6! there should be 12!

    If I just put numberofposts ion the args then I get all posts in all categories. Specifying a category for some reason ignores my numberofposts.

    Anyone know what’s going on?

Viewing 6 replies - 1 through 6 (of 6 total)
  • Hi.
    Your code is valid. Where are you trying to use it? Depending on the answer, you could try query_posts() as an alternative.
    Cheers!

    Try this:

    <ul>
    <?php
    global $post;
    $args = array( 'numberposts' => 5,  'category' => 5 );
    $catPosts = get_posts( $args );
    foreach( $catPosts as $post ) :	setup_postdata($post); ?>
    	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>
    echo count($catPosts);
    </ul>
    Thread Starter Jo Batkin

    (@jobatkin)

    I am trying to use it in the sidebar, to show all other posts in the current category.

    Thanks for your reply dadvan, but I tried your code and I still got 6 posts, not 5.

    In that case, there must be something wrong with your site because that’s where I tried it too and it works just fine.
    Did you try the usual troubleshooting steps: i.e., reverting to the WP default theme (Twenty Eleven), disabling all your plugins, etc.? Also, it would be useful to know what version of WP you are running and, also, just in case, if you posted a link to your site so we can see what is going on.
    Thanks!

    Thread Starter Jo Batkin

    (@jobatkin)

    Thanks all for checking it out for me and reassuring me there was nothing wrong with my code.
    After lots of googling I figured out that my theme must be using the ‘pre_get_posts’ filter to override the number of posts returned by get_posts. Once I knew this I just had to find the php file where this was being set, which I eventually did. After so many hours of trying to figure out why my code wasn’t working, it turns out that there is a ‘handy’ option in my theme settings to specify how many posts are displayed on a category screen. Changing this to -1 finally gives me all the posts in my category. If I don’t want to change the setting everywhere, but just in my sidebar code, then I can just add this:

    remove_filter('pre_get_posts', '<name of override function>');
    ... code to call get_posts ...
    add_action( 'pre_get_posts', '<name of override function>' );

    Thanks to all who helped.

    No problem. Glad you could figure it out.
    Happy blogging!

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘numberofposts not working in get_posts’ is closed to new replies.