WordPress Codesnippets

Programmatically add attachment


ate_attachment_metadata( $attach_id, $file[‘name’] );
wp_update_attachment_metadata( $attach_id, $attach_data );

This code is used to upload a file (e.g. myfile.txt) as an attachment to the post with the ID of 123. The code first declares a file array with the file details, such as its name, type, temporary name, error code and size. Then, the wp_insert_attachment() function is used to add the file as an attachment to the post with the ID of 123. If the wp_generate_attachment_metadata() function does not exist, it is loaded from the WordPress includes/image.php file. Finally, the attachment metadata is generated and updated for the post.

Was this code snippet helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmatically save post

This code creates a WordPress post with the values of the ‘post_title’ and ‘post_content’ variables. It sets the post status to ‘publish’ and the author

Read More »

Create order programmatically

This code creates a new post in the WordPress database with post type ‘shop_order’, post title ‘Order #12345’, post status ‘wc-processing’, and ping status ‘closed’.

Read More »