By use AJAX, JSON return null
Problem: When use AJAX and when transferring array using json_encode() function json_decode() return null.
Solution: This situation may be because of not correct data presentation before call json_encode(). For example, numbers that has type string instead int. Check it can using var_dump(). In my case was so:
array(2) { [0]=> string(3) "212" [1]=> string(3) "211" }
and must be so:
array(2) { [0]=> int(212) [1]=> int(211) }
In my case, that situation has arisen because of this code:
<?php
$args = [
'post_type' => 'custom_post_type',
'posts_per_page' => -1,
'fields' => 'ids',
'no_found_rows' => true,
];
$custom_post_type = new WP_Query( $args );
if ( $custom_post_type->have_posts() ) {
$custom_post_type_ids = [];
while ( $custom_post_type->have_posts() ) {
$custom_post_type->the_post();
$custom_post_type_ids[] .= $post;
}
wp_reset_postdata();
}
Yeah, sure we could've add (int)
function to $testimonials_ids[] .= (int)$post;
that is by converting string to integer, but better do this way:
Step 1. Change argument query 'fields' => 'ids'
to 'fields' => 'id=>parent'
Step 2. Use function wp_list_pluck() exactly for such an occasion:
<?php
if ( $custom_post_type->have_posts() ) {
$custom_post_type_ids = wp_list_pluck( $custom_post_type->posts, 'ID' );
}
thus, ultimately our code would be so:
<?php
$args = [
'post_type' => 'custom_post_type',
'posts_per_page' => -1,
'fields' => 'id=>parent',
'no_found_rows' => true,
];
$custom_post_type = new WP_Query( $args );
if ( $custom_post_type->have_posts() ) {
$custom_post_type_ids = wp_list_pluck( $custom_post_type->posts, 'ID' );
}