Wordpress featured image code

2019-08-26 02:49发布

问题:

Hi I'm trying to figure out how to put a featured image in wordpress on my custom page.

here is my code:

            <?php

                    $args = array( 'numberposts' => '1' );
                    $recent_posts = wp_get_recent_posts( $args );
                    if (has_post_thumbnail() ) {
                    foreach( $recent_posts as $recent ){
                        the_post_thumbnail();
                        echo '<li><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a> </li> ';
                    }
                }
                else {
                    echo "no featured post";
                }
            ?>

回答1:

<?php

    $args = array( 'numberposts' => '1' );
    $recent_posts = wp_get_recent_posts( $args );

    if( $recent_posts ) {
        foreach( $recent_posts as $recent ){
            if (has_post_thumbnail($recent['ID']) ) {
               echo get_the_post_thumbnail($recent['ID']);
            }
            echo '<li><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a> </li> ';
        }
    } else {
        echo "no featured post";
    }
?>

the_post_thumbnail requires you to be in a loop. If you want to retrieve with your own ID, use get_the_post_thumbnail



标签: php wordpress