WP_Query to get posts in a specific category and post format

I’ve been trying to utilize either WP_Query or get_posts to pull out the most recent post that’s both in a specific category and of a specific post format.

<?php 
$singargs = array(
'numberposts' => 1,
'tax_query' => array(
    'relation' => 'AND',
    array(
        'taxonomy' => 'category',
        'field' => 'slug',
        'terms' => array ( 'gift-of-the-day' ),
    ),
    array(
        'taxonomy', => 'post_format',
        'field' => 'slug',
        'terms' => array( 'aside'),
    )
)
);
$singPost = new WP_Query( $singargs );
foreach ( $singPost as $post ) : setup_postdata($post); ?>
<aside>
    <h2><?php the_title(); ?></h2>
</aside>
<?php endforeach; wp_reset_postdata(); ?>

What am I doing wrong here?

Related posts

Leave a Reply

2 comments

  1. Two problems i see:
    change aside to post-format-aside
    and since you are using foreach loop change new WP_Query( $singargs ); to get_posts( $singargs ); so your code sould look like this:

    <?php 
    $singargs = array(
    'numberposts' => 1,
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => array ( 'gift-of-the-day' ),
        ),
        array(
            'taxonomy', => 'post_format',
            'field' => 'slug',
            'terms' => array( 'post-format-aside'),
        )
    )
    );
    $singPost = get_posts( $singargs );
    foreach ( $singPost as $post ) : setup_postdata($post); ?>
    <aside>
        <h2><?php the_title(); ?></h2>
    </aside>
    <?php endforeach; wp_reset_postdata(); ?>
    
  2. Why don’t just use something like :

    $args = array('category' => 1 );
    $all_posts = get_posts( $args);
    foreach ($all_posts as $this_post) {
        if ( has_post_format( 'aside' ) ) {
            echo '<aside><h2>' . $this_post->title . '</h2></aside>';
            break;
            }
    }
    

    Could be some mistake in the code, but the idea is to first get the posts in wanted category, then parse it and take the first post that has the wanted post format (in case you couldn’t make your code work).

    Sorry if i’m wrong !