WordPress.org

Ready to get started?Download WordPress

Forums

Pinboard
Using the *first* Image as Featured Image (1 post)

  1. rob_st_82
    Member
    Posted 1 year ago #

    So you have this function which is supposed to use the first image in an "image"-post automagically as featured image. But it doesn't. It uses the last image.

    I hacked the functions.php to be sure to use the first image.

    In your functions.php find the line where it says
    function pinboard_get_first_image() {

    Replace the whole function (until the closing "}" briefly before the "endif;"-tag) with:

    function pinboard_get_first_image() {
    	$document = new DOMDocument();
    	$content = apply_filters( 'the_content', get_the_content( '', true ) );
    	if( '' != $content ) {
    		libxml_use_internal_errors( true );
    		$document->loadHTML( $content );
    		libxml_clear_errors();
    		$images = $document->getElementsByTagName( 'img' );
    		$document = new DOMDocument();
    		$images_amount = ($images->length); // How many images are there in the post?
    		if( $images->length ) {
    			$image= $images->item( $images->length - $images_amount ); // The first image ist the 0 (zero).
    			$src = $image->getAttribute( 'src' );
    			$width = ( $image->hasAttribute( 'width' ) ? $image->getAttribute( 'width' ) : false );
    			$height = ( $image->hasAttribute( 'height' ) ? $image->getAttribute( 'height' ) : false );
    			return array( $src, $width, $height );
    		}
    	}
    	return false;
    }

    The changes I made are concerning the variable $images_amount.

Topic Closed

This topic has been closed to new replies.

About this Theme

About this Topic