Media thumbnail for custom post inside post content

Some media are added to the post but not inserted into post content. How to insert media into post content without doing it manually. I was able to find the following code to display the attached thumbnail post inside the article content.

add_filter('the_content', 'put_thumbnail_in_posting');
function put_thumbnail_in_posting($content) {
    global $post;

    if ( has_post_thumbnail() && ( $post->post_type == 'post' ) ) {
        the_post_thumbnail( '', array( 'style' => 'float:left;margin:15px;' ) ); 
    }

    return $content;
}

Above function is tested and working. My question is how to adjust code to look for custom post type advert and insert the attached media to post content?

And how to make the function bring all the attached media not just one?

I already tested using advert in post-type advert and didn’t work.

Thanks!

1 Answer
1

@Ibraheem, you don’t have to use global $post, since it is in global. To check post type you can use get_post_type().
Using the_post_thumbnail is not properly implemented in this case, instead use get_the_post_thumbnail. Note: you can’t use has_post_thumbnail as tag condition if you are not set featured image.

add_filter( 'the_content', 'put_thumbnail_in_posting' );
function put_thumbnail_in_posting( $content )
{
    if ( 'advert' == get_post_type() && has_post_thumbnail() )
    {
        $thumbnail = get_the_post_thumbnail( null, $size="", array(
                'style' => 'float:left;margin:15px;'
        ) );

        $content = $thumbnail . $content; //thumbnail in top text
        /* $content = $content . $thumbnail; //thumbnail in bottom text  */
    }

    return $content;
}

To get all attachment in post, you can implement with the following way:

add_filter( 'the_content', 'put_thumbnail_in_posting' );
function put_thumbnail_in_posting( $content )
{
    if ( 'advert' == get_post_type() )
    {
        $args = array(
            'order'          => 'ASC',
            'post_mime_type' => 'image',
            'post_parent'    => get_the_ID(),
            'post_status'    => null,
            'post_type'      => 'attachment',
        );

        $attachments = get_children( $args );

        if ( $attachments ) {
            $thumbnails="";
            foreach( $attachments as $attachment )
            {
                $thumbnails .= wp_get_attachment_image( $attachment->ID, $size = null, $icon = true, array(
                    'style' => 'float:left;margin:15px;'
                ) );
            }
            $content = $thumbnails . $content;
        }
    }
    return $content;
}

You can add another tag condition such as is_home, is_single, etc. and tweak thumb arguments in code that suit with your need.

Leave a Comment