WordPress 在function.php 文件中方法中the_XXX方法失效

最近在使用WP给客户做一个企业网站,却出现从未遇到的问题。

事件是这样子的:我在function.php文件里写了一个根据分类ID获取文章的文章,因为该方法里的html元素是在多个页面共用的
但我在index.php页面调用时却出现了完全相同的信息且自定义的查询条件也失效了,但如果使用对象直接访问则没有问题,见下图
function.php中的方法名
/**
*首页分类ID对应的信息
*@param integer $cat_id [分类ID号]
*@param integer $per_page [显示条数]
*@return[type][description]
*/
function cat_product($cat_id=0,$per_page=3){
$args = array('posts_per_page'=> $per_page,'category'=> $cat_id );
$rand_posts = get_posts( $args );
foreach ( $rand_posts as $post ):
setup_postdata( $post );
echo $post->post_title."<br>";//通过这种方式没有问题
echo get_the_title();echo "<br><br> ";//通过这种方式无法获取下一条对象数据
?>
<?php endforeach;wp_reset_postdata();?>
<?php }//end cat_product
index.php
<?php 
        cat_product(1);
        //cat_product(4);
?>
    
解决方案:
1.将funciton中的方法直接写在index页面中
缺点:每次需要调用的时候都需要复制粘贴代码,但基本上产生的内容结构是相同的只不是不同的查询条件而已
<?php
//将funciton中的方法直接写在index页面中则没有问题
$args = array('posts_per_page'=>5,'orderby'=>'rand');
$rand_posts = get_posts( $args );
foreach ( $rand_posts as $post ):
setup_postdata( $posts );
echo $posts->post_title."<br>";
echo get_the_title();echo "<br><br> ";
endforeach;wp_reset_postdata();
?>
2.在function文件里直接使用对象访问
缺点:无法使用the_id()等方法,且需要更改需要代码
/**
*首页分类ID对应的信息
*@param integer $cat_id [分类ID号]
*@param integer $per_page [显示条数]
*@return[type][description]
*/
function cat_product($cat_id=0,$per_page=3){
$args = array('posts_per_page'=> $per_page,'category'=> $cat_id );
$rand_posts = get_posts( $args );
foreach ( $rand_posts as $post ):
echo $post->post_title;//通过这种方式没有问题
echo $post->id;
?>
<?php endforeach;wp_reset_postdata();?>
<?php }//end cat_product
3.在function里通过将对象声明成全局对象来解决,可以使用the_id()这种方式,目前使用该方案
<?php
foreach($the_query as $post):
$GLOBALS['post']= $post;//将当前对象保存成全局对象
setup_postdata($post);//声明成全局的 post,可以使用the_id 这种方式获取数据
var_dump(get_the_ID());//这里就正常输出了。
?>
<?php endforeach;wp_reset_postdata();?>
 
参考:





原文地址:https://www.cnblogs.com/huangtailang/p/4642080.html