プログラミングで飯を食え。腕をあげたきゃ備忘録!

PHP、JavaScript、HTML5、CSS3などWEB系言語を中心に基本テク、備忘録をまとめます。Android、Iphoneアプリ開発についても!

WordPressのthe_title()!メインループとサブループについて!

サクウェブTVはコチラ↓↓↓
サクウェブTV

WordPressで記事のタイトルを表示するためのテンプレートタグとして

the_title()というものがありますが、

これは基本的にループ内で使用されるものです。

したがって、例えば

$arg = array(
    "category__in"=>array(1,2,3),
    "paged"=>get_query_var("paged")//ページングをしている場合のページ番号取得
);
query_posts($arg);//メインループの検索条件を設定

if(have_posts())://メインループここから
    while(have_posts()):
        the_post();
?>
        <h2><?php the_title(); ?></h2>
<?php
    endwhile;
endif;
wp_reset_query();

などとしてタイトルを表示できます。

ちなみにthe_title()はthe_post()していることが条件となります。

ではこのメインループの中にサブループを組み込んでみると、

$arg = array(
    "category__in"=>array(1,2,3),
    "paged"=>get_query_var("paged")//ページングをしている場合のページ番号取得
);
query_posts($arg);//メインループの検索条件を設定

if(have_posts())://メインループここから
    while(have_posts()):
        the_post();
?>
        <h2><?php the_title(); ?></h2>
        <?php
            //この記事のカテゴリーIDを全て取得
            $categories = get_the_category($post->ID);
            $category_ID = array();
            foreach($categories as $category){
                array_push($category_ID,$category->cat_ID);
            }
            
            $args = array(
                "post__not_in"=>array($post->ID),
                "category__in"=>$category_ID,
                "posts_per_page"=>3,
                "orderby"=>"rand"
            );
            $my_query = new WP_Query($args);
            
            if($my_query->have_posts())://サブループここから
                while($my_query->have_posts()):
                    $my_query->the_post();
?>
                    <h3><?php the_title(); ?></h3>
<?php
                endwhile;
            endif;
            wp_reset_postdata();
        ?>
<?php
    endwhile;
endif;
wp_reset_query();

こんな感じです。

赤いthe_title()がメインループ、青いthe_title()がサブループのthe_title()です。

the_title()はthe_post()されていることが条件となりますが、

言い換えれば、直前のthe_post()に従って表示が変わるということです。

つまり、

メインループの

the_post()に従って

赤いthe_title()は動き、

サブループの

$my_query->the_post()に従って

青いthe_title()は動くわけです。

 

簡単にまとめると、

the_title()はメインループでもサブループでもthe_title()とするだけで記事のタイトルはちゃんと表示してくれる。

ということでしょう。

 

※ということは、the_content()やthe_permalink()も同じ挙動をするでしょう。