我如何才能获得一些帖子元数据,同时它仍在插入?

时间:2014-01-24 作者:user1280853

我试图创建一个函数,其中某个帖子类型的子帖子继承与其父帖子相同的标题和slug。我使用WP类型来定义我的帖子类型及其关系。但我对以下代码有问题:

function copy_parent_post_title( $post_id ) {

    $new_post = get_post($post_id);

    if($new_post->post_type == \'carnews-adverts\') {

        $parent_id = get_post_meta( $post_id, \'_wpcf_belongs_carnews_id\', true );
        $parent_title = get_the_title($parent_id);
        $post_slug = sanitize_title_with_dashes($parent_title);

        $post_update = array(
            \'ID\'           => $post_id,
            \'post_title\' => $parent_title,
            \'post_name\' => $post_slug
        );

        remove_action( \'wp_insert_post\', \'copy_parent_post_title\' );
        wp_update_post( $post_update );
        add_action( \'wp_insert_post\', \'copy_parent_post_title\' );

    }

}
add_action( \'wp_insert_post\', \'copy_parent_post_title\' );
问题是这一行:

$parent_id = get_post_meta( $post_id, \'_wpcf_belongs_carnews_id\', true );
我想这是因为此时该帖子的元数据尚未插入数据库?如果是这样的话,如何在插入帖子时访问get\\u post\\u meta来实现我想要的?

谢谢

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

也许你可以把所有的逻辑转移到added_post_meta &;\'updated_postmeta\' 挂钩。

add_action( \'added_post_meta\', \'update_carnews_adverts_aprent\', 10, 4 );
add_action( \'updated_postmeta\', \'update_carnews_adverts_aprent\', 10, 4 );

function( $meta_id, $object_id, $meta_key, $meta_value ) {
  if ( $meta_key !== \'_wpcf_belongs_carnews_id\' || ! is_numeric($meta_value) ) return;
  $post = get_post( $object_id );
  if ( $post instanceof WP_Post && $post->post_type == \'carnews-adverts\' ) {
    $parent = get_post( $meta_value );
    if ($post->post_title !== $parent->post_title || $post->post_name !== $parent->post_name) {
       $post_update = array(
          \'ID\'         => $post->ID,
          \'post_title\' => $parent->post_title,
          \'post_name\' => $parent->post_name
       );
       wp_update_post( $post_update );
    }
  }
}

结束

相关推荐

Custom Post Row Actions

我偶然发现this question 在写这个问题的时候。我有一个问题是关于这个问题的。我发现你用的是get_delete_post_link 筛选为我的操作创建一个新的url(或一个类似的函数——在任何情况下,我都会将该函数与布尔值一起使用)。唯一的问题是,I don\'t know how to capture the event now. 考虑到我在谷歌上找不到很多关于行后操作的例子,我将不胜感激-/public function _wp_filter_get_delete_post_link( $