我目前正在从事一个项目,我正在用ajax加载一篇文章。我正在使用get_post() 为了得到这个职位,setup_postdata() 设置post数据,以及get_template_part() 加载包含所需标记的模板。我的函数如下所示:
public function get_content($url) {
global $post;
$post_id = url_to_postid($url);
if($post_id){
$post = get_post($post_id);
setup_postdata( $post );
ob_start();
get_template_part(\'template/page\', \'default\');
$content = ob_get_contents();
ob_end_clean();
wp_reset_postdata();
return array(\'status\' => \'success\', \'content\' => $content);
} else {
return array(\'status\' => \'error\',\'message\'=> \'Fant ikke post til relevante url..\');
}
die();
}
我的模板包含一个嵌套循环,用于显示基于类别的餐饮菜单。所以我用
get_categories() 获取所有包含帖子的类别,然后
get_posts() 显示父类别的帖子。我的模板如下所示:
<nav class="catering-nav">
<?php
$category_args = array(
\'type\' => \'menus\',
\'child_of\' => 0,
\'parent\' => \'\',
\'orderby\' => \'name\',
\'order\' => \'ASC\',
\'hide_empty\' => 1,
\'hierarchical\' => 1,
\'exclude\' => \'\',
\'include\' => \'\',
\'number\' => \'\',
\'taxonomy\' => \'catering_themes\',
\'pad_counts\' => false
);
$categories = get_categories($category_args);
if ( $categories ) {
echo \'<ul id="catering-menu" class="list-unstyled catering-menu">\';
foreach ( $categories as $cat ) {
echo \'<li class="has-children menu-item"><a href="\' . THEME_URL . \'/themes/\' . $cat->slug .\'/">\' . $cat->name .\'</a>\';
$menus_arg = array(
\'post_type\' => \'menus\',
\'order\' => \'ASC\',
\'orderby\' => \'name\',
\'post_status\' => \'publish\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'catering_themes\',
\'field\' => \'slug\',
\'terms\' => $cat->slug,
)
),
\'posts_per_page\' => -1
);
$menus = get_posts( $menus_arg );
if ( $menus ) {
echo \'<ul class="list-unstyled sub-menu">\';
echo \'<li class="menu-item menu-item-title"><span class="catering-nav-back">Tilbake</span><span class="catering-nav-title">\' . $cat->name .\'</span></li>\';
foreach ( $menus as $post ) : setup_postdata( $post );
echo \'<li class="menu-item"><a href="\' . get_the_permalink() . \'">\'. get_the_title() .\'</a></li>\';
endforeach;
wp_reset_postdata();
echo \'</ul>\';
}
echo \'</li>\';
}
echo \'</ul>\';
}
?>
</nav>
<!-- Title and Content from the get_post() -->
<article id="post-content">
<div class="row">
<div class="col-md-11">
<h1 class="post-title"><?php the_title(); ?></h1>
</div>
<div class="col-md-1">
<a id="content-close" class="button-close" href="#"></a>
</div>
</div>
<div class="row">
<div class="col-md-12">
<?php the_content(); ?>
</div>
</div>
</article>
获取餐饮菜单的循环工作得很好,但是应该来自使用get\\u post()加载的帖子的标题和内容显示了餐饮菜单循环中加载的最后一篇帖子的数据。一些wordpress天才知道为什么会这样吗?