set-post-thumbnail wp-ajax return 0 - javascript

i try use the media manager from wordpress i use the post editor outside admin wordpress and users can create a posts whit a featured image.
I use _wp_post_thumbnail_html function to show image or show link to upload file, all users whit a rol "publisher" can upload images and upload work but doesn't work show featured image or assign to post.
on wp-ajax whit action: set-post-thumbnail returns 0 and image aren't assign to new post.
wp-ajax.php:
json:true thumbnail_id:3952
_wpnonce:b02e8553f1 action:set-post-thumbnail
response: 0
My code as:
<?php $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
//$postid = get_post( $post_id );
echo _wp_post_thumbnail_html( $thumbnail_id, $post_id );
?>
<br>
Very simple, show the media manager from wordpres, allow upload featured image but not allow assign to new post. Any solution?
edit: in edit post works fine allow change featured image i suppose because featured image required a post id, but on new post from wordpress allow upload image and asign this to new post.

This is proper image-uploading code.
<?php
global $wpdb;
include ('../../../../wp-load.php');
if ( $_FILES ) {
if(!function_exists('wp_handle_upload')){
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
$upload_overrides = array('test_form' => false);
$response = array();
ini_set('max_execution_time', 0);
foreach($_FILES as $file){
$movefile_profile = wp_handle_upload($file, $upload_overrides);
$filename = $movefile_profile['url'];
$parent_post_id = $post_id; // please provide post id must
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
$filepath = $wp_upload_dir['path'] . '/' . basename( $filename );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filepath );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail($post_id, $attach_id); // this set_post_thumbnail will set you post thumbnail
$response['message'] = 'Done';
}
echo json_encode($response);
die();
}
And for Ajax code, go to this link. If you any problems, then please comment below.

Related

Wordpress unable to save featured image

this is Nadeem I am a beginner on PHP and WordPress, I stuck on one point during custom plugin development, my problem is, I am unable to save Featured image and custom taxonomy tag and category from the frontend. In the meantime, I already Search on Google, StackOverflow, etc. too much for this error solution about this but unfortunately, this does not work and I am stuck at this point from the last 2 weeks.
This is my Plugin PHP code
/**
* The Template for displaying car archives, including the main car-data page which is a post type archive.
*
* Override this template by copying it to yourtheme/car_data/archive-car-data.php
*
* #author Shaikh Nadeem
* #package Car_Data
* #subpackage Car_Data/Templates
* #version 1.0.0
*/
class Car_Frontend_Form
{
function __construct()
{
add_shortcode( 'submit_car', array($this, 'submit_car') );
add_action( 'wp_enqueue_scripts', array( $this, 'my_enqueue' ) );
add_action( 'save_post_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_nopriv_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'init', array( $this, 'submit_car_data_post' ) );
}
public function submit_car() {
echo '<div id="submit_car_form">';
echo '<form id="cd_car" name="cd_car" class="cd_car" method="post" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data" >';
wp_nonce_field( "car-frontend-post" );
echo '<p><label for="title">Title</label><br />';
echo '<input type="text" id="title" value="" size="60" name="title" />';
echo '</p>';
echo '<p>';
echo '<label for="content">Post Content</label><br />';
echo '<textarea id="content" name="content" cols="40" rows="4"></textarea>';
echo '</p>';
echo '<p><label for="feature">Feature:</label><br />';
wp_dropdown_categories( "show_option_none=Feature&tab_index=3&taxonomy=feature&name=feature&id=feature&class=feature" ) .'</p>';
echo '<p><label for="make">Make:</label><br />';
wp_dropdown_categories( "show_option_none=Make&tab_index=4&taxonomy=make&name=make&id=make&class=make" ) .'</p>';
echo '<p><label for="post_tags">Tags</label><br />';
echo ' <input type="text" value="" size="60" name="post_tags" id="post_tags" /></p>';
echo '<p><label for="post_tags">Car Image</label><br />';
echo '<input type="file" name="file" id="file"></p>';
echo '<p align="left"><input type="submit" tabindex="6" id="submit_car" name="submit_car" /></p>';
echo '</form>';
echo '</div>';
return;
}
public function submit_car_data_post() {
if ( isset($_POST['title']) ) {
echo '<script>console.log("file error: '.$fileerror.'<br>");</script>';
$title = sanitize_text_field( $_POST['title'] );
$content = sanitize_text_field( $_POST['content'] );
$author_id = sanitize_text_field( $_POST['author_id'] );
$tags_input = sanitize_text_field( array($_POST['post_tags']) );
$feature = sanitize_text_field( array($_POST['feature']) );
$make = sanitize_text_field( array($_POST['make']) );
// $image = $_POST['file'];
$args = array(
'post_title' => $title,
'post_content' => $content,
'tags_input' => $_POST['post_tags'],
'author' => $author_id,
'post_status' => 'publish',
'post_type' => 'car-data',
'tax_input' => array(
$feature,
$make
),
// 'post_category' => array(
// 'feature' => array($_POST['feature']),
// 'make' => array($_POST['make'])
// )
);
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'car-frontend-post') ) {
return;
}
if( is_wp_error( $posts ) ){
echo json_encode( $posts->get_error_messages() );
}
// save frontend Post
$posts = wp_insert_post( $args );
// save frontend Texonomy
wp_set_object_terms( $posts, $feature, 'feature' );
wp_set_object_terms( $posts, $make, 'make' );
// save Atachment on featured image for the current custom post
$uploaddir = wp_upload_dir();
$file = $_FILES[$image];
$uploadfile = $uploaddir['path'] . '/' . basename( $file );
move_uploaded_file( $_FILES['file']['tmp_name'], $uploaddir['path'] . '/' . $filename );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => preg_replace('/\.[^.]+$/', '', $filename),
'post_excerpt' => preg_replace('/\.[^.]+$/', '', $filename),
'post_status' => 'inherit',
'post_type' => 'attachment',
'menu_order' => $_i + 1000,
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata($attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
wp_die();
}
}
public function my_enqueue() {
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
}
and i use javascript for the ajax alert message when form is submit
jQuery(document).ready(function($) {
$('.cd_car').on('submit', function(event) {
event.preventDefault();
var message = document.getElementById("file").value;
var empt = document.forms["cd_car"]["title"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
else
{
$.ajax({
type: 'post',
// url : ajax_object.ajaxurl,
data : $('.cd_car').serialize(),
success : function(data){
alert(message);
console.log(data);
},
error : function(data){
alert(message);
alert('fail');
}
});
}
});
});
Also i have there one error on this line code if ( isset($_POST['title']) ) unable to use submit key on isset post only title is working here.
I believe your issue is due to sanitize_text_field( array( .. )). sanitize_text_field only accepts strings as the parameter, so I assume by sending in an Array it's actually always seeing the string "Array" - not your POST values.
To sanitize the array, could do something like:
$tags_input = array();
if ( isset($_POST['post_tags']) && !empty($_POST['post_tags']) ) {
foreach ($_POST['post_tags'] as $val)
$tags_input[] = sanitize_text_field( $val );
}
// [ .. repeat for feature & make .. ]
Or, if they're single values only (not arrays), simply remove the array wrapper.

How to post image to custom field of my custom post type when it returns data:image\/jpeg;base64 string through Ajax?

I implemented my custom form and I need to post Image to custom field of my Custom Post Type, but it did not worked, cause image returns long string in base64 encoding...
javascript, ajax:
// get values to an array()
var requestArray = "";
requestArray = {"name" : $("#nameAdvertisement").val(),
"category" : $("#categoryAdvertisement").val(),
"description" : $("#descriptionAdvertisement").val(),
"photo" : $("#photoAdvertisement").val(),
"photoAdvertisement" : $("#pro-img-4").attr('src')};
$.ajax({
url: ajaxurl,
type: "POST",
data: {"action": "addAdvertisement", "formValidation": requestArray},
//dataType: "html",
success: function (data) {
}
});
functions.php, where code is incoming for posting my data ( $getData['photoAdvertisement'] represents long image string)
$getData = $_POST['formValidation'];
// Create post object
$my_post = array(
'post_title' => 'New Posts with Image',
'post_content' => 'Some testing content',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'inzeraty'
);
// Insert the post into the database
$post_id = wp_insert_post( $my_post);
add_post_meta($post_id, 'name', 'Name of New post', true);
add_post_meta($post_id, 'description', 'Description of new Post', true);
add_post_meta($post_id, 'photo', $getData['photoAdvertisement'], true);
This will need to be tweaked -
This works with URls of images, but not sure how you will get the $image_data through post.
First, you will need to decode the base64 image.
$newImageFile = base64_decode($getData['photoAdvertisement']);
Then you will need to find the directories to work with :
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($newImageFile);
$filename = basename($newImageFile);
Now that you have a filename, you can check if the file and the filename already exists in your library
if(wp_mkdir_p($upload_dir['path'])) $file = $upload_dir['path'] . '/' . $filename;
else $file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
You will need the functionalities of post.php - so if you don't have it yet, then include it.
if ( ! function_exists( 'post_exists' ) ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
this way you can check, if the same filename has already been used in your library like this
if (post_exists($filename)){
//Do whatever - maybe update the alt or something.
}else {
//The file does not exist, and can be inserted.
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// $post_id comes from your earlier insertion
// You will need the functions from image.php as well..
require_once(ABSPATH . 'wp-admin/includes/image.php');
//Now we will generate the new image metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
$res1= wp_update_attachment_metadata( $attach_id, $attach_data );
$filealt = "You alternative text here - maybe sanitize the filename or make an input for it";
//attach the metadata to the image
update_post_meta($attach_id, '_wp_attachment_image_alt', $filealt); // Add the alt text
//Now you can add the image to your meta fields
add_post_meta($post_id, 'photo', $attach_id);
}
Note, I have not tested this.
You will probably need to tweak it a little - Especially around the file_get_contents($newImageFile); part.
NOTE : This has to be done after your $post_id = wp_insert_post( $my_post); part
Good luck with it!

How to create a text file using php from the parameters passed to html page in url?

I need my page bargraph.html to get parameters like .../bargraph.html?di=xxxx&mn=yyyy and save the values of di and mn using a php script in a text file named cred.txt. The code I'm using for bargraph.html is
<body>
<?php
$mobile_num = $_GET["mn"];
$device_id = $_GET["di"];
$file_name = "cred.txt";
$location = "cred/".$file_name;
$text = $mobile_num."\n".$mobile_num;
$my_file = fopen($location, "w") or die("Unable to open file!");
fwrite($my_file, $text);
echo "response submitted successfully!";
fclose($my_file);
?>
</body>
The file named cred.txt is not created inside the cred/ directory and neither I get any errors. What am I doing wrong?
If the same thing can be done using JavaScript I'll use that instead of php for this purpose.
The question references bargraph.html - presumably the php code that you have is NOT on that page but a separate script? If that is the case then if you were to use exception handling to try to track down the issue it might help. Also, I have always found better success when using full paths as opposed to relative ones
<?php
if( isset( $_GET['mn'], $_GET['di'] ) ){
try{
$filename='cred.txt';
$mobile_num=filter_input( INPUT_GET, 'mn', FILTER_SANITIZE_STRING );
$device_id=filter_input( INPUT_GET, 'di', FILTER_SANITIZE_STRING );
/*
I have always found it is best to use a full path rather than relative
Change `path/to/` to the appropriate path
*/
$path=$_SERVER['DOCUMENT_ROOT'] . '/path/to/cred';
/* If the path does not exist, warn user */
if( !realpath( $path ) ){
throw new Exception( sprintf( 'Unable to find path: %s', $path ) );
}
/* Can the chosen directory be read? */
if( is_readable( $path ) && is_writable( $path ) ){
$file=$path . '/' . $filename;
#$text=$mobile_num . PHP_EOL . $mobile_num . PHP_EOL;
/* I think this is probably what you intended? */
$text=$device_id . PHP_EOL . $mobile_num . PHP_EOL;
$status=file_put_contents( $file, $text, FILE_APPEND | FILE_TEXT );
throw new Exception( $status ? sprintf('All good! Saved %s',$file) : sprintf('Error - unable to save %s',$file) );
} else {
/*
should set permissions if reading/writing of target folder failed
chmod($path,0777); etc
*/
throw new Exception( sprintf( 'The path %s is either not readable or writable',$path ));
}
}catch( Exception $e ){
exit( $e->getMessage() );
}
}
?>
Using a plain HTML page you could send an ajax request to the above PHP script ( in code below called bargraph.php )
<html>
<head>
<title>ajax-store credentials</title>
</head>
<body>
<form id='bg'>
<input type='text' name='mn' id='mn' placeholder='Mobile number: eg 0141 353 3874' />
<input type='text' name='di' id='di' placeholder='Device ID: eg yellow banana' />
<input type='button' id='bttn' value='Go' />
</form>
<script>
document.getElementById('bttn').onclick=function(e){
var mn=document.getElementById('mn').value;
var di=document.getElementById('di').value;
if( mn != '' && di != '' ){
var xhr=new XMLHttpRequest();
xhr.onload=function(r){
document.getElementById('status').innerHTML=this.response;
};
xhr.onerror=function(r){
document.getElementById('status').innerHTML=err.message;
};
xhr.open('GET','?mn='+mn+'&di='+di,true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
}
}
</script>
<div id='status'></div>
</body>
</html>
You can do like this.
$mobile_num = $_GET["mn"];
$device_id = $_GET["di"];
$file_name = "cred.txt";
$path = getcwd();
$location = $path.'/cred/'.$file_name;
$text = $device_id."\n".$mobile_num;
$my_file = fopen($location, "w") or die("Unable to open file!");
fwrite($my_file, $text);
echo "response submitted successfully!";
fclose($my_file);
You need to give write permission on cred folder.

How to consume here.com's REST api service

Has anyone tried using here.com's rest api?
I'm trying to run an example request, but nothing happens. I'm new to REST, so I'm clueless about the problem. If the $url is plugged directly into the browsers address text box, the image is displayed, but my curl function in the code below does not retrieve anything, or so it seems.
$url = "http://image.maps.cit.api.here.com/mia/1.6/route?app_id=redacted&app_code=redacted&r0=52.5338,13.2966,52.538361,13.325329&r1=52.540867,13.262444,52.536691,13.264561,52.529172,13.268337,52.528337,13.273144,52.52583,13.27898,52.518728,13.279667&m0=52.5338,13.2966,52.538361,13.325329&m1=52.540867,13.262444,52.518728,13.279667&lc0=440000ff&sc0=440000ff&lw0=6&lc1=44ff00ff&sc1=44ff00ff&lw1=3";
$ch = curl_init($url);
$options = array(
CURLOPT_CONNECTTIMEOUT => 20 ,
CURLOPT_AUTOREFERER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$result = json_decode($response);
echo "response: <br>";
echo "<br>";
echo "result: <br> " . $result;
curl_close($ch);
I found the error in the end.. This is a working sample of using the here.com REST api that I'm posting so that anyone who is in the same situation may have a look at it. The problem was that the construction of the query string was incorrect as I just copied and pasted it from the browser. If anybody comes across the same problem, I recommend taking a look at the documentation here..
$base_url = 'http://image.maps.cit.api.here.com';
$path = '/mia/1.6/';
$resource = 'route'; // type of service... this should change if you want something else
$query_string = array(
'app_id' => 'XXXXXXXXXXXXXXXXXXXXXX', //your app id
'app_code' => 'XXXXXXXXXXXXXXXXXXXXXX', // your app code
'r0' => '52.540867,13.262444,52.536691,13.264561,52.529172,13.268337,52.528337,13.273144,52.52583,13.27898,52.518728,13.279667', // coords for the route
'lw' => '4', // line width
'lc' => '00ff00', // line color
);
$url = $base_url . $path.$resource . '?' . http_build_query($query_string);
$img_file = './img/test_img2.jpg'; // save image here
$ch = curl_init($url);
$fp = fopen($img_file, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
<img src='<?php echo $img_file;?>'>

Special Characters encoding in textareas

I'm pulling contents from text files into a textarea to be used and noticed it appeared that slashes were appearing near quotes and apostrophes. I was able to resolve that by disabling magic quotes on the server, however I noticed that special characters still don't seem to display properly.
What I am trying to figure out is there a way when retrieving the file to decode/encode them properly or to encode them so they're UTF 8 compliant in the first place? Below is my coding for retrieving the files:
<?php
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file ) {
if ( ! is_dir( $file ) ) {
$filesContents[$file] = file_get_contents($directory , $file);
echo '<option value="'. $file .'">' . $file . '</option>';
}
}
?>
</select>
and below is my save script:
if($_POST['Action'] == "SAVE") {
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) {
echo 'There is no session username';
}
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) {
echo 'There is no POST desired filename';
}
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
endif;
header('Location: mysite.site/evo/codesaveindex.php?saved=1&file='.$FILENAME);
}
?>

Categories