WordPress主题制作教程5:循环

wordpress循环分两种,一种是自定义循环,一种是默认循环。

自定义循环:根据指定参数进行实例化

调用所有页面,post_type值:page对应页面,post对应文章

<?php
$args=array(
  'post_type'=>'page' 
);

$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>

调用多id内容,参数修改为:

$args=array(
'post_type'=>'page' ,
'page_id=2,86'
);

调用指定id内容,参数修改为:

$args=array(
 'post_type'=>'page' ,
'page_id'=>2
);

默认循环:根据链接结构进行数据查询

<?php
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        // Your loop code
    endwhile;
else :
    echo wpautop( 'Sorry, no posts were found' );
endif;
?>

动动手:

文章的链接结构为:?p=x     --------调用single.php

页面的链接结构为:?page_id=x   --调用page.php

把page.php修改为:

<?php
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        // Your loop code
echo "页面标题:".get_the_title();
    endwhile;
else :
    echo wpautop( 'Sorry, no posts were found' );
endif;
?>

把single.php修改为:

<?php
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        // Your loop code
echo "文章标题:".get_the_title();
    endwhile;
else :
    echo wpautop( 'Sorry, no posts were found' );
endif;
?>

 想知道怎么在循环内调用其他内容,请看:

WordPress主题制作教程6:常用模版标签

 相关文章:

查看wordpress的WP_Query文档

原文地址:https://www.cnblogs.com/tinyphp/p/4399855.html