Programmatically set thumbnail via URL – IF ELSEIF issue
-
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); } } }
- The topic ‘Programmatically set thumbnail via URL – IF ELSEIF issue’ is closed to new replies.