首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将Wordpress Taxonomy输出为文本,然后将其用作元关键字?

如何将Wordpress Taxonomy输出为文本,然后将其用作元关键字?
EN

Stack Overflow用户
提问于 2017-08-25 10:11:40
回答 2查看 465关注 0票数 1

我正在为我的帖子创建输出微数据的函数。我想使用meta-keywords作为分类法,所以我需要将它们输出为逗号分隔的文本。

我尝试了this question here中的解决方案,但根本没有结果。

第一次尝试:

代码语言:javascript
复制
echo '<meta itemprop="keywords" content="';
$terms = get_the_term_list( $post->ID,', ' );
$terms = strip_tags( $terms );
echo $terms;
echo '"/>';

第二次尝试:

代码语言:javascript
复制
$terms = get_the_term_list( $post->ID,', ' );
$terms = strip_tags( $terms );
echo '<meta itemprop="keywords" content="';
echo $terms;
echo '"/>';

第三次尝试:

代码语言:javascript
复制
$terms = get_the_term_list( $post->ID,', ' );
$terms = strip_tags( $terms );
echo '<meta itemprop="keywords" content="';
$terms;
echo '"/>';

所有的尝试都没有产生任何输出。你能告诉我有没有一种方法可以得到这样的输出:

代码语言:javascript
复制
<meta itemprop="keywords" content="category1,category2,tag1,tag2,tag3"/>

提前谢谢。

EN

回答 2

Stack Overflow用户

发布于 2017-08-25 12:25:11

使用自定义字段而不是分类法。这是将附加信息添加到wordpress站点的正确方法。

请查看下面的链接。

https://developer.wordpress.org/reference/functions/get_post_meta/

https://codex.wordpress.org/Custom_Fields

票数 0
EN

Stack Overflow用户

发布于 2017-08-25 13:07:51

你的第三次尝试永远不会成功,因为你必须使用echo来打印出术语,但你的第一次尝试更接近。

问题是您没有正确使用get_the_term_list()See the Codex -它一次只适用于一个分类法,并且您必须传入要获取其术语的分类法的名称。

您希望获取所有分类法的所有术语,因此首先需要获取所有分类法的列表,然后可以使用该列表来获取术语。

我还建议使用wp_get_post_terms(),因为它可以返回没有标签的名称。

代码语言:javascript
复制
$term_names = array(); // array to store all names until we're ready to use them

// get all taxonomies for the current post
$taxonomy_names = get_object_taxonomies( $post );

foreach ($taxonomy_names as $taxonomy){      
    // get the names of all terms in $taxonomy for the post
    $term_list = wp_get_post_terms($post->ID, $taxonomy, array("fields" => "names"));

    // add each term to our array
    foreach($term_list as $term){
        $term_names[] = $term;
    }
}

if ($term_names){ // only display the metatag if we have any terms for this page
    // implode will join all the terms together separated by a comma
    $keywords = implode(",", $term_names);
    echo '<meta itemprop="keywords" content="'.$keywords .'"/>';
}

我还没有测试该代码,所以可能会有几个问题,但请让我知道,因为逻辑应该为您工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45873426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档