How to grab only the post image in wordpress?

Asked

Viewed 650 times

1

How I only get the link from the post image in the worpdress to put in the bootstrap card element?

<?php
            $arti_query = new WP_Query(array('category_name' => 'artigos'));
            if ( $arti_query->have_posts() ) { 
                while ( $arti_query->have_posts() ) {
                    $url = get_image();
                    $arti_query->the_post();
                    echo '<a href="#" class="card">';
                    echo '<img class="card-img-top" src="'.$url.'">';
                    echo '<div class="card-body">';
                    echo '<h5 class="card-title">';
                    echo the_title();
                    echo '</h5>';
                    $content = get_the_content();
                    $content = preg_replace( '/<img[^>]+./', '', $content );
                    $content = preg_replace( '/<p[^>]+./', '', $content);
                    echo '<p class="card-text">'.$content.'</p>';
                    echo '</div>';
                    echo '<div class="card-footer">';
                    echo '<small class="text-muted">';
                    echo get_the_date();
                    echo '</small>';
                    echo '</div>';
                    echo '</a>';

                }   
            } 
            ?>

inserir a descrição da imagem aqui

1 answer

0

I usually use this function below to return the URL of the first image of the post in Wordpress:

/*
 * Esta função retorna a primeira imagem associada ao post
 * Source: https://codex.wordpress.org/Function_Reference/get_children#Show_the_first_image_associated_with_the_post
 */
function echo_first_image( $postID ) {
        $args = array(
                'numberposts' => 1,
                'order' => 'ASC',
                'post_mime_type' => 'image',
                'post_parent' => $postID,
                'post_status' => null,
                'post_type' => 'attachment',
        );

        $attachments = get_children( $args );

        if ( $attachments ) { foreach ( $attachments as $attachment ) {
                        $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' )  ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' );

                        echo wp_get_attachment_thumb_url( $attachment->ID );
                }
        }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.