How to upload post thumbnail while wp_insert_post?
Question
I am trying post submit on front end. All works without thumbnail uploading and setting. Here is my html form.
<form method="post" action="">
<input type="text" name="title">
<textarea name="content"></textarea>
<input type="file" name="thumbnail">
<input type="submit" name="submit">
</form>
And here is my php code.
<?php
if (isset($_POST['submit'])) {
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$title = $_POST['title'];
$content = $_POST['content'];
# Set Post
$new_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'pending',
'post_type' => 'post',
);
$post_id = wp_insert_post($new_post);
# Set Thumbnail
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'pending',
'post_parent' => $post_id
);
$attachments = get_posts($args);
foreach($attachments as $attachment){
$attachment_id = media_handle_upload('thumbnail', $attachment->ID);
}
if (!is_wp_error($attachment_id)) {
set_post_thumbnail($post_id, $attachment_id);
header("Location: " . $_SERVER['HTTP_REFERER'] . "/?files=uploaded");
}
}
?>
It creates post ok. But it not sets any thumbnail. I don’t know where i am wrong.
0
front-end, posts, uploads
3 years
2020-03-27T12:51:25-05:00
2020-03-27T12:51:25-05:00 0 Answers
136 views
0
Leave an answer