Make foreach show one by one within javascript loo

2019-08-24 01:20发布

I'm trying to display latest posts from multiple categories in the page by using foreach within javascript loop, but instead one by one the foreach display them all as in the picture below:

I want to display it one every element, not all of them in every element.

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

Is there any solution for this? *The order of categories with JavaScript is same.

1条回答
看我几分像从前
2楼-- · 2019-08-24 02:00

Since PHP is rendered server side, you cant combine it in that way with JavaScript.

But you could pass JSON to JavaScript to parse the structure and display it on the website.

Imagine you have the following array with your data:

$data = array(
    array(
        'category_id' => 39,
        'chapters' => array(
            array(
                'link' => 'http://google.de',
                'chapter_name' => 'First chapter',
            )
        ),
    ),
    array(
        'category_id' => 37,
        'chapters' => array(
            array(
                'link' => 'http://google.de',
                'chapter_name' => 'Second chapter',
            )
        ),
    ),
    array(
        'category_id' => 42,
        'chapters' => array(
            array(
                'link' => 'http://google.de',
                'chapter_name' => 'Third chapter',
            )
        ),
    ),
);

You can simply output the JSON representation of this array with json_encode($data) (make sure to echo it into a JS variable).

Then you can easily read it out with JavaScript. Here is a nice codepen: https://codepen.io/YannickFricke/pen/Vqzoob

A quick note about the forEach function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

查看更多
登录 后发表回答