我正在为我的帖子创建输出微数据的函数。我想使用meta-keywords作为分类法,所以我需要将它们输出为逗号分隔的文本。
我尝试了this question here中的解决方案,但根本没有结果。
第一次尝试:
echo '<meta itemprop="keywords" content="';
$terms = get_the_term_list( $post->ID,', ' );
$terms = strip_tags( $terms );
echo $terms;
echo '"/>';第二次尝试:
$terms = get_the_term_list( $post->ID,', ' );
$terms = strip_tags( $terms );
echo '<meta itemprop="keywords" content="';
echo $terms;
echo '"/>';第三次尝试:
$terms = get_the_term_list( $post->ID,', ' );
$terms = strip_tags( $terms );
echo '<meta itemprop="keywords" content="';
$terms;
echo '"/>';所有的尝试都没有产生任何输出。你能告诉我有没有一种方法可以得到这样的输出:
<meta itemprop="keywords" content="category1,category2,tag1,tag2,tag3"/>提前谢谢。
发布于 2017-08-25 12:25:11
使用自定义字段而不是分类法。这是将附加信息添加到wordpress站点的正确方法。
请查看下面的链接。
https://developer.wordpress.org/reference/functions/get_post_meta/
发布于 2017-08-25 13:07:51
你的第三次尝试永远不会成功,因为你必须使用echo来打印出术语,但你的第一次尝试更接近。
问题是您没有正确使用get_the_term_list()。See the Codex -它一次只适用于一个分类法,并且您必须传入要获取其术语的分类法的名称。
您希望获取所有分类法的所有术语,因此首先需要获取所有分类法的列表,然后可以使用该列表来获取术语。
我还建议使用wp_get_post_terms(),因为它可以返回没有标签的名称。
$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 .'"/>';
}我还没有测试该代码,所以可能会有几个问题,但请让我知道,因为逻辑应该为您工作。
https://stackoverflow.com/questions/45873426
复制相似问题