使用wp_Update_post在保存帖子时更新和添加标签帖子


Update and Add tags post on save post using wp_update_post

我正在尝试构建一个函数,用于保存帖子wp_update_post,以添加用逗号分隔的标记,如代码中所示

//Create the post array
$post = array(
'ID' => 5,
'tags_input' => 'foo,bar,baz');     
// Update the post
wp_update_post($post);

该代码在我的function.php主题中运行良好,但我希望启动一个函数,使其仅在帖子或使用add_filter ('wp_update_post','');save_post('wp_update_post,''); 创建新帖子的版本中运行

我试着做这个

function add_tags($post) {
    global $post;
    $idpost = $post->ID;
    $tags = 'tag1, tag2, tag3, tag4';
    $post = array(
    'ID' => $idpost,
    'tags_input' => $tags);     
    wp_update_post($post);
    return $post;
}
add_filter( 'wp_update_post', 'add_tags');
save_post( 'wp_update_post', 'add_tags');

在之间放入而不是运行到无限循环中

我可能做错了什么

已解决:

function my_function(){
    if ( ! wp_is_post_revision( $post_id ) ){
        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'my_function');
        // update the post, which calls save_post again
        $post = array(
                'ID' => 5,
                'tags_input' => 'foo,bar,baz');  
        wp_update_post( $post );
        // re-hook this function
        add_action('save_post', 'my_function');
    }
}
// hook the function
add_action('save_post', 'my_function');