Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON API Wordpress not showing featured image when uploaded via App

Tags:

json

wordpress

I am facing some unknown issues with wordpress featured image. When I update a featured image from the website; it gets displayed in the app via json.

http://indiafastener.com/api/?json=get_post&post_type=listing-item&id=1377

however when I upload an image via json into the wordpress db; the output is NULL in the image field.

http://indiafastener.com/api/?json=get_post&post_type=listing-item&id=1380

when I see the db; it has the image path and the path does not lead to 404.

Image Path: http://www.indiafastener.com/webservices/listing/uploads/2017-04-01_12-01-40IMG-20150715-WA0004.jpg

Could it be because the image is not there in the wp-content/uploads/2016/02/ folder?

Code to upload the image

require_once('../../wp-config.php');
require_once('../../wp-admin/includes/image.php');
$dirname = "../../wp-content/uploads/2017/01/";
$filename = $_FILES["file"]["name"];

$attachment = array(
    'post_mime_type' => 'image/jpeg',
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
    'post_content' => '',
    'post_status' => 'inherit',
    'guid' => $dirname.basename($filename)
//'wp-content/uploads/2017/01/' . basename($filename)
);
$your_post_id  = 1392;
$attach_id = wp_insert_attachment( $attachment, $filename,'$your_post_id' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
//$id=1385;
update_post_meta($id, '_thumbnail_id', $attach_id);
echo "success";

Any help on this will be highly appreciated.

Screenshots

DB post_type attachment of image uploaded via app enter image description here

DB Post linked to the image Id enter image description here

Missing Image Preview: enter image description here

like image 549
Utpal - Ur Best Pal Avatar asked Jan 06 '17 07:01

Utpal - Ur Best Pal


1 Answers

I am not sure about your code but my below piece of code is working perfectly for assign image as feature image for post. please go through it. attachment id should be assign to particulate post, check your post meta '_thumbnail_id' for post as well.

require_once(ABSPATH . 'wp-admin/includes/image.php');

$filename = 'your file name';

$attachment = array(
    'post_mime_type' => 'your mime type',
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
    'post_content' => '',
    'post_status' => 'inherit',
    'guid' => $wp_upload_dir['url'] . '/' . basename($filename)
);
$attach_id = wp_insert_attachment( $attachment, $filename,'your_post_id' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
update_post_meta($id, '_thumbnail_id', $attach_id);
like image 105
Ash Patel Avatar answered Nov 08 '22 21:11

Ash Patel