WordPress.org

Ready to get started?Download WordPress

Forums

Query with multiple category_name? (7 posts)

  1. JesperA
    Member
    Posted 4 years ago #

    Hi!

    Currently i am using the standard stuff:
    <?php query_posts('category_name=Nyheter&showposts=4'); ?>

    The problem is that it seems like there is no way to add one more category by name?

  2. stvwlf
    Member
    Posted 4 years ago #

    Hi

    I just tested this and it doesn't appear to support more than one category by name, even when names are placed in an array.

    If you must do it by name and not by cat ID (doing it by ID is built into WP and requires no extra work for multiple cats) I would approach it by building a string of cat ID's doing successive lookups of names one by one, and then feeding the string of ID's into the query_posts.

    <?php
    $catIDs = get_cat_ID( $cat_name='Nyheter' );
    $catIDs .= ',' . get_cat_ID( $cat_name='SecondCat' );
    $catIDs .= ',' . get_cat_ID( $cat_name='ThirdCat' );
    query_posts("cat=$catIDs&showposts=4");
    ?>

    You must use double quotes on the query_posts doing it this way.

    If there are a lot of cats to look up, it could be turned into a loop using the cat names in an array at the top.

  3. oldcastle
    Member
    Posted 3 years ago #

    The above code didn't work for me. It was needed to do a little fix.

    <?php
    $catIDs = get_cat_ID( $cat_name='Nyheter' );
    $catIDs .= ',-' . get_cat_ID( $cat_name='SecondCat' );
    $catIDs .= ',-' . get_cat_ID( $cat_name='ThirdCat' );
    query_posts("cat=$catIDs&showposts=4");
    ?>

    I just put the minus sign "-" beside the coma. Now it's works perfectly.

  4. chinmoy
    Member
    Posted 3 years ago #

    use this <?php query_posts('category_name=array('Nyheter', 'Movie')&showposts=4'); ?>

  5. oldcastle
    Member
    Posted 3 years ago #

    This doesn't work for excluding categories.

  6. chinmoy
    Member
    Posted 3 years ago #

    query_posts(array('category__not_in' => array('Nyheter', 'Movie')));

    or

    query_posts('cat' => '-2,-6,-10');

  7. oldcastle
    Member
    Posted 3 years ago #

    http://codex.wordpress.org/Function_Reference/query_posts
    # category__not_in - must use cat ids

    If you want to exclude cats by ID it's ok, but if you want to exclude by name, @stvwlf solution works perfectly.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.