所以我试图输出一个包含来自同一类别的3个帖子的循环。它似乎正在正确地拉动所有除了,当它输出每个项目的循环时,只有get_the_content是正确的。其他数据(图像,标题,链接)正在输出当前帖子的值。
所以基本上我需要让这个循环获得the_post_thumbnail和the_title以及get_permalink的正确值。
<?php
/**
* The template used for displaying page content
*
* @package WordPress
* @subpackage Twenty_Fifteen
* @since Twenty Fifteen 1.0
*/
?>
<?php
$related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 3, 'post__not_in' => array($post->ID) ) );
if( $related ) {
?>
<div class="related-posts">
<h2>Related Posts</h2>
<?php foreach( $related as $related_post ) {
setup_postdata($related_post);
?>
<article>
<div class="post-thumbnail">
<?php the_post_thumbnail('thumbnail'); ?>
</div><!-- .post-thumbnail -->
<?php the_title( '<h3>', '</h3>' ); ?>
<p>
<?= wp_trim_words( get_the_content(), 10, '<a href="'. get_permalink() .'"> Read More...</a>' ); ?>
</p>
</article>
<?php
}
?>
</div>
<?php
}
wp_reset_postdata();
?>
答案 0 :(得分:2)
由于setup_postdata
功能,您正面临问题。此函数将对象作为参数,它应为$post
。
查看文档。 https://codex.wordpress.org/Function_Reference/setup_postdata
<?php
$related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 3, 'post__not_in' => array($post->ID) ) );
if( $related ) {
?>
<div class="related-posts">
<h2>Related Posts</h2>
<?php
global $post;
foreach( $related as $post ) {
setup_postdata($post);
?>
<article>
<div class="post-thumbnail">
<?php the_post_thumbnail('thumbnail'); ?>
</div><!-- .post-thumbnail -->
<?php the_title( '<h3>', '</h3>' ); ?>
<p>
<?= wp_trim_words( get_the_content(), 10, '<a href="'. get_permalink() .'"> Read More...</a>' ); ?>
</p>
</article>
<?php
}
?>
</div>
<?php
}
wp_reset_postdata();
?>