Search code examples
phpwordpresswp-list-categories

Removing one category from wordpress posts


Well firstly I am horrible with php. This is my code

$myposts = get_posts('showposts=9');
foreach($myposts as $post) :
setup_postdata($post);

I wanted category "1" to not display so I tried:

$myposts = get_posts('cat=-1, showposts=9');
foreach($myposts as $post) :
setup_postdata($post);

This made all posts stop showing. So I tried selecting only the categories I wanted:

$myposts = get_posts('cat=40,41,42,43,etc, showposts=9');
foreach($myposts as $post) :
setup_postdata($post);

Only 1 post from each category would show up, instead of all of them.

I have the php written on this specific page template, as I would like to use the category elsewhere just not show up on this page. I've tried a few other things but I don't really understand the structure of php and plunking it into random spots hasn't yielded any results.


Solution

  • There are a couple of ways to achieve this. You can use get_posts() (https://codex.wordpress.org/Template_Tags/get_posts) or you can use WP_Query() (http://codex.wordpress.org/Class_Reference/WP_Query)

    I'm not sure what your showposts=9 argument does in your code when you call get_posts()?

    To get all posts except for those in one category (with ID=1) using get_posts:

    $myposts = get_posts(array('cat'=>'-1', 'posts_per_page'=>-1));
    

    The 'cat'=>'-1' means exclude posts where the category ID is 1 and 'posts_per_page'=>-1 means do not limit the number of posts returned.