0

EDIT3: I have gotten some outside help and have totally changed my code around to now use xpath to select the div instead of using the nth img from the html source. I am happy to say this is working! Now the issue I have is adding an ELSEIF to evaluate different categories instead of just the one. I seem to have boxed myself in with this logic. I have tried adding the ELSEIF inside the "if ( in_array( 'Mongolia.GoGo.mn', $cat_name ) )" loop but that just threw an unexpected ELSEIF error. Again I'm lost... Here is the code:

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;
    }

    // get all image tags
    //if ( get_post_meta($post_id, '_apt_skip_post_thumb', true) ) {
        if ( in_array( 'Mongolia.GoGo.mn', $cat_name ) ) {
            // get custom post field
            $custom_fields = get_post_custom($post_id);
            $htmlURL = $custom_fields['original_guid'][0];
            // try to load the webpage
            $dom = new domDocument;

            @$dom->loadHTML(file_get_contents($htmlURL));



            $finder = new DomXPath($dom);
            $classname="newscover";
            $content = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
            $imageURL = '';
            if($content->length){
                if($content->item(0)->childNodes->length > 1){
                    $imageURL = $content->item(0)->childNodes->item(1)->getAttribute('src');
                }
            }else{
                $content = $dom->getElementById('ncbubuhome');

                @$dom->loadHTML($content->nodeValue);

                $images = $dom->getElementsByTagName('img');

                foreach ($content->childNodes as $node) {
                    if($node->nodeName != '#text'){
                        foreach ($node->childNodes as $childNode) {
                            if($childNode->nodeName == 'img'){
                                $imageURL = $childNode->getAttribute('src');
                                break;
                            }
                        }
                    }
                }

            }

            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);
            }
        }

    //}
}

Original text: 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.

(This logic is obsolete. Now I'm using xpath to select the class I want) 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.

//former obsolete code snippet

EDIT2: Well I'm still working on this. I've gotten some help from the Wordpress forums to change my code some but this function still doesn't seem to be working. The logic here seems very straightforward but it's not working. I just don't get it... Here is my current code.

//former obsolete code snippet 2

  • Can you try logging the $post_id and $post function arguments within your auto_featured_image_publish_post callback when you both publish a post and try to update an already published post and tell us the result of the log statement? Also I'd suggest removing the first code snippet since it is obsolete and clutters this question thread making it harder to understand. – Adam Apr 4 '15 at 2:33
  • Thanks userabuser. I figured out the sticking point I was on. I've taken a different path and got it working. The issue I have now is described in EDIT3. – Robert Ritz Apr 5 '15 at 10:10
  • Glad it's working for you now... – Adam Apr 6 '15 at 1:07
1

Ok I got it! Here is the code I used:

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 = 'http://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 = 'http://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);
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.