【问题标题】:How to attach custom taxonomy to a post in Wordpress?如何将自定义分类法附加到 Wordpress 中的帖子?
【发布时间】:2019-02-22 17:11:30
【问题描述】:

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,还有一些类别,例如 - 部分。现在,为了使为此分类法构建的主题动画化,我需要浏览所有帖子,并根据帖子的 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 对象 ( [errors] => 数组 ( [invalid_taxonomy] => 数组 ( [0] => Неверная таксономия. ) ) [error_data] => 数组 ( ) )

我做错了什么?

【问题讨论】:

标签: wordpress custom-taxonomy


【解决方案1】:

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

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

要将带有term_id = 7 的术语“部分”分配给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 页面了解更多信息。

【讨论】:

    【解决方案2】:

    尝试类似:

    $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

    【讨论】:

      猜你喜欢
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2011-11-19
      • 2012-05-01
      • 1970-01-01
      • 2013-08-04
      相关资源
      最近更新 更多