我有一些自定义帖子,从父母到伟大的孩子。我为父帖子分配了一个自定义分类的术语,我希望所有子帖子都可以继承。有没有办法做到这一点?否则,我将不得不将该术语应用于每个帖子,这将是一项非常艰巨的任务。
答案 0 :(得分:1)
我发现上面的代码很有用,并对其进行了调整,以使其可以将父级保存到子级,以防对任何人有用(这似乎更符合OP用例,因为每次他们添加父级时学期,它将在保存时save流下来)
function set_child_terms( $post_id, $post ) {
$args = array(
'post_parent' => $post_id,
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'any'
);
$children = get_children( $args );
if ( 'publish' === $post->post_status && $children > 0 ) {
foreach( (array) $children as $child) {
if(!empty($child)){
$taxonomies = get_object_taxonomies( $post->post_type );
foreach ( (array) $taxonomies as $taxonomy ) {
$terms = wp_get_post_terms( $post->ID, $taxonomy );
if ( !empty( $terms ) ) {
$termArr = array_map(create_function('$obj', 'return $obj->term_id;'), $terms);
$tmp = wp_set_object_terms( $child->ID, $termArr, $taxonomy, false ); // set to true if you don't want to overwrite/reset existing terms
}
}
} }
}
}
add_action( 'save_post', 'set_child_terms', 100, 2 );
?>
答案 1 :(得分:0)
如果您从wordpress ui创建帖子,只需将其添加到您的functions.php中,它就会满足您的需求:
function set_parent_terms( $post_id, $post ) {
if ( 'publish' === $post->post_status && $post->post_parent > 0 ) {
$parent = get_post($post->post_parent);
if(!empty($parent)){
$taxonomies = get_object_taxonomies( $parent->post_type );
foreach ( (array) $taxonomies as $taxonomy ) {
$terms = wp_get_post_terms( $parent->ID, $taxonomy );
if ( !empty( $terms ) ) {
$termArr = array_map(create_function('$obj', 'return $obj->term_id;'), $terms);
$tmp = wp_set_object_terms( $post_id, $termArr, $taxonomy, true );
}
}
}
}
}
add_action( 'save_post', 'set_parent_terms', 100, 2 );
如果您使用wp_insert_post
创建帖子,那么我真的不知道如何让它发挥作用