LoginSignup
7
6

More than 5 years have passed since last update.

【WordPress】query_postsの代替としてのget_postsについて

Last updated at Posted at 2014-07-17

結論

get_posts()を使い、setup_postdata()し、wp_reset_postdata()する。

書き比べ

query_posts()版

<?php
    query_posts('category_name=' . $category->slug . '&orderby=title&order=ASC');
    if(have_posts()):
        while(have_posts()):
?>
            <h4><?php the_title(); ?>"></h4>
            <?php the_contents(); ?>
<?php
        endwhile;
    endif;
?>

get_posts()版

<?php
    $post_args = array(
        'category'  => $category->cat_ID
       ,'orderby'   => 'title'
       ,'order'     => 'ASC'
       ,'post_type' => 'post'
    );
    $shohin_posts = get_posts( $post_args );
    foreach($shohin_posts as $post) :
        setup_postdata( $post );
    ?>
        <h4><?php the_title(); ?>"></h4>
        <?php the_contents(); ?>
<?php
    endforeach; 
    wp_reset_postdata();
?>

参考

テンプレートタグ/query posts - WordPress Codex 日本語版
query_postsを捨てよ、pre_get_postsを使おう【追記あり】【報告あり】 | notnil creation weblog
テンプレートタグ/get posts - WordPress Codex 日本語版

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6