我在functions.php
中定义了此功能
function cn_add_script($postsperpage) {
// find all of the published posts
$publishedposts = get_posts('post_type=post&post_status=publish&posts_per_page=-1');
// count the published posts
$count = count($publishedposts);
// only run this function on 'page-bulletins.php'
if( is_page_template('page-bulletins.php') ) {
// not entirely sure what this does, I think this tells Wordpress to use URLs with '/page/#' and also recognizes what page the user is currently viewing.
$paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;
// divide the total number of posts by the posts per page, then round this number up ('ceil' does this)
$maxpages = ceil($count/$postsperpage);
// store the next page number in a variable
$nextpagecalc = $paged + 1;
// if the next page number is greater than the max number of pages
if( $nextpagecalc > $maxpages ) {
// code to be finalized; store an empty path if there are no more pages to show
$nextpage = '';
}
else {
// if there is a next page, put the path for it in a variable
$nextpage = get_bloginfo('url').'/bulletins/page/'.$nextpagecalc.'/';
}
}
$array = ['startPage', 'maxPages', 'nextLink'];
$array = array (
'startPage' => $paged,
'maxPages' => $maxpages,
'nextLink' => $nextpage
);
wp_register_script (
// handle name for script (to be used later to localize the script)
'cnLoadPosts',
// location of the script
get_bloginfo('template_url').'/_/js/functions-ajax-ck.js'
);
// call the script defined above
wp_enqueue_script ('cnLoadPosts');
// in the script defined above, define a handle that Javascript can use
wp_localize_script ('cnLoadPosts', 'cnPageAdvance', $array);
}
add_action( 'wp_enqueue_scripts', 'cn_add_script' );
我正在尝试使用wp_enqueue_scripts将
$paged
,$maxpages
和$nextpage
的值传递到文件functions-ajax-ck.js
。当我使用print_r($array)
时,我会得到以下输出:Array ( [startPage] => 1 [maxPages] => 4 [nextLink] => http://localhost:8888/slfiber/bulletins/page/2/ )
但是,此信息未通过检查该元素验证已保存到
functions-ajax-ck.js
文件中:/* <![CDATA[ */
var cnPageAdvance = {"startPage":"1","maxPages":"0","nextLink":""};
/* ]]> */
作为参考,这是
.js
文件中的代码: (function($) {
$(window).load(function() {
// The number of the next page to load (/page/x/).
var pageNum = parseInt(cnPageAdvance.startPage) + 1;
// The maximum number of pages the current query can return.
var max = parseInt(cnPageAdvance.maxPages);
// The link of the next page of posts.
var nextLink = cnPageAdvance.nextLink;
$('#loadmore').click(function() {
alert(max);
});
});
})(window.jQuery);
如果将
$paged
,$maxpages
和$nextpage
分别替换为“ 1”,“ 5”和“ http://wwwgoogle.com”,则值可以很好地传递。如何获取保存变量值的$ array传递给我的
js
文件? 最佳答案
当您通过wp_enqueue_scripts
挂接该函数时,该函数不接收任何参数,因此您基本上是在零处除$maxpages = ceil($count/$postsperpage);
。
使得$maxpages
undefined
等于0
(请参见this)。
并导致if( $nextpagecalc > $maxpages )
变为true,因此您的$nextpage
为空。