将WordPress循环放入类中

将WordPress循环放入类中

本文介绍了将WordPress循环放入类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个基本上为WordPress开发者的框架,以帮助开发主题和主题框架更有效和更快。

I am trying to build a framework essentially for WordPress Developers to help develop Themes and Theme Frameworks more efficiently and faster.

我有一个小问题通过把wordpress循环放到类中,这是我有:

How ever, I am having a small issue by putting the wordpress loop into a class, this is what I have:

class AisisCore_Template_Helpers_Loop{

    protected $_options;

    public function __construct($options = null){
        if(isset($options)){
            $this->_options = $options;
        }
    }

    public function init(){}

    public function loop(){
        if(have_posts()){
            while(have_posts()){
                the_post();
                the_content();
            }
        }
    }
}

Keep考虑到现在的类的简单。所有你需要做的是:

Keep in mind the simplicity of the class for now. All you have to do is:

$loop = new AisisCore_Template_Helpers_Loop();
$loop->loop();

您应该会看到帖子列表。

And you should see the list of posts.

然而,似乎没有出现帖子。是否有阻止WordPress循环工作的东西?

How ever, it appears that posts do not appear. Is there something preventing the WordPress loop from working?

推荐答案

我相信你有范围的问题。您需要将 $ wp_query 传入类或通过全局获取。我相信这只会工作,但只为全局 $ wp_query

I believe you have problem with "scope". You will need to pass $wp_query into the class or grab it via global. I believe that just this would work but only for the global $wp_query:

public function loop(){
    global $wp_query;
    if(have_posts()){
        while(have_posts()){
            the_post();
            the_content();
        }
    }
}

未经测试,但我认为应该与全局 $ wp_query 或通过传递一些其他查询结果集合。

Untested but I think the following should work either with the global $wp_query or by passing in some other query result set.

protected $wp_query;

public function __construct($wp_query = null, $options = null){
    if (empty($wp_query)) global $wp_query;
    if (empty($wp_query)) return false; // or error handling

    $this->wp_query = $wp_query;

    if(isset($options)){
        $this->_options = $options;
    }
}

public function loop(){
    global $wp_query;
    if($this->wp_query->have_posts()){
        while($this->wp_query->have_posts()){
            $this->wp_query->the_post();
            the_content();
        }
    }
}

手指交叉,我认为它应该工作。没有承诺。

Fingers crossed on that one but I think it should work. No promises though.

这篇关于将WordPress循环放入类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:35