根据元值更改帖子状态

时间:2013-03-10 作者:Michael B

我已经将这个cron设置为在发布x天后丢弃帖子。这是可行的。编辑:将我的答案添加到我的问题。

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: 在上述函数中包含基于元字段值的帖子(默认为21天,但用户可以选择更早的日期)。

我设置了第二个cron来执行此操作。

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 );
           }
        }
    }
}
我不知道这是否是最好的方法,但它正在发挥作用。

1 个回复
SO网友:Tim Hallman

您的代码看起来不错,而且考虑到您没有提交用户输入的数据,因此不需要prepare()方法,但作为一种最佳实践,最好了解它的工作原理并一致地使用它。

话虽如此,使用prepare()方法,您的代码如下所示:

$sql = $wpdb->prepare( "
  SELECT ID
  FROM %s
  WHERE post_type = \'classifieds\' 
  AND post_status = \'publish\'
  ", $wpdb->posts );

 $post_ids = $wpdb->get_results( $sql, ARRAY_A );
此外,您还可以从以下内容缩短if语句:

if ( $expiration_date > $today )
           { 

           }
           else
           { 
               $my_post = array();
               $my_post[\'ID\'] = $postid;
               $my_post[\'post_status\'] = \'trash\';

               wp_update_post( $my_post );
           }
收件人:

if ( $expiration_date < $today )
           { 
               $my_post = array();
               $my_post[\'ID\'] = $postid;
               $my_post[\'post_status\'] = \'trash\';
               wp_update_post( $my_post );
           }

结束