【问题标题】:Is there a way to make child posts inherit parent post terms?有没有办法让子帖子继承父帖子条款?
【发布时间】:2014-08-18 20:29:40
【问题描述】:

我有一些从父母到曾孙的自定义帖子。我为父帖子分配了一个自定义分类法中的术语,我希望所有子帖子都继承该术语。有没有办法做到这一点?否则,我将不得不对每个帖子应用该术语,这将是一项非常艰巨的任务。

【问题讨论】:

  • 研究this results
  • @brasofilo 感谢您的建议。但是,我在此处发布之前搜索了网络,但没有找到解决方案。
  • 好的。最好将此类信息添加到您的问题中,这样您就不会收到您已经尝试过的建议。

标签: wordpress


【解决方案1】:

我发现上面的代码很有用,并对其进行了调整,以便它可以将父级保存到子级,以防对任何人有用(这似乎更符合 OP 用例,因为每次添加父级时术语它会在保存时逐渐减少)

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 );


?>

【讨论】:

    【解决方案2】:

    如果您从 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 创建帖子,那么我真的不知道如何使它工作

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 2021-10-06
      • 1970-01-01
      相关资源
      最近更新 更多