【发布时间】:2018-12-28 05:28:54
【问题描述】:
我正在尝试通过在 javascript 循环中使用 foreach 来在页面中显示来自多个类别的最新帖子,但是 foreach 将它们一一显示,如下图所示:
我想在每个元素中显示一个,而不是在每个元素中都显示。
for (var i in books) { //Start JS Code
var html = '<div class="row"><div class="book_history">';
// JS Output
<?php // Start PHP
$catids = array(39, 37, 2); // Category for test
foreach ( $catids as $catid ) {
$my_query = new WP_Query( array(
'cat' => $catid,
'ignore_sticky_posts' => 1,
'posts_per_page' => 1,
'no_found_rows' => true )
);
if ( $my_query->have_posts() ) :
while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
html += '<a href="<?php the_permalink(); ?>">»Chapter <?php the_title(); ?></a></div>'; // Javascript Code, Displaying the result of foreach with js
<?php endwhile;
endif;
wp_reset_postdata();
} ?> // End PHP
$bookcontainer.append(html); // Insert all result of foreach and js into some element
} // End JS Code
有什么解决办法吗? *JavaScript 的分类顺序是一样的。
【问题讨论】:
-
在一个代码块中混合 JS+HTML+PHP 是一种非常糟糕的做法,您可以使用 en.m.wikipedia.org/wiki/Ajax_(programming)#Javascript 示例代替
标签: javascript php wordpress