简体   繁体   中英

How filter posts by Year on Wordpress

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', ),          );

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'
                ),
              )
            );

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM