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
DB Post linked to the image Id
Missing Image Preview:
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);
Related
I'm trying to write the product details from a woocommerce product page to a downloadable CSV, on the click of a button.
Similar structure to this:
<?php
$header_args = array( 'SKU', 'Description', 'Price' );
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=csv_export.csv');
$output = fopen( 'php://output', 'w' );
ob_end_clean();
fputcsv($output, $header_args);
$data = array(
'0' => array( '$product->get_sku();', '$product->get_description();', '$product->get_price();' ),
);
foreach($data AS $data_item){
fputcsv($output, $data_item);
}
exit;
?>
Can someone assist on how I can alter this code? so on a button click or link click, a CSV will download with SKU, Description & Price?
I am trying to integrate an API into my Wordpress plugin. The following PHP code successfully connects to the API and retrieves a list of Estates (the API is from a real-estate software):
$url = 'https://api.whise.eu/v1/estates/list';
$body = array(
'Filter' => array( 'languageId' => 'nl-BE'),
);
$args = array(
'headers' => array( 'Authorization' => 'Bearer ' . $token),
'body' => json_decode($body)
);
$response = wp_remote_post($url,$args);
As per the documentation (http://api.whise.eu/WebsiteDesigner.html#operation/Estates_GetEstates) it is possible to filter the results, but I haven't been able to get this to work. I don't have much experience with APIs and JSON, so I might be missing something here.
The code above still retrieves the data in English, even though I added the language filter as explained in the docs. When I replace 'body' => json_decode($body) with 'body' => $body, I get the following response:
{"Message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource."}
Thanks!
Just so that this question doesn't go unanswered:
You need to add the Content-Type header and set it to application/json. This is so the endpoint can interpret your data as a JSON string.
You also need to change 'body' => json_decode($body) to 'body' => json_encode($body) as you want to convert your $body array into a JSON string (see json_decode() vs json_encode()).
This is how your code should look now:
$url = 'https://api.whise.eu/v1/estates/list';
$body = array(
'Filter' => array( 'languageId' => 'nl-BE'),
);
$args = array(
'headers' => array(
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json'
),
'body' => json_encode($body)
);
$response = wp_remote_post($url,$args);
i'm facing problems into cURL. here i can get the json data from another source code and also i got some ideas. but really i can't save the json data into my own server in sql database. i wanna to retrieve the data from
url: https://jamuna.tv/wp-json/wp/v2/posts
and wanna to save into my server (mysql).
here is the $url json data i wanna to save in mysql server:
id
date
link
title
content
author
categories
wp:attachment
and i want to save them into mysql database. my table name is "news" and i want to save them into my table columns.
id [id]
title [title]
description [content]
date [date]
category [categories]
thumbnail [wp:attachment]
admin [author]
here i'm mark the json from url and replaced into my sql columns name. if anyone can give me the instructions about how i can fetch the data from user and save into mysql.
thanks advance.
There is an implementation of your desired with PHP. You must check if values are valid or not or if the array members exist or not. This is just a primitive implementation of your example.
<!DOCTYPE html>
<html>
<body>
<?php
// db connection
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$db = new PDO('mysql:host=localhost;dbname=test;', 'user', 'pass', $options);
// download json from url
$json = file_get_contents('https://jamuna.tv/wp-json/wp/v2/posts');
echo '<br/>';
$sql = "INSERT INTO `mytable` (`id`,`title`,`description`,`date`,`category`,`thumbnail`,`admin`)
VALUES (:id, :title, :content , :date, :categories, :attachment, :author)";
$stm = $db->prepare($sql);
// parse JSON
$arr = json_decode($json, true);
$i = 0;
foreach ($arr as $record) {
echo "==================Insert record " . $i ++ . "<br>";
$data = array(
':id' => $record['id'],
':title' => $record['title']['rendered'],
':content' => $record['content']['rendered'],
':date' => $record['date'],
':categories' => $record['categories'][0],
':attachment' => $record['_links']['wp:attachment'][0]['href'],
':author' => $record['author']
);
var_dump($data);
// inserting a record
$stm->execute($data);
}
?>
</body>
</html>
I am trying to send an email with attachment when I used var_dump($filename)it returns the filename and gettype($filename) it returns string. but when I am trying to send an attachment it still returns Unable to open file for reading [filename.pdf] even if $file_attachment was looped I tried to change UploadedFile::getInstancesByName('file_attachment'); to UploadedFile::getInstanceByName('file_attachment'); but nothing happened. Please help me.
This is my controller
if(Yii::$app->request->isPost){
$email = Yii::$app->request->post('email');
$message = Yii::$app->request->post('message');
$file_attachment = UploadedFile::getInstancesByName('file_attachment');
if($file_attachment){
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message);
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach($filename);
}
//$mail->send();
//echo gettype($filename);
// var_dump($filename);
$mail->send();
}else{
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message)
->send();
}
}
This is the view
<?php
echo FileInput::widget([
'name' => 'file_attachment',
'attribute' => 'file_attachment',
'options' => ['multiple' => true]
]);
?>
The baseName property of yii\web\UploadedFile contains the original filename but the file is not present on the server under its original filename. You need to use tempName property that contains path to the uploaded file on server.
Your for each cycle that attaches files to mail should look like:
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach(
$file->tempName,
['fileName' => $filename]
);
}
It might also be a good idea to check hasError property of yii\web\UploadedFile before attempting to attach file to see if the upload was successful.
Also make sure that you've set 'enctype' => 'multipart/form-data' in you form options when you are not using ActiveForm with ActiveField::fileInput() otherwise the files might not be uploaded.
In following code, I'm trying to create a new category (name = 'To be deleted') and then I want to delete it.
first part of the code working fine and I can see new record in the database every time I run the unit test
but I'm having a problem with recode deletion. what's wrong with my code
public function testCategoryDeletion()
{
$user = \App\User::find(1);
//dd($user->name);
$category = \App\Category::create(['name' => 'To be deleted']);
//dd($category->id);
$response = $this->actingAs($user, 'api')
->json('DELETE', "/api/category/{$category->id}")
->assertStatus(200)->assertJson([
'status' => true,
'message' => 'Category Deleted',
]);
}
Test case output
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API> ./vendor/bin/phpunit
PHPUnit 7.5.7 by Sebastian Bergmann and contributors.
. . . . . . . 7 / 7 (100%)
Time: 1.53 minutes, Memory: 18.00 MB
OK (7 tests, 65 assertions)
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API>
In database, recode is created but not deleted,
I fixed the controller as follows and now its working,
public function destroy(Category $category)
{
$status = $category->delete();
return response()->json([
'status' => $status,
'message' => $status ? 'Category Deleted' : 'Error Deleting Category'
]);
}
API routes
Route::group(['middleware' => 'auth:api'], function(){
Route::resource('/task', 'TaskController');
Route::resource('/category', 'CategoryController');
Route::get('/category/{category}/tasks', 'CategoryController#tasks');
});