Forums

How to query posts by their meta data (4 posts)

  1. rafapple
    Member
    Posted 1 year ago #

    I want to be able to query my posts by their meta-data.

    For example, I have posts that are being treated as events. These posts have a 'month' variable which I inserted via the 'more fields' plugin.

    This 'month' variable can be filled with values such as: January, February.. etc.

    I want to be able to get all posts that have the month variable equal to some value. Ex.: All posts where month='January'

    Thanks for reading!

  2. MichaelH
    Volunteer
    Posted 1 year ago #

    <?php
    $args=array(
      'meta_key'=>'month',
      'meta_value'=> 'January',
      '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. rafapple
    Member
    Posted 1 year ago #

    is it possible to simultaneously query by more than one meta_key ?

    Example: All posts where month='January' and year='2010'

  4. MichaelH
    Volunteer
    Posted 1 year ago #

    You'd have to resort to wpdb or retrieve all 2010 posts, then filter for January.

Topic Closed

This topic has been closed to new replies.

About this Topic