- 2010-04-23 (金) 17:20
- 技術
wordpressのプラグイン、特にウィジェットを作っていると、テンプレートのメインループとは別のループを作りたいと思う事があります。
しかし…WordPressのCodexには日本語情報が無い……!
と言うわけで英語情報から引っ張ってきました。ついでに少しCodexを更新してみました。( The Loop – WordPress Codex 日本語版 )
Codexを見て貰っても良いのですが、こっちも簡潔に纏めておきます。
普段のループはこんな感じですよね。
<pre>
if($query->have_posts()): while($query->have_posts()): $query->the_post();
// 適当に処理する
endwhile; endif;
</pre>
if($query->have_posts()): while($query->have_posts()): $query->the_post();
// 適当に処理する
endwhile; endif;
</pre>
それを、こんな感じのループで書きます。オブジェクト指向、ってやつです。
<pre>
$my_query = new WP_Query('showposts='.$instance['count'].'&cat='.$instance['cat_id']);
if($my_query->have_posts()): while($my_query->have_posts()): $my_query->the_post();
// 適当に処理する
endwhile; endif;
</pre>
$my_query = new WP_Query('showposts='.$instance['count'].'&cat='.$instance['cat_id']);
if($my_query->have_posts()): while($my_query->have_posts()): $my_query->the_post();
// 適当に処理する
endwhile; endif;
</pre>
すると、コレがループの前でも、後でも、複数回使っても、競合しません。便利ですね。オブジェクト指向って凄いなぁ、と思わされる瞬間です。
以下、もう少し突っ込んだ話。
実は$wp_query = new WP_Query(/* なんかURLから適当に引き出した条件 */); という様な処理で最初の方にオブジェクトが作られていて、
have_posts()やthe_posts()はそのメソッドを呼び出す関数…という実装になってるみたいです。
- Newer: youtube HTML5版がSafariで乱れる問題
- Older: KtaiStyleとMy Category Orderの連携
Comments:0
Trackbacks:0
- Trackback URL for this entry
- http://blog.s-satoshi.net/tech/wordpress_multiple_loop/trackback/
- Listed below are links to weblogs that reference
- wordpressで複数のループを扱う方法 from S.Satoshiのブログ