Cause Custom Post Type to Expire by Date
-
I stumbled upon the query below while trying to find a way to cause a custom post type to expire on a set date. An expiry date is set only for posts of this custom type but when the function executes it hides ALL posts outside the custom type.
And rather than hiding the custom posts less than (<) today’s date, it shows them. When the sign is set to greater than (>) the dates are correctly hidden.
function my_filter_expired_posts( $query ) { // doesn't affect admin screens if ( is_admin() ) return; // check for main query if ( $query->is_main_query() ) { //filter out expired posts $today = date('Y-m-d H:i:s'); $metaquery = array( array( 'key' => 'end_date', 'value' => $today, 'compare' => '<', 'type' => 'DATE' ) ); $query->set( 'meta_query', $metaquery ); } } add_action( 'pre_get_posts', 'my_filter_expired_posts' );
I read the Codex and tried to use the AND condition to include the custom post type’s key value pair ending with the below function, but that results in all posts types being hidden (posts and custom posts):
function my_filter_expired_posts( $query ) { // doesn't affect admin screens if ( is_admin() ) return; // check for main query if ( $query->is_main_query() ) { //filter out expired posts $today = date('Y-m-d H:i:s'); $metaquery = array( array ( 'key' => 'post_type', 'value' => 'jobs', 'compare' => '=', 'type' => 'CHAR' ), 'relation' => 'AND', array( 'key' => 'end_date', 'value' => $today, 'compare' => '<', 'type' => 'DATE' ) ); $query->set( 'meta_query', $metaquery ); } } add_action( 'pre_get_posts', 'my_filter_expired_posts' );
The thing is, I really don’t know how the filter works so I can’t begin to imagine what conditions to set and how.
I thought limiting the query to the custom post types would be the first and best option rather than checking if ‘end_date’ is empty or somehow using the EXISTS/NOT EXISTS comparisons. See: https://codex.www.ads-software.com/Class_Reference/WP_Meta_Query
https://codex.www.ads-software.com/Plugin_API/Action_Reference/pre_get_postsI’d really appreciate your help.
Thanks.
- The topic ‘Cause Custom Post Type to Expire by Date’ is closed to new replies.