2017-04-20 42 views
0

我需要在template-part中使用the_title()和其他函數!index.php中的wp_get_recent_posts

在我的index.php我有:

$args=array(
    'orderby' => 'post_date', 
    'order' => 'DESC' 
); 
$recent_posts =wp_get_recent_posts($args,ARRAY_A); 
foreach ($recent_posts as $post) { 

    setup_postdata($post); 
    echo "<h1>$post[ID]</h1>"; 
    the_title(); 
    get_template_part('template-parts/post/content', 'list'); 
} 

回波顯示正確後ID's。 但是,the_title():總是顯示「hello world」(第一篇文章), 因此,我的模板部分只有不是來自$ recent_posts的第一個Post Object。

怎麼了?

+0

模板部分是使用許多the_功能,如the_title()......我不希望重寫呼應$數據[「標題」] – user992154788

回答

0

試試下面的foreach代碼:

foreach ($recent_posts as $post) { 

setup_postdata($post); 
echo "<h1>$post[ID]</h1>"; 
echo $post["post_title"]; 
get_template_part('template-parts/post/content', 'list'); 
} 
0

首先,通過一些參數在帖子中查詢關鍵詞,比如,

'post_type'  => 'post', 
'post_status'  => 'publish', 

到澄清你想要顯示你的帖子的帖子類型。 循環變化的內部,

the_title(); 

成,

$post->post_title or $post['post_title'] 

取決於數據通過對象或數組獲取。

我希望這會對你有用。

0

好的,我發現它。 對於那些瞭解我真正的問題:

不要使用wp_get_recent_posts。 相反:

$the_query = new WP_Query('posts_per_page=10'); 
while ($the_query -> have_posts()) { 
    $the_query -> the_post(); 
    get_template_part('template-parts/post/content', 'list'); 
}