Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding posts with thumbnail programmatically in WordPress

I know I can use the wp_insert_post() function in WordPress to add posts programmatically, but I want to add posts with a thumbnail, and for that matter, also resize/crop the post photo to the correct WordPress sizes.

Is all this possible programmatically, or do I need to do some work manually (i.e. the resizing/cropping)?

like image 576
rebellion Avatar asked Apr 20 '10 09:04

rebellion


People also ask

How do I add a featured image in WordPress post programmatically?

Create HTML Form We require a form with file input and a submit button to add the featured image via coding. So, in the page template, paste the HTML below. This code shows a form with a file input field and a submit button. We can also include a hidden field with a nonce value.

How do I add multiple thumbnails to featured images in WordPress?

To add a dynamic featured image, just click on the box. Your WordPress media library will automatically open up and from here. Simply select the added featured image that you want. Note: Even though you can add as many images as you want, you will have to add them one at a time.


2 Answers

Check out wp_insert_attachment(), found in wp-includes/post.php (Codex article).

So you create your post first using wp_insert_post(), then attach the file, somewhat like this (modified the Codex):

<?php 
    $post_id = wp_insert_post( $my_post_data ); 

    $attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id,  $attach_data );
    set_post_thumbnail( $post_id, $attach_id );
?>

Regarding image resizing/cropping, if you go to your media settings (yoursite.com/wp-admin/options-media.php), you can define custom sizes for your images. Probably not as robust as you're looking for, but if you integrate the output with something like the TimThumb Script, you may get close to what you're looking for.

To see all the variables that the function has, read the commented info in post.php.

like image 111
John K Avatar answered Sep 24 '22 01:09

John K


After you insert the post and the attachment using wordpress' wp_insert_post and wp_insert_attachment functions, you can add the thumbnail to the post using the _thumbnail_id with the attachment's id, as long as your theme supports post thumbnails.

// $post_id = wp_insert_post(...)
// $attach_id = wp_insert_attachment(...)

add_post_meta($post_id, '_thumbnail_id', $attach_id, true);

This way you'll be able to use wordpress default functions for thumbnail resizing and such.

like image 34
guigouz Avatar answered Sep 24 '22 01:09

guigouz