Support

Account

Home Forums General Issues How to list posts by custom field in sidebar

Helping

How to list posts by custom field in sidebar

  • I want to list all posts containing the same day and month in its’ acf value as todays day and month, as a list of posts in sidebar.php. So, for example, if I have 3 posts with a acf value of 26102013 and today it is 26102016, I want to list only these 3 posts and not the others which do not contain that same day and month (2610) of the year. Kind of “It happened on this day in history”.

    So, after reading the forum I ended up trying to get an array of such posts, where I defined it something like this:

    //todays day and month
    $dm = date('dm');
    
    //acf values for 'date_of_death', formatted only as days and months, not years
    $format_in = 'Ymd';
    $format_out = 'dm';
    $date = DateTime::createFromFormat($format_in, get_field('date_of_death'));
    
    //find all such posts which contain same day and month in date_of_death value as in $dm
    
    $args = array (
        'posts_per_page'  => -1,
        'post_type' => 'post',
        'meta_query' => array(
        array(
              'key'   => 'date_of_death',
              'value'   => $dm,
              'relation' => 'LIKE'
          )
        ),
    );
    
    //and display them in a list
    if( $posts): ?>
        <ul>
        <?php foreach( $posts as $post ): 
          setup_postdata( $post )
          ?>
            <a href="<?php the_permalink(); ?>"><?php the_title();?></a>
        <?php endforeach; ?>  
        </ul>  
        <?php wp_reset_postdata(); ?>
      <?php endif; ?>

    I am not getting desired results. Can someone explain me what am I doing wrong?

    Thank you very much.

  • On your meta_query, the key for defining the comparison type should be ‘compare’, not ‘relation’.

    WP_Meta_Query

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘How to list posts by custom field in sidebar’ is closed to new replies.