Forums

[resolved] Custom Query Help (3 posts)

  1. apascal
    Member
    Posted 2 years ago #

    I am trying to make a custom Query in WordPress for posts that have a certain custom field, for example “vid” = true. I only want to display one post, but it doesn’t have to be the most recently posted post. It has to be the most recent post that has the meta value, but there can be dozens of posts with this meta value.

    My question is, how can I filter out posts that don’t have this meta value and only display the most recent one? The problem I’m facing now is that the custom Query is taking the last post that was published, whether it has this meta value or not.

    I would really really appreciate any help. Thanks. :)

  2. MichaelH
    Volunteer
    Posted 2 years ago #

    <?php
    $args=array(
      'cat' => $cat_id,
      'meta_value'=> 'your value here',
      'meta_key'=>'your meta key here',
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => 1,
      'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      echo 'List of Posts';
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>
  3. apascal
    Member
    Posted 2 years ago #

    Works like a charm! Thanks so much!

Topic Closed

This topic has been closed to new replies.

About this Topic