Method as Condition in While Loop

Need to create a Method like WordPress’s function have_posts() for templating.

Method goes something like this:

Read More
class posts{
    public function have_posts(){
        $query = 'SELECT * FROM posts';
        $result = mysql_query($query);
        return mysql_fetch_array($result);
    }
}

Using the class in the template (theme):

$posts = new posts;
while($row = $posts->have_posts()){
    echo $row['post_title'];
}

But I am trying to achieve something like:

<?php while(have_posts()){ ?>
<h1><?php post_title(); ?></h1>
<?php } ?>

Alternatives & Suggestions are also welcomed 🙂

Related posts

Leave a Reply

1 comment

  1. For your specific question, the following should work

    class posts
    {
        private $_result;
        private $_current;
    
        public function __construct()
        {
            $query = 'SELECT * FROM posts';
            $this->_result = mysql_query($query);
        }
    
        public function have_posts()
        {
            return ($this->_current = mysql_fetch_array($this->_result));
        }
    
        public function post_title()
        {
            echo $this->_current['title'];
        }
    } 
    
    <?php $posts = new posts(); ?>
    
    <?php while($posts->have_posts()){ ?>
        <h1><?php $posts->post_title(); ?></h1>
    <?php } ?>