0

I have creted a script which will fetch content from one of my site and automatically create new post in my wordpress blog.

When I am running that script from browser, its working really cool! post is being created, intended image is being set as featured image but when I am trying to run it from background or as a cron job, post is being created, published but the featured image is not being set.

Please suggest me the proper solution. Here is my code to set the featured image.

$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
        'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => preg_replace('/\.[^.]+$/', '', basename($post_title)),
        'post_content' => 'just xyz',
        'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
if( $featured )
{
    set_post_thumbnail($parent_post_id, $attach_id);
}

Additional info if it can help you in finding the problem. wp_get_attachment_image was not even working exactly after attaching image and executing above code. It was returning empty string.

0

Ohh Sorry, It was my mistake! It was caching problem.

Whoever facing such problems, just try to disable Database Cache(of Total Cache) plugin. This caching is now pre-inistalled in all your new wordpress installation.

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.