Wordpress Insert Featured Image wp_insert_post

Asked

Viewed 354 times

0

Hello I’m with this code below that inserts a post in Wordpress.

In addition to the title, I would like to insert a highlighted image someone knows how to do this ?

Follow the code below I’m using:

 <form action="" method="post">

<input name="Nome" value="Titulo do post">
 
<input type="file">

<button type="submit">Enviar</button>
</form>

<?php 
$my_post = array(
     'post_type' => 'post',
     'post_status' => 'publish',
     'post_title' => $_POST['Nome'],
     
  );
  
$post_id = wp_insert_post($my_post);

?>

  • You want to show image when selecting ?

  • Matheus would like to select

  • After selecting, show photo ?

  • Then insert in the post in the Wordpress panel as highlighted image

  • Sorry, I was getting something else ...

1 answer

0

Hello people who look for the same already solved follows the code below`

<form method="post" action="" id="quick-post-form" enctype="multipart/form-data">

<input name="Nome" value="Titulo do post">
 
 
<input type="file"  name="image-uploader" id="img-upload">

<button type="submit">Enviar</button>
</form>


<?php
// Functions.php content:
function insert_attachment($file_handler,$post_id,$setthumb='false') {
    // check to make sure its a successful upload
    if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
 
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
 
    $attach_id = media_handle_upload( $file_handler, $post_id );

$filetype = wp_check_filetype('$attach_id');
echo $filetype['type'];

    if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
    return $attach_id;
}



// Post form content:
     $post_id = wp_insert_post(
			array(
				//'comment_status'	=>	'open',
				//'ping_status'		=>	'closed',
				//'post_author'		=>	$user_id,
				//'post_name'		    =>	$slug,
				'post_title'		=>	$_POST['Nome'],
				'post_status'		=>	'publish',
				'post_type'		    =>	'post',
                //'post_content'		=>  $_POST['quick-post-area'],
                //'post_category' => array( 3 ),
			)
		);
if ($_FILES) {
    foreach ($_FILES as $file => $array) {
    $newupload = insert_attachment($file,$post_id);
    // $newupload returns the attachment id of the file that
    // was just uploaded. Do whatever you want with that now.
    }
}
?>

`

Browser other questions tagged

You are not signed in. Login or sign up in order to post.