skip to Main Content

How to filter posts by year, by a custom field?

$args = array(
    'post_type'   => 'movies',
    'showposts'   => '28',
    'meta_value' => array( 'release_date' =>  '2021-09-01', ),          );

2

Answers


  1. You probably need something along the meta query lines:
    See WP_Meta_Query

    $args = array(
                  'post_type' => 'movies',
                  'post_status' => 'publish',
                  'posts_per_page' => -1,
                  'orderby'   => 'release_date',
                  'order'     => 'ASC',
                  'meta_query'  => array(
                    'relation' => 'AND',
                    array(
                      'key'   => 'release_date',
                      'value'     => '2021-09-01',
                      'compare'   => '=',
                      'type' => 'DATE'
                    ),
                  )
                );
    
    Login or Signup to reply.
  2. Just use the global $wpdb to execute your custom DB query.

    It should be something like that:

    SELECT p.ID, m.meta_value as post_year FROM wp_posts p INNER JOIN wp_postmeta m ON (p.ID = m.post_id and m.meta_key = 'release_date') WHERE p.post_type = 'movies' and 'publish' ORDER BY m.meta_value DESC;

    And on the PHP side you may use something like code below:

    global $wpdb;

    $results = $wpdb->get_results( $query, 'ARRAY_A' );

    Or use WP_Meta_Query. But i believe that it might be resolved as simple DB-request without extra helper classes.

    if you know mysql well you will able to customize that request easily for your aims.

    Wish you luck.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search