Get the most recent post with a specific custom field – WordPress

Im trying to reduce the amount of multiple loops I have on the homepage of a magazine website.

I want to display a post with a specific custom field differently, however I only want the first post (most recent) with that custom field. I can achieve this by creating another loop but I would like it to be included in the loop below.

Read More

For example here is my query but I need a further condition for if (get_post_meta($post->ID, 'featured', true)): so it includes only the most recent post that meets this condition

 $fourth_query = new WP_Query($args4); 
 while($fourth_query->have_posts()) : $fourth_query->the_post();
 if (get_post_meta($post->ID, 'featured', true)):   
     get_template_part( 'content-opinion', get_post_format() );
 else :
     get_template_part( 'content', get_post_format() );
 endif;
 endwhile;
 wp_reset_postdata();

Related posts

Leave a Reply

2 comments

  1. The function get_post_meta() returns a value not a boolean, so you have to check if the custom field exist so try with the empty() function

    $fourth_query = new WP_Query($args4); 
     while($fourth_query->have_posts()) : $fourth_query->the_post();
     if (!empty(get_post_meta($post->ID, 'featured', true))):   
         get_template_part( 'content-opinion', get_post_format() );
     else :
         get_template_part( 'content', get_post_format() );
     endif;
     endwhile;
     wp_reset_postdata();
    
  2. you can merge two query

    <?php 
        $generalQuery               = new WP_Query($args); // there is your main query 
        $queryWithCustomField       = new WP_Query($args); // there is your query with custom post and posts_per_page = 1
        $queryWithCustomField->posts = $queryWithCustomField->posts + $generalQuery->posts; // merge it now
    
        if ( $queryWithCustomField->have_posts() ) : while ( $queryWithCustomField->have_posts() ) : $queryWithCustomField->the_post();
            echo "your first post is ";
        endwhile;
        else:
            echo "No post Found";
        endif;
     ?>