• Resolved robertritz

    (@robertritz)


    I am attempting to set the featured thumbnail programmatically via functions.php. Here is the code I half wrote (the rest comes very helpfully from another StackExchange post. There don’t seem to be any syntax errors (I’ve got debugging turned on) but when making a new post with the correct category nothing happens. I’m very new to PHP so I’m assuming it’s an issue with my code but I’m not sure exactly where.

    I’m loading the HTML of a URL in a custom field via DOM, then pulling the IMG tags. After that an If ElseIf looks at the category and grabs the nth image based on the category and attaches it as the post thumbnail. I feel that the logic is right but I might be missing something.

    <?php
    add_action('publish_post', 'auto_featured_image_publish_post');
    function auto_featured_image_publish_post($post, $post_id) {
    
    	$category = $post->the_category;
    
    	// we're using the excerpt field, change this to whatever field
        // you're using
        $post = get_post($post_id);
        $htmlURL = $post->original_guid;
    
        // try to load the webpage
        $doc = new DOMDocument();
        $doc->loadHTMLFile($htmlURL);
    
    	// get all image tags
        $images = $doc->getElementsByTagName('img');
    	if ( has_post_thumbnail($post_id) == false ) {
    		if ($category == "Mongolia.GoGo.mn") {
    			$imgcount = count($images);
    			$imageURL = $imgcount[62]->getAttribute('src');
    
    			// download image from url
    			$tmp = download_url($imageURL);
    
    			$file = array(
    				'name' => basename($imageURL),
    				'tmp_name' => $tmp
    			);
    
    			// create attachment from the uploaded image
    			$attachment_id = media_handle_sideload( $file, $post_id );
    
    			// set the featured image
    			update_post_meta($post_id, '_thumbnail_id', $attachment_id);
    		} elseif ($category == "News.mn English") {
    				$imgcount = count($images);
    				$imageURL = $imgcount[2]->getAttribute('src');
    
    				// download image from url
    				$tmp = download_url($imageURL);
    
    				$file = array(
    					'name' => basename($imageURL),
    					'tmp_name' => $tmp
    				);
    
    				// create attachment from the uploaded image
    				$attachment_id = media_handle_sideload( $file, $post_id );
    
    				// set the featured image
    				update_post_meta($post_id, '_thumbnail_id', $attachment_id);
    		} elseif ($category == "InfoMongolia") {
    				$imgcount = count($images);
    				$imageshortURL = $imgcount[3]->getAttribute('src');
    				$imageURL = "https://infomongolia.com/" . $imageshortURL;
    
    				// download image from url
    				$tmp = download_url($imageURL);
    
    				$file = array(
    					'name' => basename($imageURL),
    					'tmp_name' => $tmp
    				);
    
    				// create attachment from the uploaded image
    				$attachment_id = media_handle_sideload( $file, $post_id );
    
    				// set the featured image
    				update_post_meta($post_id, '_thumbnail_id', $attachment_id);
    		}
    	}
    }
Viewing 6 replies - 1 through 6 (of 6 total)
  • Thread Starter robertritz

    (@robertritz)

    EDIT: Well it took a while but eventually errors showed up. I put the corresponding line of code next to the errors. From these errors it looks like this functions isn’t pulling the fields from the post properly? Here are the errors:

    Warning: Missing argument 2 for auto_featured_image_publish_post() in /var/www/html/wordpress/wp-content/themes/point/functions.php on line 508
             function auto_featured_image_publish_post($post, $post_id) {
    
    Notice: Trying to get property of non-object in /var/www/html/wordpress/wp-content/themes/point/functions.php on line 510
             $category = $post->the_category;
    
    Notice: Undefined variable: post_id in /var/www/html/wordpress/wp-content/themes/point/functions.php on line 514
             $post = get_post($post_id);
    
    Notice: Trying to get property of non-object in /var/www/html/wordpress/wp-content/themes/point/functions.php on line 515
             $htmlURL = $post->original_guid;
    
    Warning: DOMDocument::loadHTMLFile(): Empty string supplied as input in /var/www/html/wordpress/wp-content/themes/point/functions.php on line 519
             This is empty because the other variables are :)
    
    Notice: Undefined variable: post_id in /var/www/html/wordpress/wp-content/themes/point/functions.php on line 523
             if ( has_post_thumbnail($post_id) == false ) {

    Something like this works:

    add_action('publish_post', 'auto_featured_image_publish_post',10,2);
    function auto_featured_image_publish_post($post_id, $post) {
    
    	$cat_detail=get_the_category($post_id);
    	$cat_name = array();
    	foreach($cat_detail as $cd){
    		$cat_name[] = $cd->cat_name;
    	}
    
           $htmlURL = get_permalink( $post_id );
    
           // try to load the webpage
           $doc = new DOMDocument();
           @$doc->loadHTMLFile($htmlURL);
    
    	// get all image tags
            $images = $doc->getElementsByTagName('img');
    	if ( has_post_thumbnail($post_id) == false ) {
    		if ( in_array( 'Mongolia.GoGo.mn', $cat_name ) ) {
    			$imageURL = $images->item(62)->getAttribute('src');
    
    			// download image from url
    			$tmp = download_url($imageURL);
    
    			$file = array(
    				'name' => basename($imageURL),
    				'tmp_name' => $tmp
    			);
    
    			// create attachment from the uploaded image
    			$attachment_id = media_handle_sideload( $file, $post_id );
    
    			// set the featured image
    			update_post_meta($post_id, '_thumbnail_id', $attachment_id);
    		}
    	}
    }

    or this:

    add_action('publish_post', 'auto_featured_image_publish_post',10,2);
    function auto_featured_image_publish_post($post_id, $post) {
    
    	$cat_detail=get_the_category($post_id);
    	$cat_name = array();
    	foreach($cat_detail as $cd){
    		$cat_name[] = $cd->cat_name;
    	}
    
           $post_content = $post->post_content;
           $doc = new DOMDocument();
           $doc->loadHTML($post_content);
    
    	// get all image tags
           $images = $doc->getElementsByTagName('img');
           if ( has_post_thumbnail($post_id) == false ) {
    		if ( in_array( 'Mongolia.GoGo.mn', $cat_name ) ) {
    			$imageURL = $images->item(62)->getAttribute('src');
    
    			// download image from url
    			$tmp = download_url($imageURL);
    
    			$file = array(
    				'name' => basename($imageURL),
    				'tmp_name' => $tmp
    			);
    
    			// create attachment from the uploaded image
    			$attachment_id = media_handle_sideload( $file, $post_id );
    
    			// set the featured image
    			update_post_meta($post_id, '_thumbnail_id', $attachment_id);
    		}
    	}
    }

    Thread Starter robertritz

    (@robertritz)

    Thanks PhPCentre! I tried the first option as my post’s permalink is actually an external link so this works best. I put it in my functions.php and made a new post, edited the permalink, set the category, saved and then hit publish. It did take a few seconds longer so I’m thinking it tried something.

    Is there something I can do to debug this? I’m using a different evaluator to determine if there is a thumbnail already. Also I pulled in the custom field meta as an array and am trying to select the specific custom field. Here is my current code. I’m really scratching my head over this and why it isn’t working…

    <?php
    add_action('publish_post', 'auto_featured_image_publish_post',10,2);
    function auto_featured_image_publish_post($post_id, $post) {
    
    	$cat_detail=get_the_category($post_id);
    	$cat_name = array();
    	foreach($cat_detail as $cd){
    		$cat_name[] = $cd->cat_name;
    	}
    
        $custom_fields = get_post_custom($post_id);
    	$htmlURL = $custom_fields['original_guid'];
    
           // try to load the webpage
           $doc = new DOMDocument();
           @$doc->loadHTMLFile($htmlURL);
    
    	// get all image tags
            $images = $doc->getElementsByTagName('img');
    	if ( get_post_meta($post_id, '_apt_skip_post_thumb', true) ) {
    		if ( in_array( 'Mongolia.GoGo.mn', $cat_name ) ) {
    			$imageURL = $images->item(62)->getAttribute('src');
    
    			// download image from url
    			$tmp = download_url($imageURL);
    
    			$file = array(
    				'name' => basename($imageURL),
    				'tmp_name' => $tmp
    			);
    
    			// create attachment from the uploaded image
    			$attachment_id = media_handle_sideload( $file, $post_id );
    
    			// set the featured image
    			update_post_meta($post_id, '_thumbnail_id', $attachment_id);
    		}
    	}
    }

    Assuming you want to use the first value for key ‘original_guid’ in your custom field, use this instead:

    $htmlURL = $custom_fields['original_guid'][0];

    Also this check:

    if ( get_post_meta($post_id, '_apt_skip_post_thumb', true) ) {
    
    }

    as the name of the key implies, are you not suppose to be doing the opposite:

    $meta_value = get_post_meta($post_id, '_apt_skip_post_thumb', true);
    if ( empty( $meta_value ) ) {
    
    }

    Thread Starter robertritz

    (@robertritz)

    Hi there, I got some outside help and dramatically changed the code around. Here is my working code. Wanted to share for anyone interested! I uses xpath instead of getting the nth image. I’m not sure which one is better, but xpath is probably more predictable.

    add_action('publish_post', 'custom_auto_featured_image_publish_post',10,2);
    function custom_auto_featured_image_publish_post($post_id, $post) {
    	// get category of post ID
    	$cat_detail=get_the_category($post_id);
    	$cat_name = array();
    	foreach($cat_detail as $cd){
    		$cat_name[] = $cd->cat_name;
    	}
    
    	$custom_fields = get_post_custom($post_id);
    
    	if(isset($custom_fields['original_guid']) && !empty($custom_fields['original_guid'])){
    		$htmlURL = $custom_fields['original_guid'][0];
    		// try to load the webpage
    		$dom = new domDocument;
    		$imageURL = '';
    
    		@$dom->loadHTML(file_get_contents($htmlURL));
    
    		if ( in_array( 'Mongolia.GoGo.mn', $cat_name ) ) {
    
    		    $finder = new DomXPath($dom);
    			$classname="newscover";
    			$content = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
    
    		    if($content->length){
    		    	if($content->item(0)->childNodes->length > 1){
    		    		$imageURL = $content->item(0)->childNodes->item(1)->getAttribute('src');
    				}
    			}else{
    				$content = $dom->getElementById('ncbubuhome');
    
    				if($content->childNodes->length){
    				    foreach ($content->childNodes as $node) {
    				    	if($node->nodeName != '#text'){
    				    		foreach ($node->childNodes as $childNode) {
    				    			if($childNode->nodeName == 'img'){
    				    				$imageURL = $childNode->getAttribute('src');
    				    				break;
    				    			}
    				    		}
    				    	}
    				    }
    			    }
    		    }
    		}elseif ( in_array( 'InfoMongolia', $cat_name ) ) {
    
    		    $finder = new DomXPath($dom);
    			$classname="full_text";
    			$content = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
    
    			if($content->length){
    	    		if($content->item(0)->childNodes->length){
    				    foreach ($content->item(0)->childNodes as $node) {
    				    	if($node->nodeName == 'img'){
    				    		$imageURL = $node->getAttribute('src');
    				    		break;
    				    	}
    				    }
    				}
    		    }
    		    if($imageURL != ''){
    			if (filter_var($imageURL, FILTER_VALIDATE_URL) === false) {
    		    	$domain = 'https://www.infomongolia.com/';
    		    	$imageURL = str_replace('../', '', $imageURL);
    			    $imageURL = $domain . $imageURL;
    			}
    		    }
    		} elseif ( in_array( 'UBPost', $cat_name ) ) {
    
    		    $finder = new DomXPath($dom);
    			$classname="full_text";
    			$content = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
    
    			if($content->length){
    	    		if($content->item(0)->childNodes->length){
    				    foreach ($content->item(0)->childNodes as $node) {
    				    	if($node->nodeName == 'img'){
    				    		$imageURL = $node->getAttribute('src');
    				    		break;
    				    	}
    				    }
    				}
    		    }
    		    if($imageURL != ''){
    			if (filter_var($imageURL, FILTER_VALIDATE_URL) === false) {
    		    	$domain = 'https://www.infomongolia.com/';
    		    	$imageURL = str_replace('../', '', $imageURL);
    			    $imageURL = $domain . $imageURL;
    			}
    		    }
    		}
    		if($imageURL != ''){
    			$imageURL = str_replace(' ', '%20', $imageURL);
    
    			// download image from url
    			$tmp = download_url($imageURL);
    
    			$ext = pathinfo(basename($imageURL), PATHINFO_EXTENSION);
    		    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    		    $name = strtotime("now") . '_feature_image.' . $ext;
    		    $type = finfo_file($finfo, $tmp);
    			$file = array(
    				'name' => $name,
    				'size' => filesize($tmp),
    				'type' => $type,
    				'tmp_name' => $tmp,
    				'error' => UPLOAD_ERR_OK
    			);
    
    			$overrides = array(
    				'test_form' => false,
    				'test_size' => true,
    				'test_upload' => true,
    			);
    
    			// upload image to server
    			$file_uploaded = wp_handle_sideload( $file, $overrides );
    
    			// $filename should be the path to a file in the upload directory.
    			$filename = $file_uploaded['file'];
    			$filetype = $file_uploaded['type'];
    
    			// Prepare an array of post data for the attachment.
    			$attachment = array(
    				'guid'           => $file_uploaded['url'],
    				'post_mime_type' => $filetype,
    				'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
    				'post_content'   => '',
    				'post_status'    => 'inherit'
    			);
    
    			// Insert the attachment.
    			$attach_id = wp_insert_attachment( $attachment, $filename );
    
    			// Generate the metadata for the attachment, and update the database record.
    			$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    			wp_update_attachment_metadata( $attach_id, $attach_data );
    			// set the featured image
    			update_post_meta($post_id, '_thumbnail_id', $attach_id);
    		}
    	}
    }

    One more suggestion, just try to make your codes as DRY as possible. I see repetitions in your codes.

    Thanks..

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Programmatically set thumbnail via URL – IF ELSEIF issue’ is closed to new replies.