10 09/2014

wordpress loop

最后更新: Wed Sep 10 2014 12:39:11 GMT+0800

wordpress 有五种办法 遍历,除了第一种以外都可以带 sql 查询参数

Default Loop

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

    <div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
        <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
        <?php the_content(); ?>
    </div>

<?php endwhile; ?>

    <div class="navigation">
        <div class="next-posts"><?php next_posts_link(); ?></div>
        <div class="prev-posts"><?php previous_posts_link(); ?></div>
    </div>

<?php else : ?>

    <div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
        <h1>Not Found</h1>
    </div>

<?php endif; ?>

Loop with query_posts()

<?php global $query_string; // required
$posts = query_posts($query_string.'&cat=-9'); // exclude category 9 ?>

<?php // DEFAULT LOOP GOES HERE ?>

<?php wp_reset_query(); // reset the query ?>

Loop with WP_Query()

<?php $custom_query = new WP_Query('cat=-9'); // exclude category 9
while($custom_query->have_posts()) : $custom_query->the_post(); ?>

    <div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
        <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
        <?php the_content(); ?>
    </div>

<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>

Loop with get_posts()

<?php global $post; // required
$args = array('category' => -9); // exclude category 9
$custom_posts = get_posts($args);
foreach($custom_posts as $post) : setup_postdata($post);
...
endforeach;
?>

wp get recent posts()

<h2>Recent Posts</h2>
<ul>
<?php
    $recent_posts = wp_get_recent_posts();
    foreach( $recent_posts as $recent ){
        echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' .   $recent["post_title"].'</a> </li> ';
    }
?>
</ul>

参数

 <?php $args = array(
    'numberposts' => 10,
    'offset' => 0,
    'category' => 0,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'include' => ,
    'exclude' => ,
    'meta_key' => ,
    'meta_value' =>,
    'post_type' => 'post',
    'post_status' => 'draft, publish, future, pending, private',
    'suppress_filters' => true );

    $recent_posts = wp_get_recent_posts( $args, $output = ARRAY_A );
?> 

via http://codex.wordpress.org/The_Loop