如何解决Wordpress get_posts() 仅显示用户配置文件中自定义帖子的部分正确数据
我有一个基于 wordpress 的网站,我正在尝试移动一些以前只是普通 MysqL 表的自定义功能,以及一些用于插入/更新/显示内容的代码。我正在尝试将它作为自定义帖子合并到 WP 中,以便我可以使用过滤器、标签、分页等。
它应该在用户个人资料中显示一些自定义项目(终极会员)。比如,用户信息,然后是 10 个用户最喜欢的此类项目,然后在下一个选项卡上有 10 个其他类型的项目,等等。
但似乎 WP 中的事情并不那么简单,您不能只是将事物相互重叠并期望它们不会重叠。 >_> 因此,当我尝试添加一个包含自定义帖子类型数据的块时,它仅返回一些与配置文件数据混合的数据,而这些数据混合了虚无。
是的,我明白了,据我从手册中了解到,可能有一个配置文件循环和一些数据已经存在于变量中。我无法理解的是如何修复它。这是它的外观:
$args = array(
'author' => $uid,'numberposts' => 10,'post_type' => 'ff',);
$ff = get_posts($args);
if($ff){
foreach($ff as $f){
setup_postdata($f);
the_content(); //shows what's needed,as well as ID,the_time() and some more
the_title(); //shows author's name instead of post title
the_tags(); //shows nothing,as well as excerpt,etc
get_the_excerpt(); //still nothing
$f->post_excerpt; //but this shows the excerpt,as well as print_r($f)
}
wp_reset_postdata();
}
也许有人可以提示我错过了什么?提前致谢!
解决方法
尝试使用帖子 ID 获取您的数据并进行回显。多一点代码,但可能效果更好。
// Set the global post up here
global $post;
$args = array(
'author' => $uid,'numberposts' => 10,'post_type' => 'ff',);
$ff = get_posts($args);
if($ff){
foreach($ff as $f){
setup_postdata($f);
$id = $f->ID; // get post ID
$content = get_the_content($id); // get the content to echo later
$tags = get_the_tags($id); // use to get tags,these are not part of the get_posts return object
echo $content; // show the content
echo $f->post_title; // show the returned post title. can use get_the_title($id) and echo it if this does not work
// Display the tags after getting them above
foreach ($tags as $tag) {
echo $tag->name . ',';
}
// You can get the excerpt this way too but you said your other worked okay
$excerpt = get_the_excerpt($id);
echo $excerpt;
}
wp_reset_postdata();
}
(原文)详细说明。这将设置全局 post 对象。这通常是您的函数在循环中工作的要求。我多年来发现的情况并非总是如此,但如果您没有在循环中使用帖子 ID 来获取数据,那么这是一个很好的做法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。