WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Should get_posts("category__and=1,2") work? (6 posts)

  1. wp3678
    Member
    Posted 5 years ago #

    Does anyone know if a statement like below should work?

    $theposts = get_posts("category__and=1,2");

    I have tried several variations but I just can't seem to get the formatting correct it just seems to return any post/no posts/none matching posting etc. The get_posts help page says you can use query_posts parameters.

    Anyone know what I am doing wrong?

    TIA

  2. MichaelH
    Member
    Posted 5 years ago #

    Try:

    $args = array(
      'category__and' => array(1,2)
      );
    $theposts = get_posts($args);

    query_posts() arguments work with get_posts().

  3. wp3678
    Member
    Posted 5 years ago #

    Many thanks that does work in isolation but I think my problem is actually with trying to parametrize the 1,2 bit.

    In the get_posts example it uses examples like:

    $myposts = get_posts('numberposts=5&offset=1&category=1');

    This means the 5, 1, 1 in the criteria string can easily be built up into to appropriate string to be sent into get_posts.

    Can the category__and option be made to work like that or do I need to do something else to build up a string?

    The following (obviously?) do not work for me is what I need possible?

    $myposts = get_posts('category_and=1,2');
    $myposts = get_posts('category_and=array(1,2)');
    $myposts = get_posts('category_and=>array(1,2)');

    TIA

  4. MichaelH
    Member
    Posted 5 years ago #

    $args = array(
      'numberposts' => 5,
      'category__and' => array(1,2)
      );
    $theposts = get_posts($args);

    Also see various examples in the query_posts article.

  5. wp3678
    Member
    Posted 5 years ago #

    Probably many ways of doing this but the PHP explode() function does the job (converts a string to array).

    `$args = array(
    'numberposts' => 5,
    'category__and' => explode(",","1,2");
    );
    $theposts = get_posts($args);`

  6. MichaelH
    Member
    Posted 5 years ago #

    Yes, explode is just an extra step to get to array, so don't know why you wouldn't just use 'category__and' => array(1,2)

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags