WordPress API JSON output not valid with quotes - json

I have a custom function that outputs a Json
However the Json Output has always quotes added and is thus unvalid.
function my_callback( $data ) {
$zz999_ids = do_shortcode('[wpv-view name="json-zz999-ids"]');
//$result = do_shortcode('[wpv-view name="json-traject-bus" ids="'.$zz999_ids.'"]');
$result = '[{"bus_id":"BC025","traject_id":"D","traject_show":[["06:00-08:16"]]}]';
return print_r($result, true);
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/traject2/', array(
'methods' => 'GET',
'callback' => 'my_callback',
) );
} );
The result I get is: "[{\"bus_id\":\"BC025\",\"traject_id\":\"D\",\"traject_show\":[[\"06:00-08:16\"]]}]"
I just replaced the $result with a teststring. It is exactly same format that comes through the function.
How to get rid of those outer quotes?

function my_callback( $data ) {
$zz999_ids = do_shortcode('[wpv-view name="json-zz999-ids"]');
//$result = do_shortcode('[wpv-view name="json-traject-bus" ids="'.$zz999_ids.'"]');
$result = '[{"bus_id":"BC025","traject_id":"D","traject_show":[["06:00-08:16"]]}]';
$result = json_decode($result);
return $result;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/traject2/', array(
'methods' => 'GET',
'callback' => 'my_callback',
) );
} );
For you better understanding about json_decode please visit here

Related

How to apply pagination for custom endpoint request in wordpress?

I have created a custom restful API endpoint in WordPress which returns the JSON with the only required fields.
So with this one when I go to the example.com/wp-json/wl/posts, it returns 5 posts as I have limited the number of the posts.
function wl_posts() {
$args = [
'numberposts' => 99999,
'post_type' => 'post'
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach($posts as $post) {
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['slug'] = $post->post_name;
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$i++;
}
return $data;
}
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'posts', [
'methods' => 'GET',
'callback' => 'wl_posts',
]);
});
But I also want to add the pagination, so if I add ?page=2 , it should return another 5 posts.
How can that be archived?
When visiting /?rest_route=/ or /wp-json/wp/v2/pages you can drill down into ie. wp/v2/pages/endpoints/0/args then check with page and per_page
curl http://YOUR-SITE/wp-json/wl/v1/posts/?per_page=1&page=2
Publish arguments for reference
We can define and publish these as arguments. This is not required but they are now in line with posts and pages
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'posts', [
'methods' => 'GET',
'callback' => 'wl_posts',
'args' => [
'page' => [
'description' => 'Current page',
'type' => "integer",
],
'per_page' => [
'description' => 'Items per page',
'type' => "integer",
]
],
]);
});
Fetch arguments
As get_posts has its own logic and it uses WP_Query in the end let's use WP_Query for the better.
function wl_posts() {
$args = [];
if (isset($_REQUEST['per_page'])) {
$args['posts_per_page'] = (int) $_REQUEST['per_page'];
}
if (isset($_REQUEST['page'])) {
$args['page'] = (int) $_REQUEST['page'];
}
$args['post_type'] = 'post';
$get_posts = new WP_Query;
$posts= $get_posts->query( $args );
$data = [];
$i = 0;
foreach($posts as $post) {
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['slug'] = $post->post_name;
$data[$i]['featured_image']['thumbnail'] =
get_the_post_thumbnail_url($post->ID, 'thumbnail');
$i++;
}
return $data;
}

Query Wordpress Database after AJAX Call - Getting an Error of Call to a member function get_results() on null

I am trying to query the WP Database but I am receiving an error of Call to a member function get_results() on null. I believe I need to somehow register wpdb but despite reading through multiple similar questions I can't piece together what needs to be done. Any help is greatly appreciated as I am new and learning Wordpress and Ajax.
My JS file is called zip-search-popup.js
(function($) {
$(document).ready(function() {
$('.zip-bar-button').click(function(event) {
event.preventDefault();
submittedZip = $("#zipcode-bar-input").val();
$.ajax({
//need an automatic URL so that this doesn't need to be updated
url: from_php.ajax_url,
type: "GET",
data: {
action : 'zip_search',
submittedZip : submittedZip,
},
success: function (response) {
console.log(response);
alert("working");
}
})
$('.zip-search-popup-con').fadeToggle(350);
})
$('.zip-search-dismiss').click(function() {
$('.zip-search-popup-con').toggle();
})
})
})(jQuery);
I have registered my scripts in functions.php and have my SQL query function within here as well.
add_action('wp_enqueue_scripts', 'hyix_enqueue_custom_js');
function hyix_enqueue_custom_js() {
//enqueue zip-search-popup.js
wp_enqueue_script('zip-search-popup', get_stylesheet_directory_uri().'/js/zip-search-popup.js', array('jquery'), false, true);
wp_localize_script('zip-search-popup', 'from_php', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
//hook zip-search-popup function into ajax
add_action( 'wp_ajax_zip_search', 'ajax_zip_search' );
//same hook for users not logged in
add_action( 'wp_ajax_nopriv_zip_search', 'ajax_zip_search' );
//query for pulling in shipping data
function ajax_zip_search() {
$submitted_zip = $_REQUEST['submittedZip'];
global $wpdb;
// The SQL query
$response = $wpdb-> get_results("SELECT {$wpdb->prefix}woocommerce_shipping_zones.zone_name ".
"FROM {$wpdb->prefix}woocommerce_shipping_zone_locations ".
"INNER JOIN {$wpdb->prefix}woocommerce_shipping_zones ".
"ON {$wpdb->prefix}woocommerce_shipping_zone_locations.zone_id = {$wpdb->prefix}woocommerce_shipping_zones.zone_id ".
"WHERE location_code = '$submittedZip' ");
$response = array(
'request' => $_REQUEST,
'zip' => $submitted_zip,
'test' => 'is ok',
);
wp_send_json( $response );
// echo $response;
die();
}
You should use the Wordpress-Way to use AJAX
All Ajax-Request will be recieved by wp-admin/admin-ajax.php which fires the Ajax-Hooks which run your PHP-Code. The Ajax-Hook depends from the action-parameter in your Ajax-Request.
With wp_localize_script() you can provide some data from PHP to Javascript, i.e. the ajax_url.
Place this code in your functions.php. This include the code that handles your Ajax-Request.
add_action('wp_enqueue_scripts', 'hyix_enqueue_custom_js');
function hyix_enqueue_custom_js() {
//enqueue zip-search-popup.js
wp_enqueue_script('zip-search-popup', get_stylesheet_directory_uri().'/js/zip-search-popup.js', array('jquery'), false, true);
wp_localize_script('zip-search-popup', 'from_php', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_ajax_zip_search', 'ajax_zip_search' );
add_action( 'wp_ajax_nopriv_zip_search', 'ajax_zip_search' );
function ajax_zip_search() {
$submitted_zip = $_REQUEST['submittedZip'];
// do some zip search
$response = array(
'request' => $_REQUEST,
'zip' => $submitted_zip,
'test' => 'is ok',
'foo' => 'bar'
);
wp_send_json( $response );
}
Now you can use the ajax_url provided by wp_localize_script(). Don't forget to send an action-parameter:
$.ajax({
url: from_php.ajax_url,
type: "GET",
data: {
action: 'zip_search',
submittedZip: submittedZip
},
success: function (response) {
console.log(response);
alert('it works');
}
});

JSON WP REST API getting featured image by Taxonomy Terms

I'm trying to get a featured-image from my custom taxonomy-*projects* term-*elfla*.
I managed to get a image from the posts with this code what i found here but I don't understand how to do it with taxonomy terms.
At this point I do not understand how to get the featured image source and whether the 'GET' request url is correct.
JS:
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET','http://localhost/test/wordpress/wp-json/wp/v2/posts/?filter=projects&filter=elfla&_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
portfolioPostsBtn.remove();
console.log(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
});
}
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < postsData.length; i++) {
ourHTMLString += '<img src="'+postsData[i].featured_image_thumbnail_url+ '" alt="img">';
}
portfolioPostsContainer.innerHTML = ourHTMLString;
}
Functions.php
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
$thumbnail_id = get_term_meta( $post->ID , 'thumbnlai' false );
$thumbnail = wp_get_attachment_image_src( $thumbnail_id );
$_data['featured_image_thumbnail_url'] = $thumbnail[0];
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
Use this function.
**function custom_api_get_all_posts() {
register_rest_route( 'custom/v1', '/all-posts', array(
'methods' => 'GET',
'callback' => 'custom_api_get_all_posts_callback'
)); }
function custom_api_get_all_posts_callback( $request ) {
// Initialize the array that will receive the posts' data.
$posts_data = array();
// Receive and set the page parameter from the $request for pagination purposes
$paged = $request->get_param( 'page' );
$paged = ( isset( $paged ) || ! ( empty( $paged ) ) ) ? $paged : 1;
// Get the posts using the 'post' and 'news' post types
$posts = get_posts( array(
'paged' => $paged,
'post__not_in' => get_option( 'sticky_posts' ),
'posts_per_page' => 1000,
'post_type' => array('post') // This is the line that allows to fetch multiple post types.
)
);
// Loop through the posts and push the desired data to the array we've initialized earlier in the form of an object
foreach( $posts as $post ) {
$id = $post->ID;
$post_thumbnail = ( has_post_thumbnail( $id ) ) ? get_the_post_thumbnail_url( $id ) : null;
$posts_data[] = (object) array(
'id' => $id,
'slug' => $post->post_name,
'type' => $post->post_type,
'title' => $post->post_title,
"content" => apply_filters('the_content', $post->post_content),
'featured_img_src' => $post_thumbnail
);
}
return $posts_data; }
use this link http://yourdomin.com/wp-json/custom/v1/all-posts.
I think it will work for you

The file "C:\xampp\tmp\php8911.tmp" does not exist

I after install
composer require intervention/image
I want to upload image and after submit a form, I get this error.
The file "C:\xampp\tmp\php1D5F.tmp" does not exist
public function store(ArticleRequest $request)
{
auth()->loginUsingId(1);
$imagesUrl = $this->uploadImages($request->file('images'));
$article = auth()->user()->article()->create(array_merge($request->all(), ['images' => $imagesUrl]));
$article->categories()->attach(request('category'));
return redirect(route('articles.index'));
}
protected function uploadImages($file)
{
$year = Carbon::now()->year;
$imagePath = "/upload/images/{$year}/";
$filename = $file->getClientOriginalName();
$file = $file->move(public_path($imagePath) , $filename);
$sizes = ["300" , "600" , "900"];
$url['images'] = $this->resize($file->getRealPath() , $sizes , $imagePath , $filename);
$url['thumb'] = $url['images'][$sizes[0]];
return $url;
}
private function resize($path , $sizes , $imagePath , $filename)
{
$images['original'] = $imagePath . $filename;
foreach ($sizes as $size) {
$images[$size] = $imagePath . "{$size}_" . $filename;
Image::make($path)->resize($size, null, function ($constraint) {
$constraint->aspectRatio();
})->save(public_path($images[$size]));
}
return $images;
}
I tried Change the code:
$imagesUrl = $this->uploadImages($request->file('images'));
return $imagesUrl;
It displaied return $imagesUrl well.
images
300 "/upload/images/2018/300_tvto.jpg"
600 "/upload/images/2018/600_tvto.jpg"
900 "/upload/images/2018/900_tvto.jpg"
original "/upload/images/2018/tvto.jpg"
thumb "/upload/images/2018/300_tvto.jpg"
I think problem from array_merge
So what's the solution?
You need to convert ArticleRequest to Request and bring it to the controller page like below.
public function store(Request $request)
{
$this->validate(request(),[
'title' => 'required|max:250',
'type' => 'required',
'description' => 'required',
'image' => 'required|mimes:jpeg,png,bmp',
'path.*' => 'required|mimes:avi,mp4,.mov,wmv',
'price' => 'required',
]);

Send JSON from HTTPS to HTTP

I use Request solution for ajax-request, but I get an error:
reqwest.min.js:6 Mixed Content: The page at 'https://...' was loaded
over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://...'. This request has been blocked; the content must be
served over HTTPS.
Server-side code (i'm using wordpress plugin for this):
add_action('wp_ajax_nopriv_wpse144893_search', 'wpse144893_search_data'); // allow logged out users
add_action('wp_ajax_wpse144893_search', 'wpse144893_search_data'); // allow logged in users
function wpse144893_search_data(){
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
$errors = array();
$data = array(
'status' => 'error',
'message' => '',
'result' => array()
);
if(!isset($_REQUEST['term']) || empty($_REQUEST['term']))
$errors[] = 'No search term given!';
if(!isset($_REQUEST['limit']) || empty($_REQUEST['limit']))
$limit = 10;
else
$limit = (int) $_REQUEST['limit'];
if(empty($errors)){
$term = sanitize_text_field($_REQUEST['term']);
// setup query data
$args = array(
'posts_per_page' => $limit,
's' => $term
);
$query = new WP_Query($args); // run query
$results = array();
if($query->have_posts()): while($query->have_posts()): $query->the_post();
$post_item = array(
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'permalink' => get_permalink()
);
$results[] = $post_item;
endwhile;
$data['status'] = 'success';
$data['message'] = 'Results found!';
$data['result'] = $results;
else:
$errors[] = 'No post found!';
$data['message'] = $errors;
endif;
}
echo json_encode($data); // print json
die(); // kill the script
}
Client-side code (request plugin):
reqwest({
url: 'http://...'
, type: 'json'
, method: 'get'
, crossOrigin: true
, withCredentials: true
, error: function (err) { alert('1'); }
, success: function (resp) {
alert('2');
}
})
I tried use this header('Content-type: application/json');header('Access-Control-Allow-Origin: *'); (see in server code above) but it does not solve the problem.
Problem is solved by moving second server to HTTPS...