我在这里是新的,也是PHP的新..

只是想知道如何像Wordpress中那样制作自己的灵活循环...
请注意我不是在谈论wordpress ..我想在自己的PHP应用程序中实现它...

让我们回顾一下WP,其中有一个类似以下的代码:

while (have_post() : thepost())// .. bla bla...

echo the_title();
echo the_content();

endwhile; // this is just an ilustration


您能否弄清楚have_post()或the_post()如何与数据库交互,
这样它们就可以循环播放。

谢谢..

最佳答案

WordPress使用全局变量,这些变量在循环遍历时会修改。例如。:

var $posts = null;
var $post = null;
var $post_count = 0;
var $post_index = 0;

function have_post() {
    global $posts, $post_count, $post_index;

    $post_index = 0;

    // do a database call to retrieve the posts.
    $posts = mysql_query('select * from posts where ...');

    if ($posts) {
        $post_count = count($posts);
        return true;
    } else {
        $post_count = 0;
        return false;
    }
}

function thepost() {
    global $posts, $post, $post_count, $post_index;

    // make sure all the posts haven't already been looped through
    if ($post_index > $post_count) {
        return false;
    }

    // retrieve the post data for the current index
    $post = $posts[$post_index];

    // increment the index for the next time this method is called
    $post_index++;

    return $post;
}

function the_title() {
    global $post;
    return $post['title'];
}

function the_content() {
    global $post;
    return $post['content'];
}


但是,我绝对建议您对WordPress进行OOP样式编码。这将使变量在对象的实例内定义,而不是全局访问。例如。:

class Post {
    function __construct($title, $content) {
        $this->title = $title;
        $this->content = $content;
    }

    function getTitle() {
        return $title;
    }

    function getContent() {
        return $content;
    }
}

class Posts {
    var $postCount = 0;
    var $posts = null;

    function __construct($conditions) {
        $rs = mysql_query('select * from posts where $conditions...');

        if ($rs) {
            $this->postCount = count($rs);
            $this->posts = array();

            foreach ($rs as $row) {
                $this->posts[] = new Post($row['title'], $row['content']);
            }
        }
    }

    function getPostCount() {
        return $this->postCount;
    }

    function getPost($index) {
        return $this->posts[$index];
    }
}

关于php - 如何像Wordpress Loop一样制作自己的while循环?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1516181/

10-16 11:53