wordpress - WordPress get_posts() 不返回模板标签
问题描述
我想使用 WordPressget_posts
功能获取最新的 5 篇文章。我做了以下事情:
在functions.php文件中,我添加了extra.php文件,其中包含以下代码:
if( !function_exists( 'evertstrap_post' ) ) {
function evertstrap_post() {
$args = array(
'post_type' => 'post',
'numberposts' => 5,
);
$recent_posts = get_posts( $args );
foreach ( $recent_posts as $post ) {
setup_postdata( $post );
echo get_the_title();
echo '<br/>';
}
wp_reset_postdata();
}
}
现在,我从home.php文件调用evertstrap_post()
但它没有得到最新的 5 个帖子!
但
如果我直接将代码放入index.php文件,那么它就可以工作。
我该如何解决?
解决方案
我有时在 WordPress 中看到过这种情况echo
,输出是不利的。你能试一试吗?
if( !function_exists( 'evertstrap_post' ) ) {
function evertstrap_post() {
global $post;
$args = array(
'post_type' => 'post',
'numberposts' => 5,
);
$recent_posts = get_posts( $args );
$output = '';
foreach ( $recent_posts as $post ) {
setup_postdata( $post );
$output .= get_the_title();
$output .= '<br/>';
}
wp_reset_postdata();
return $output;
}
}
然后home.php
你可以这样做:
<?php echo evertstrap_post(); ?>
推荐阅读
- java - 我如何为我的更新编写 DAO 层\获取所有实体
- php - 如何在 Symfony 5 中删除“X-Robots-Tag”http 标头
- angular - Angular NgZorro Datepicker 不能使用 Moment
- python - python 的 time.sleep() 长时间的准确度如何?
- google-bigquery - 如何使用 BigQuery 命令行工具执行一次性 S3 数据传输?
- sorting - 在 Pine 脚本中排序
- c - 在C中的函数内更改数组的一些值
- reactjs - History.push 一个带有反应路由器的新标签的链接
- google-compute-engine - Google Compute Engine 上的内部 500 错误,安装最小的 jupyter
- spring-boot - Servlet 过滤器应用了两次