0

I use this query to call posts from a custom-type post I setup apart

$args = array( 'posts_per_page' => 5, 'order'=> 'DES', 'post_type' => 'custom-post' );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<div class="thumbnail">
<?php echo get_the_post_thumbnail( $post->ID, 'thumbnail' ); ?>
</div>
<?php the_title( sprintf( '<h2><a href="%s">', esc_url( get_permalink() ) ),'</a></h2>' ); ?>
<?php  echo '<p>' . get_the_excerpt() . '</p>' ?>
<?php endforeach;
wp_reset_postdata();

Two questions:

  1. Is that correct or can I improve it better somehow?
  2. Is it possible to call posts that are placed both in 2 different taxonomy generated from that custom post type ("flowers" and "colors" for instance) and then call post that is in the "flowers" category but not in the "colors" one?

Thank you

0

Answering your second question - yes, it is possible, you can use tax_query for this, for example, this query will get all posts that has any term of 'flowers' taxonomy AND 'colors' taxonomy:

$query = new WP_Query( array(
    'post_type' => 'custom-post',
    'posts_per_page' => 5,
    'order' => 'DESC',
    'tax_query' => array(
        'relation' => 'AND', // it is also possible to use OR
        array(
            'taxonomy' => 'flowers',
            'operator' => 'EXISTS'
        ),
        array(
            'taxonomy' => 'colors',
            'operator' => 'EXISTS'
        )
    )
) );

The second query will get all posts that have terms from 'flowers' taxonomy, but not from 'colors' taxonomy:

$query = new WP_Query( array(
    'post_type' => 'custom-post',
    'posts_per_page' => 5,
    'order' => 'DESC',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'flowers',
            'operator' => 'EXISTS'
        ),
        array(
            'taxonomy' => 'colors',
            'operator' => 'NOT EXISTS' // <-- Take a look at this operator
        )
    )
) );

The code is not tested

Here are also links to the Documentation, check out how to use WP_Query https://developer.wordpress.org/reference/classes/wp_query/#standard-loop

And also WP_Tax_Query https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters

0

Testing your code I arrived finally to an answer: In the first query I didn't use any 'operator' and it works! In the second query I used the 'operator' 'IN' and 'NOT IN' and it worked! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.