サポート » 使い方全般 » 最新の投稿を一件のみ、タイトルとリンク、抜粋をヘッダーに表示

  • 解決済 eijiy

    (@eijiy)


    WordPressテーマのtwentytenで、最新の投稿を一件のみ、タイトルとリンク、それに内容の抜粋をヘッダーに表示したいのですが、内容の抜粋をどうして表示させるのか分らないので、どなたかご教授頂けないでしょうか。

    以下のようにすればタイトルとリンクが一件表示されますが、

    <?php $new_posts = get_posts("order=desc&orderby=date&numberposts=1"); ?>
    <ul class="borbot">
        <?php foreach($new_posts as $post): ?>
            <li><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
        <?php endforeach; ?>
    </ul>

    以下のタグを使っても抜粋は表示されません。
    <?php the_excerpt(); ?>
    宜しくお願い致します。

4件の返信を表示中 - 1 - 4件目 (全4件中)
  • 記述する場所が悪いとかじゃないってことですか?
    簡単なところで

    <?php $new_posts = get_posts("order=desc&orderby=date&numberposts=1"); ?>
    <ul class="borbot">
        <?php foreach($new_posts as $post): ?>
            <li><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a><br /><?php the_excerpt();?></li>
        <?php endforeach; ?>
    </ul>

    というかたちでダメってことですか?

    トピック投稿者 eijiy

    (@eijiy)

    kvexさん、返信ありがとうございます。

    そうです、そのコードで駄目です。

    <?php the_excerpt(); ?>
    はループ外では使えないのでしょうか。

    以下のコードをヘッダーに入れると

    <br />
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?></p>
    <div class="post">
    <a href="<?php the_permalink(); ?>" rel="bookmark"><br />
    ■<?php the_title(); ?></a>-<br />
    <?php the_date(); ?>-<?php the_time(); ?><br />
    <?php the_category(); ?><br />
    <?php the_excerpt(); ?>
    </div>
    <p><?php endwhile; else : ?><br />
    <?php _e('sorry,no posts'); ?><br />
    <?php endif; ?>

    現在表示中のタイトル、リンク、投稿日時、カテゴリ、内容の抜粋が表示されます。

    これを現在表示中の記事と関係なく、トップページを開いた時のみヘッダーに最新の投稿の一件を表示させるように変えられないものでしょうか。

    eijiyさんこんにちは

    get_postsで取得して作ったループではthe_excerpt()で抜粋を表示することができません。しかしsetup_postdata()を使えばすべての投稿データが取得できるようになります。

    <?php $new_posts = get_posts("order=desc&orderby=date&numberposts=1"); ?>
    <ul class="borbot">
        <?php foreach($new_posts as $post): ?>
            <?php setup_postdata($post); ?>
            <li><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a><br /><?php the_excerpt();?></li>
        <?php endforeach; ?>
    </ul>

    という内容と同じことがCodexの「テンプレートタグ/get posts 全ての投稿データにアクセス」のところに書いています。

    トピック投稿者 eijiy

    (@eijiy)

    show555さん、返信ありがとうございます。

    勉強不足(反省!)です。
    setup_postdata($post);を使うんですね。

    お陰でテストも成功して、実現できそうです。

    ありがとうございました。

4件の返信を表示中 - 1 - 4件目 (全4件中)
  • トピック「最新の投稿を一件のみ、タイトルとリンク、抜粋をヘッダーに表示」には新たに返信することはできません。