0

我想做一个 cron 作业,女巫删除帖子自定义字段中所有早于日期的帖子。我的functions.php中有以下函数我的自定义字段名称是bewerbungs_frist

    function foobar_truncate_posts(){
    global $wpdb;

    $currenttime = new DateTime();
    $currenttime_string = $currenttime->format('Ymd');

    # Set your threshold of max posts and post_type name
    $post_type = 'job';

    # Query post type
    $query = "
        SELECT ID FROM $wpdb->posts
        WHERE post_type = '$post_type'
        AND post_status = 'publish'
        ORDER BY post_modified DESC
    ";
    $results = $wpdb->get_results($query);

    # Check if there are any results
     if(count($results)){
            foreach($results as $post){

                $customfield = get_field('bewerbungs_frist', $post->ID);
                $customfield_object = new DateTime($customfield);
                $customfield_string = $customfield_object->format('Ymd');


                if ( $customfield_string < $currenttime_string ) {

                    echo "The value of the custom date field is in the past";
                    echo $customfield_string;


                    $purge = wp_delete_post($post->ID);
                }
            }
        }

}

foobar_truncate_posts();

我使用插件来处理我的 cronjobs。Hock 的名字是:foobar_truncate_posts和 Arguments 是[]

cronjob 有效,但不会删除自定义字段日期早于今天日期的帖子。这两个变量是一样的。

$currenttime_string20130820 $customfield_string20130820

4

1 回答 1

1

您的代码中有一个错字,您在$result.

这个:

  foreach($result as $post){

应该是这样的:

  foreach($results as $post){

我刚试了一下。一旦你修复了 wp_delete_post() 就可以了。


编辑


我真的不清楚你想做什么。您想检查自定义字段是否设置为过去的某个时间?服务的目的是什么continue?另外,我猜您正在使用高级自定义字段 (ACF)。使用 jquery 日期选择器,您可以将日期格式化为Ymd默认格式,因此您不必将其转换为 DateTime 对象。

无论如何,这个函数应该解释如何正确设置和比较时间值,你应该能够从那里得到它:

function foobar_truncate_posts(){
    global $wpdb;

    $currenttime = new DateTime();
    $currenttime_string = $currenttime->format('Ymd');

    # Set your threshold of max posts and post_type name
    $post_type = 'post_type_job';

    # Query post type
    $query = "
        SELECT ID FROM $wpdb->posts
        WHERE post_type = '$post_type'
        AND post_status = 'publish'
        ORDER BY post_modified DESC
    ";
    $results = $wpdb->get_results($query);

    # Check if there are any results
     if(count($results)){
            foreach($results as $post){

                $customfield = get_field('bewerbungs_frist', $post->ID);
                $customfield_object = new DateTime($customfield);
                $customfield_string = $customfield_object->format('Ymd');

                if ( $customfield_string < $currenttime_string ) {

                    echo "The value of the custom date field is in the past";

                    $purge = wp_delete_post($post->ID);
                }
            }
        }

}

foobar_truncate_posts();
于 2013-08-18T00:27:52.337 回答