Insert new Post with Feature Image From web services / API in Wordpress

Hello Developers,
  If you want to insert new post from Web Service in Wordpress.

Create a file add_post.php in your api folder
paste below code :

<?php
require ("../wp-load.php");

if ( $_REQUEST['title'] != "") {
$post = array(
'post_content'   => $_REQUEST['Description'] , // The full text of the post.
'post_title'     => $_REQUEST['title'], // The title of your post.
'post_status'    => 'draft' , // Default 'draft'.
'post_type'      => 'product', // Default 'post'.
'post_author'    => $_REQUEST['user_id'], // The user ID number of the author. Default is the current user ID.
);  
$post_id = wp_insert_post( $post, false);


if ( $_FILES['ProductImage']['name'] != "" ) {
global $wpdb;
//For Uploading photo from front End
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
$uploadedfile = $_FILES['ProductImage'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );

$filename = $movefile['file'];

$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename);
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

$a = add_post_meta($post_id, '_thumbnail_id', $attach_id, true);
}


$ar = array ("reg" => 'true', "msg" => "Product Added Successfully");
echo json_encode( $ar );
exit();

} else {
$ar = array ("reg" => 'false', "msg" => "Require Field Missing");
echo json_encode( $ar );
exit();
}
?>

when you add new post you can get $post_id. With this id you can add many extra parameters in post meta table of wordpress with below code :

update_post_meta($post_id, 'geo_latitude', $_REQUEST['lat']);

For insert new post your url may be look like :
www.webtecso.com/api/add_post.php?title=&user_id=&title=

Comments