-2

I'm trying to display a list of the 4 most recent posts in a certain category on my home page, each displayed only by their featured image, and then when you click on one of the images it takes you to the full article/post. I found a tutorial that explains how to do this but it seems to predate thumbnails/featured images and uses custom values instead. I haven't been able to modify it to use featured images or find one that uses them.

Here's the code I'm working with

<?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);
    }
    ?>    

All I want to do is get it to grab the posts featured image instead of that custom value.
I'm sure there's a simple fix for this, I just haven't had any success yet, I always end up breaking it.

4

2 回答 2

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();
?>
于 2014-10-14T07:29:45.437 回答
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();
?>
于 2014-10-14T07:42:54.527 回答