Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

php - Putting the WordPress Loop into a class

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

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 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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
        }
    }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...