1

ワードプレスでスライドショーを作成したいのですが、そのカテゴリを作成しました。次に、スライドショー用にそのカテゴリの画像を取得したいと思います。これが私のコードの一部です:

<div id="slide-show">
   <ul>
        <?php query_posts('cat=1'); while(have_posts()): the_post();?>
        <li>
            <a href="<?php the_permalink();?>">
            <img src="<?php
            $image=wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail');
            echo $image[0];?>" alt="<?php the_title();?>" /></a>
        </li>
        <?php endwhile; wp_reset_query();?>
    </ul>
</div>

しかし、それは機能しません。誰か助けてくれませんか?

4

1 に答える 1

0

まず、繰り返します。

まず、使わない query_posts
チェックしてください:


この場合、目的の出力を作成する関数を作成することをお勧めします。functions.phpテーマファイルの中に入れます。ファイルの最後に配置します。PHP ファイルの最後に
ある場合は削除してください。これは不要であり、その後に空白があるとサイトが壊れる可能性があります。?>

とはいえ、関数は必要な Html を正確に出力し、テーマ テンプレート ファイル ( index.phpsingle.phppage.phpなど)でこのように呼び出されます。

<?php get_gallery(4); ?>

数字の 4 はカテゴリ ID です。

これが関数です。コード内のコメントを確認してください。

function get_gallery( $id )
{
    // Simple query
    $posts = get_posts( array(
        'category' => $id, 
        'post_status' => 'publish', 
        'post_type' => 'post', 
    ) );

    // Start building the Html code
    $slide_show = '
        <div id="slide-show">
            <ul>';

    // Iterate through the results
    foreach ( $posts as $post )
    {
        // Assign value and test if it exists at the *same time*
        if( $thumb = get_post_thumbnail_id( $post->ID ) )
        {
            $permalink = get_permalink( $post->ID );
            $image = wp_get_attachment_image_src( $thumb );

            // Build the Html elements
            $slide_show .= '
                <li>
                    <a href="' . $permalink . '">
                    <img src="'. $image[0] . '" alt="' . $post->post_title .'" />
                    </a>
                </li>';
        }
    }

    // Finish the Html
    $slide_show .= '
            </ul>
        </div>
    ';

    // Print the Html
    echo $slide_show;
}

結果:
HTML出力のスクリーンショット

于 2012-12-23T23:26:44.437 に答える