【问题标题】:Delete expired posts in wordpress by date meta data custom field按日期元数据自定义字段删除 wordpress 中过期的帖子
【发布时间】:2014-12-09 18:26:18
【问题描述】:

---已解决:代码如图所示---

我有这段我认为应该可以工作的代码,但是唉......

如果有人可以偷看一下,看看是否有明显的东西。我查看了很多关于 wordpress codex 的资源,但是我已经尝试了所有我能想到的。

// expired_post_delete hook fires when the Cron is executed

add_action( 'expired_post_delete', 'delete_expired_posts' );

// This function will run once the 'expired_post_delete' is called

function delete_expired_posts() {

$todays_date = current_time('mysql');

$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'meta_key' => 'date',
    'meta_query' => array(
        array(
            'key' => 'date',
            'value' => $todays_date,
            'type' => 'DATE',
            'compare' => '<'
            )
    )
);
 $posts = new WP_Query( $args );

// The Loop
if ( $posts->have_posts() ) {

    while ( $posts->have_posts() ) {
        $posts->the_post();
        wp_delete_post(get_the_ID());
    }

} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
}

// Add function to register event to WordPress init
add_action( 'init', 'register_daily_post_delete_event');

// Function which will register the event
function register_daily_post_delete_event() {
// Make sure this event hasn't been scheduled
if( !wp_next_scheduled( 'expired_post_delete' ) ) {
    // Schedule the event
    wp_schedule_event( time(), 'daily', 'expired_post_delete' );
    }
}

【问题讨论】:

  • 你试过'value' =&gt; $todays_date(不带引号)吗?
  • 做了那个更新,还是没有生成,非常感谢!

标签: date custom-fields wordpress


【解决方案1】:

the_date() 需要在循环中使用。在循环之外,它将返回 null。请改用current_time()

$todays_date = current_time('mysql'); // returns YYYY-MM-DD HH:MM:SS

【讨论】:

  • 我尝试了您的建议,但仍然没有结果。我需要一种方法来查看要调试的值,不知道代码在哪里发生故障……真是一团糟。哈哈。尽管如此,还是感谢您的提示。我需要截断 current_time() 的时间吗?或者如果我比较一个日期会知道忽略时间?再次感谢!
  • post meta 中存储的日期格式是什么?
  • 日期存储为 YYYY-MM-DD,复制自帖子:2014-12-01
  • 贝基 谢谢你的帮助。你的建议让我对日期问题感到放心,这是最不用担心的一件事。最后一个错误很愚蠢...没有正确创建 WP_Query 对象的实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
相关资源
最近更新 更多