查询unctions.php中的帖子并更新字段

时间:2019-06-22 作者:Gregory Schultz

我在中查询帖子时遇到问题functions.php. 这主要是在后端更新帖子,而不是在前端显示查询。我正在尝试获取所有使用状态帖子格式的帖子,如果变量为true,则更新一个元字段。

我的代码:

function status_alerts($query) { //start function
global $post; // set the global
$args = array( // all posts in the status post format
    \'posts_per_page\' =>  -1,
    \'taxonomy\' => \'post_format\',
    \'field\' => \'slug\',
    \'terms\' => array( \'post-format-status\' ),
    \'operator\'=> \'IN\'
);
$alert_query = new WP_Query( $args ); while ( $alert_query->have_posts() ) : $alert_query->the_post(); //query post
    if (get_post_meta( $post_id, \'breaking_news_status\', true ) == \'active\') { // if the post has a meta field called \'active\'
        if ((get_post_meta($post_id, \'status_time_duration\', true) + + get_the_time(\'U\')) < date( \'U\', current_time( \'timestamp\', 0 ) )) { // if the \'status_time_duration\' plus the publish date is greater than the current time
            update_post_meta($post_id, \'breaking_news_status\', \'archive\'); // add a check to \'archive\' to \'breaking_news_status\'
        }
    }
endwhile;
}

1 个回复
最合适的回答,由SO网友:Chetan Vaghela 整理而成

你必须用get_the_id()替换$post_id;

function status_alerts($query) { //start function
  global $post; // set the global
  $args = array( // all posts in the status post format
    \'posts_per_page\' =>  -1,
    \'taxonomy\' => \'post_format\',
    \'field\' => \'slug\',
    \'terms\' => array( \'post-format-status\' ),
    \'operator\'=> \'IN\'
  );
   $alert_query = new WP_Query( $args ); while ( $alert_query->have_posts() ) : $alert_query->the_post(); //query post
    if (get_post_meta( get_the_ID(), \'breaking_news_status\', true ) == \'active\') { // if the post has a meta field called \'active\'
        if ((get_post_meta(get_the_ID(), \'status_time_duration\', true) + + get_the_time(\'U\')) < date( \'U\', current_time( \'timestamp\', 0 ) )) { // if the \'status_time_duration\' plus the publish date is greater than the current time
            update_post_meta(get_the_ID(), \'breaking_news_status\', \'archive\'); // add a check to \'archive\' to \'breaking_news_status\'
        }
    }
  endwhile;
  wp_reset_query();
}

相关推荐

如何为class-wp-query.php追踪这些PHP通知和警告的原因?

我的WordPress调试。日志文件中充满了这些PHP通知,间隔大约15分钟,然后是几个小时…[23-Mar-2018 05:33:00 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3736 [23-Mar-2018 05:33:00 UTC] PHP Notice: Trying to get p