首页 > 解决方案 > 如何将自定义帖子分类名称仅放入数组?

问题描述

我在 wordpress 中有自定义帖子类型。自定义帖子有分类法。

<?php
    $customQuery = new WP_Query([
        'post_type' => 'custom'
    ]);
    while ($customQuery->have_posts()) {
        $customQuery->the_post();
        print_r(the_taxonomies());
    }
?>

结果

Array
(
    [portfolio_tag] => Taxonomies: <a href="http://localhost/wordpress/custom_tag/app/">App</a> and <a href="http://localhost/wordpress/custom_tag/developer/">Developer</a>.
)

如何让所有分类名称在wordpress中排列?

Array
(
   'App',
   'Developer'
)

标签: phparrayswordpresstaxonomy

解决方案


您可以使用wp_get_object_termswp_get_post_terms如果它不起作用,那么您将功能替换wp_get_object_termswp_get_post_terms

in wp_get_object_termsandwp_get_post_terms函数有 2 个参数,第一个是 post id,第二个是 custom-taxonomy-name,所以你可以在这里传递第二个参数

为了知识

https://codex.wordpress.org/Function_Reference/wp_get_post_terms

https://codex.wordpress.org/Function_Reference/wp_get_object_terms

<?php
    $customQuery = new WP_Query([
        'post_type' => 'custom'
    ]);
    while ($customQuery->have_posts()) {
        $customQuery->the_post();
        $arr_get_terms = wp_get_object_terms($customQuery->ID, 'custom-taxonomy-name-here');
        print_r($arr_get_terms);
    }
?>

推荐阅读