使用wp_localize_script将PHP函数中的变量解析为jQuery脚本会导致NULL变量,我不明白为什么。
我希望其他人确实注意到这个问题。
在function.php中跟随函数将变量解析为jQuery脚本:
function wordpress_my_load_more_scripts()
{
global $custom_query;
wp_enqueue_script('jquery');
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/myloadmore.js', array('jquery') );
wp_localize_script( 'my_loadmore', 'wordpress_loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'posts' => json_encode( $custom_query['query_vars'] ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => json_encode($custom_query['max_num_pages'])
));
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'wordpress_my_load_more_scripts' );
以下jQuery脚本将数据变量写入控制台:
jQuery(function($){
$('.wordpress_loadmore').click(function()
{
var button = $(this),
data = {
'action' : 'loadmore',
'query': wordpress_loadmore_params.posts,
'page' : wordpress_loadmore_params.current_page
};
console.log(data);
$.ajax({
url : wordpress_loadmore_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr )
{
console.log("Loading");
button.text('Loading...');
},
success : function( data )
{
console.log("Success");
if(data)
{
console.log("We got data!");
console.log(wordpress_loadmore_params.current_page);
console.log(wordpress_loadmore_params.max_page);
button.text( 'More posts' ).prev().before(data);
wordpress_loadmore_params.current_page++;
if ( wordpress_loadmore_params.current_page == wordpress_loadmore_params.max_page )
{
console.log("Last page! Remove button");
button.remove();
}
} else {
console.log("No data! Remove button");
button.remove(); }
},
error: function()
{
console.log("Error");
}
});
});
});
的console.log(数据);输出以下消息:
(index):27 Debug Objects:
jquery-migrate.js?ver=1.4.1:23 JQMIGRATE: Migrate is installed with logging active, version 1.4.1
myloadmore.js:12 {action: "loadmore", query: "null", page: "1"}
myloadmore.js:20 Loading
myloadmore.js:26 Success
myloadmore.js:30 We got data!
myloadmore.js:31 1
myloadmore.js:32 null
为什么查询为NULL?
这是自定义查询:
<div class="woocommerce columns-3">
<ul class="products columns-3">
<?php
$query_params = array(
'post_type' => 'post',
'posts_per_page' => 3 // Value "-1" displays all products in feed
);
$custom_query = new WP_Query( $query_params);
if( $custom_query->have_posts() ) :
while ($custom_query->have_posts()) : $custom_query->the_post(); ?>
<li class="product post-item">
<span class="post-image">
<a href="<?php the_permalink(); ?>">
<?php
if ( has_post_thumbnail())
{
the_post_thumbnail();
}
?>
</a>
</span>
<h2 class="post-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
<span class="post-category"><?php the_category(', ');?></span>
</li>
<?php endwhile; ?>
<?php endif; ?>
</ul>
<nav>
<?php
// global $custom_query; // you can remove this line if everything works for you
// don't display the button if there are not enough posts
if ( $custom_query->max_num_pages > 1 )
echo '
<div class="wordpress_wrapper">
<div class="wordpress_loadmore">More posts</div>
</div>'; // you can use <a> as well
?>
</nav>
<?php wp_reset_postdata(); ?>
</div>
链接到当前解决方案 - https://www.uvjagtpro.dk/arkiv/
答案 0 :(得分:1)
您看到的null
不是null
类型,而是string
类型(我刚检查过您的网站)。这意味着你实际上做了类似的事情:json_encode("null")
。
您似乎正在尝试将query_vars
和max_num_pages
加载为数组:
'posts' => json_encode( $custom_query['query_vars'] ),
'max_page' => json_encode($custom_query['max_num_pages'])
但我猜这些是对象属性,就像在另一个文件中一样:
if ( $custom_query->max_num_pages > 1 )
所以我想如果你把它们改写成它应该可以工作:
'posts' => json_encode( $custom_query->query_vars ),
'max_page' => json_encode($custom_query->max_num_pages)
我猜可能$custom_query
对象有一些ArrayAccess接口,这就是为什么你可以作为一个数组访问该对象的原因,它不会引发警告或错误。
答案 1 :(得分:0)
我在这里部分解决了我的问题。
我无法使用原始循环中的自定义WP_query。我必须在wordpress_my_load_more_scripts()函数中定义一个新的WP_query。
见下文:
add_action( 'wp_enqueue_scripts', 'wordpress_my_load_more_scripts' );
function wordpress_my_load_more_scripts()
{
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$query_args = array(
'posts_per_page' => 3,
'post_type' => 'artikler',
'paged' => $paged
);
$wp_query = new WP_Query( $query_args);
if (!isset( $wp_query ))
{
debug_to_console("Query is NULL!");
return;
}
wp_register_script( 'my_loadmore', plugins_url( 'myloadmore.js', __FILE__ ), array('jquery') );
$postArray = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'posts' => json_encode( $wp_query->query_vars ),
'max_page' => $wp_query->max_num_pages,
'results' => $wp_query->found_posts
);
wp_localize_script( 'my_loadmore', 'wordpress_load_more_params', $postArray);
wp_enqueue_script( 'my_loadmore' );
}
现在输出到控制台:
{action: "load_more", query: "{"posts_per_page":3,"post_type":"artikler","paged"…_page":"50","no_found_rows":false,"order":"DESC"}", max: "4", page: "1", results: "10"}
action:"load_more"
max:"4"
page:"1"
query:"{"posts_per_page":3,"post_type":"artikler","paged":1,"error":"","m":"","p":0,"post_parent":"","subpost":"","subpost_id":"","attachment":"","attachment_id":0,"name":"","static":"","pagename":"","page_id":0,"second":"","minute":"","hour":"","day":0,"monthnum":0,"year":0,"w":0,"category_name":"","tag":"","cat":"","tag_id":"","author":"","author_name":"","feed":"","tb":"","meta_key":"","meta_value":"","preview":"","s":"","sentence":"","title":"","fields":"","menu_order":"","embed":"","category__in":[],"category__not_in":[],"category__and":[],"post__in":[],"post__not_in":[],"post_name__in":[],"tag__in":[],"tag__not_in":[],"tag__and":[],"tag_slug__in":[],"tag_slug__and":[],"post_parent__in":[],"post_parent__not_in":[],"author__in":[],"author__not_in":[],"ignore_sticky_posts":false,"suppress_filters":false,"cache_results":true,"update_post_term_cache":true,"lazy_load_term_meta":true,"update_post_meta_cache":true,"nopaging":false,"comments_per_page":"50","no_found_rows":false,"order":"DESC"}"
results:"10"
__proto__:Object