按标签获取相关帖子

时间:2015-02-17 12:38:37

标签: json wordpress wp-query

我整合了其他网站的所有帖子,并且我想显示其中一个帖子的相关帖子,但只显示相同自定义帖子类型的相关帖子 ...

因此,当我添加这些自定义帖子时,我添加自定义帖子元素,并且我将这些保存为json。例如:

meta_key =" post_tags";

meta_value =" [" tagA"," tagB"]&#34 ;;

但我无法获得相关帖子。我正在尝试:

global $post;
$tags = get_post_meta($post->ID, "post_tags", true); //this is the json

if ($tags) {
    $args=array(
    'meta_key' => 'post_tags',
    'meta_value' => $tags, // how compare with others posts???
    'post__not_in' => array($post->ID), //not the same post
    'posts_per_page'=>5, // Number of related posts to display.
    'caller_get_posts'=>1
);

$my_query = new wp_query( $args );

if($my_query->post_count > 0){
     ?> <h3>Related posts</h3> <?php
}else if($my_query->post_count == 0){
     ?> <h3>There is not related posts</h3> <?php
}

但它始终显示&#34;没有相关帖子&#34; ....当我有相同的帖子时使用相同的meta_key&post; post_tags&#39; ([&#34; TAGA&#34;&#34; TAGB&#34;])。

提前感谢,Daniel

1 个答案:

答案 0 :(得分:1)

首先,如果您添加'post_type'的查询参数,则只能返回自定义帖子类型的帖子。

其次,您可以制作自定义帖子类型支持帖子标签,然后当您整合其他帖子时,您只需使用...导入标签即可。

wp_set_post_terms( $post->ID, $tags );

如果您仍然希望按照自己的方式进行操作,将术语保存在元字段中,则需要将术语保存为PHP数组而不是JSON数组。在将其保存为元之前,请使用以下内容...

$php_terms = json_decode( $original_json, true );

...将json数组转换为php数组。然后你可以运行与上面相同的查询。问题是,在你查询了你的术语时,wordpress期待一个PHP数组,所以这应该可以解决你的问题。

希望有所帮助