I have this cron set up to trash posts x days after it is posted. This works. Edit: Added my answer to my question.
add_action( 'wp', 'do_trash_ads' );
function do_trash_ads()
{
if ( ! wp_next_scheduled( 'delete_classifieds' ) )
wp_schedule_event( time(), 'daily', 'delete_classifieds' );
}
add_action( 'delete_classifieds', 'expire_posts' );
function expire_posts()
{
global $wpdb;
$daystogo = "14";
$post_ids = $wpdb->get_results( "
SELECT ID
FROM {$wpdb->posts}
WHERE post_type ='classifieds'
AND post_status = 'publish'
AND DATEDIFF(NOW(), post_date) > '{$daystogo}'
" );
foreach( $post_ids as $id )
{
$postid = $id->ID;
$my_post = array();
$my_post['ID'] = $postid;
$my_post['post_status'] = 'trash';
wp_update_post( $my_post );
}
}
What I would like to do: Include posts in the above function that are based on a meta field value (21 days is the default, but a user can select an earlier date).
I set up a 2nd cron to do this.
add_action( 'wp', 'do_trash_ads_user' );
function do_trash_ads_user()
{
if ( ! wp_next_scheduled( 'delete_ads_user' ) )
wp_schedule_event( time(), 'daily', 'delete_ads_user' );
}
add_action( 'delete_ads_user', 'expire_posts_user' );
function expire_posts_user()
{
global $wpdb;
$post_ids = $wpdb->get_results( "
SELECT ID
FROM {$wpdb->posts}
WHERE post_type ='classifieds'
AND post_status ='publish'
" );
foreach( $post_ids as $id )
{
$postid = $id->ID;
$expiration_value = get_post_meta( $postid, 'ecpt_ad-expire-date', true );
if( $expiration_value )
{
$todays_date = date( "Y-m-d" );
$today = strtotime( $todays_date );
$expiration_date = strtotime( $expiration_value );
if ( $expiration_date > $today )
{
}
else
{
$my_post = array();
$my_post['ID'] = $postid;
$my_post['post_status'] = 'trash';
wp_update_post( $my_post );
}
}
}
}
I don't know if this is the best method but it is working.
$wpdb->prepare()
, which has several examples here on WP.SE. Than theres also
wp_update_post()` andwp_insert_post()
.prepare()
method that tell you exactly how and when to use it. To avoid duplication I'll let you read the existing answers :)