如何在Wordpress中调用并显示链接到其帖子的精选图像?

时间:2014-10-14 07:19:01

标签: php wordpress featured

我试图在我的主页上显示某个类别中最近4个帖子的列表,每个帖子只显示其特色图片,然后当您点击其中一个图片时,它会带您到全文/帖子。我找到了一个教程,解释了如何做到这一点,但它似乎早于缩略图/特色图像,而是使用自定义值。我还没有能够修改它以使用特色图片或找到使用它们的图像。

这是我正在使用的代码

<?php
    $featured_posts = get_posts('numberposts=4&category=2');

    foreach( $featured_posts as $post ) {
        $custom_image = get_post_custom_values('featured_image', $post->ID);
        $image = $custom_image[0] ? $custom_image[0] : get_bloginfo("template_directory")."/img/no_featured.jpg";
        printf('<li><a href="%s" title="%s"><img src="%s" alt="%s" /></a></li>', get_permalink($post->ID), $post->post_title, $image, $post->post_title);
    }
    ?>    

我想要做的就是让它抓住帖子特色图片而不是那个自定义值。
我确定有一个简单的解决方案,我只是没有如果有任何成功,我总是打破它。

2 个答案:

答案 0 :(得分:0)

请使用以下代码。这将显示4个来自指定类别的最新帖子,包括标题,精选图​​片和内容。点击特色图片后,它将转到帖子页面。

<?php
    $posts = new WP_Query();
    $posts->query( "category_name='{enter your category slug here}'&posts_per_page=4" );
    if($posts->have_posts()) :
        while ($posts->have_posts()) : $posts->the_post();
            the_title();
            the_post_thumbnail();
            the_content();
        endwhile;        
    endif;
    wp_reset_postdata();
?>

答案 1 :(得分:0)

因为您只想显示精选图片,包含在链接标记中:

<?php
    $args = array(
        'cat' => 2,
        'posts_per_page' => 4
    );
    // The Query
    $the_query = new WP_Query( $args );

    // The Loop
    if ( $the_query->have_posts() ) {
        echo '<ul>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post(); ?>
            <li><a href="<?php the_permalink(); ?>">
              <?php the_post_thumbnail(); ?>
            </a></li>
        <?php }
        echo '</ul>';
    }
    /* Restore original Post Data */
    wp_reset_postdata();
?>
相关问题