0

I have a custom field called date started on my custom post type, I even added a datepicker. Now I want to search post according to some dates. Usually I would use sql functions to find dates between some days but I have no idea how to search for a date given in a custom field.

1

You need to use WP_Query for getting the posts which match your query.

And in WP_Query you need to use the following:

    'meta_query'        => array(
            'meta_key'          => 'date_started', // change it to your custom field meta_key
            'type'              => 'DATE',  // You can also try changing it to TIME or DATETIME if it doesn't work
            'meta_value'        => '2017-05-23', // Replace with your preferred value
            'meta_compare'      => '=',
),

Complete code would look something like:

<?php
$post_query = new WP_Query(
    array(
        'post_type'         => 'post',
        'posts_per_page'    => 1,
        'meta_query'        => array(
            'meta_key'          => 'date_started', // change it to your custom field meta_key
            'type'              => 'DATE',  // You can also try changing it to TIME or DATETIME if it doesn't work
            'meta_value'        => '2017-05-23', // Replace with your preferred value
            'meta_compare'      => '=',
        ),
    )
);

if($post_query->have_posts()) : while($post_query->have_posts()) : $post_query->the_post();

the_title(); // Print the title of found post

endwhile;
endif;
wp_reset_postdata();

?>
  • array( 'key' => 'fecha_inicial', 'value' => $fecha, 'compare' => '=', 'type' => 'DATE' / ), – Juan Diego May 24 '17 at 2:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.