WordPress: Delete posts by using the date of a cus

2019-06-02 05:01发布

I'm using a Custom Post Type to show events on my site. The events have two custom fields for the start and the end date. The dates are stored in the following format: YYYY-MM-DD.

I'm using the field to sort the events in the frontend where I start with the next event based on the current date.

After this date, the events are not showing in the frontend anymore because they lie in the past.

Now I want to delete the events after the end date. Is there any way to do this?

I've found a nice solution from @pieter-goosen to delete posts after a number of days: https://wordpress.stackexchange.com/questions/209046/delete-expired-posts-after-a-number-of-days-after-they-expired

But I don't know how to use this function with a meta field.

Any ideas/hints?

My code:

function expirePastEvents() {

    $current_date_query = date ('Y-m-d');

    $postType = 'event'; // Change this to your post type name.
    $metaKeyName = 'gid_22'; // Change this to your meta key name for end date.
    $skipTrash = false; // Whether or not to skip the trash.

    $posts = new WP_Query([
        'post_type' => $postType,
        'fields' => 'ids',
        'post_status' => 'publish',
        'meta_query' => [
            [
                'key' => $metaKeyName,
                //'value' => current_time('timestamp'),
                'value' => $current_date_query,
                'compare' => '<='
            ]
        ]
    ]);

    foreach ($posts->posts as $post) {
        wp_delete_post($post->ID, $skipTrash);
    }
}



// expired_post_delete hook fires when the Cron is executed
add_action( 'expired_post_delete', 'expirePastEvents' );


// Add function to register event to wp
add_action( 'wp', 'register_daily_events_delete_event');
function register_daily_events_delete_event() {
    // Make sure this event hasn't been scheduled
    if( !wp_next_scheduled( 'expired_post_delete' ) ) {
        // Schedule the event
        wp_schedule_event( time(), 'hourly', 'expired_post_delete' );
    }
}

3条回答
来,给爷笑一个
2楼-- · 2019-06-02 05:22

Do the following steps:

  1. Install WP Control Plugin.
  2. Activate the plugin.
  3. Navigate to wp-admin/tools.php?page=crontrol_admin_manage_page and in Add Cron Event section add 'my_daily_event_delete' in the Hook Name tabs below.
  4. Save the event.

    Add the below code in the your functions.php file.

    add_action('my_daily_event_delete', '_delete_this_daily');
    
    function _delete_this_daily() {
      $past = strtotime( "- 1 day" );
      // Set our query arguments
      $args = [
        'fields'         => 'ids', // Only get post ID's to improve performance
        'post_type'      => 'event', // Post type
        'posts_per_page' => -1,
        'meta_query'     => [
            [
                'key'     => 'event_end_date', // Replace this with the event end date meta key.
                'value'   => $past,
                'compare' => '<='
            ]
        ]
      ];
      $q = get_posts( $args );
    
      // Check if we have posts to delete, if not, return false
      if ( !$q ) {
        return false;
      }
      // OK, we have posts to delete, lets delete them
      foreach ( $q as $id ){
          wp_delete_post( $id );
      }
    }
    
查看更多
走好不送
3楼-- · 2019-06-02 05:23

The link you provided shows you how to do this, you simply need to change some of the information in the answer to get it to work.

function expirePastEvents() {
    $postType = 'events'; // Change this to your post type name.
    $metaKeyName = 'end_date'; // Change this to your meta key name for end date.
    $skipTrash = false; // Whether or not to skip the trash.

    $posts = new WP_Query([
        'post_type' => $postType,
        'fields' => 'ids',
        'post_status' => 'publish',
        'meta_query' => [
            [
                'key' => $metaKeyName,
                'value' => current_time('timestamp'),
                'compare' => '<='
            ]
        ]
    ]);

    foreach ($posts->posts as $post) {
        wp_delete_post($post->ID, $skipTrash);
    }
}
查看更多
叼着烟拽天下
4楼-- · 2019-06-02 05:34

I found a solution

Here is my code:

function get_delete_old_events() {

    $past_query = date('Y-m-d', strtotime('-1 day'));

    // Set our query arguments
    $args = [
        'fields'         => 'ids', // Only get post ID's to improve performance
        'post_type'      => 'event', // Post type
        'posts_per_page' => -1,
        'meta_query'     => [
            [
                'key'     => 'gid_22', // Replace this with the event end date meta key.
                'value'   => $past_query,
                'compare' => '<='
            ]
        ]
      ];
    $q = get_posts( $args );

    // Check if we have posts to delete, if not, return false
    if ( !$q )
        return false;

    // OK, we have posts to delete, lets delete them
    foreach ( $q as $id )
        wp_trash_post( $id );
}

// expired_post_delete hook fires when the Cron is executed
add_action( 'old_event_delete', 'get_delete_old_events' );

// Add function to register event to wp
add_action( 'wp', 'register_daily_events_delete_event');

function register_daily_events_delete_event() {
    // Make sure this event hasn't been scheduled
    if( !wp_next_scheduled( 'old_event_delete' ) ) {
        // Schedule the event
        wp_schedule_event( time(), 'hourly', 'old_event_delete' );
    }
}

I've changed the argument wp_delete_post() to wp_trash_post() because wp_delete_post() only applies to native posts, pages, and attachments. Great answer from @rarst here: https://wordpress.stackexchange.com/questions/281877/error-after-deleting-custom-post-type-with-a-function-no-trash-used/281888#281888

查看更多
登录 后发表回答