如何将自定义分类法附加到Wordpress中的帖子?

问题描述 投票:0回答:2

A在数据库中有很多带有自定义帖子类型的帖子。同时主题创建了分类学机构:

function my_taxonomies_institutions() {
    $labels = array(
        'name'              => _x( 'Category', 'taxonomy general name' ),
        'singular_name'     => _x( 'Category', 'taxonomy singular name' ),
        // and tothers
    );
    $args = array(
        'labels'             => $labels,
        'hierarchical'       => true,
        'show_admin_column'  => true,
        'rewrite'            => array( 'hierarchical' => true, 'slug' => 'institutions' ),
    );
    register_taxonomy( 'institutions', 'institution', $args ); 
}
add_action( 'init', 'my_taxonomies_institutions', 0 );

好的,管理区域中有一个菜单项Instituitions,还有一些类别,例如 - Sections。现在为了动画为这个分类法构建的主题,我需要浏览所有帖子并根据它的post_type将Instituitions术语附加到帖子。

print term_exists('sections'); // 7

我尝试了以下内容

$ret = wp_set_post_terms($pid, 7, 'institution');
$ret = wp_set_post_terms($pid, 'sections', 'institution');

但结果是

WP_Error Object([errors] => Array([invalid_taxonomy] => Array([0] =>无效的分类法。))[Error_data] => Array())

我做错了什么?

wordpress custom-taxonomy
2个回答
1
投票

您注册了名称为institutions的分类法,但错误地使用了institution,因此te error [invalid_taxonomy]。它应该是这样的

$ret = wp_set_post_terms($pid, array(7,), 'institutions');
$ret = wp_set_post_terms($pid, array('sections',), 'institutions');

要将term_id = 7这个术语“sections”分配给institution类型的所有帖子,请执行类似的操作

$posts = get_posts(array(
  'post_type' => 'institution',
  'post_status' => 'publish',
  'posts_per_page' => -1
));

foreach ( $posts as $post ) {
   wp_set_post_terms( $post->ID, array(7,), 'institutions');
   // OR 
   // wp_set_post_terms( $post->ID, array ('sections',), 'institutions');
}

我希望这会奏效。请查看this codex页面了解更多信息。


0
投票

尝试类似的东西:

$posts = get_posts([
  'post_type' => 'institution',
  'post_status' => 'publish',
  'numberposts' => -1
]);

foreach ( $posts as $post ) {
   wp_set_post_terms( $post->ID; array( ), 'institutions');
}

如果你想通过id wp_set_post_terms,你应该使用wp_set_post_terms( $post->ID; array( $id ))而不是wp_set_post_terms( $post->ID; $id)看看here

© www.soinside.com 2019 - 2024. All rights reserved.