我试图创建一个函数,其中某个帖子类型的子帖子继承与其父帖子相同的标题和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来实现我想要的?
谢谢
最合适的回答,由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 );
}
}
}