how to loop in wordpress in javascript

To loop through elements in WordPress using JavaScript, you can use a combination of the WordPress function wp_localize_script and standard JavaScript for or forEach loops.

Assuming you have enqueued a script that requires the loop, you can pass an array of data to the script using wp_localize_script and use that data to loop through elements in the script.

Here's an example code snippet:

index.tsx
// PHP function to localize script data
function my_enqueue_scripts() {
  wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array( 'jquery' ), '1.0', true );
  wp_localize_script( 'my-script', 'my_data', array(
    'posts' => json_encode( get_posts() ), // use any query you want here
  ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );

// JavaScript loop through elements using the localized data
var posts = JSON.parse( my_data.posts );
posts.forEach( function( post ) {
  console.log( post.title.rendered ); // do something with each post
});
595 chars
15 lines

In this example, we are enqueuing a script called my-script.js and passing it an array of post data using wp_localize_script. Within the my-script.js file, we are parsing the data and looping through each post using the forEach function.

gistlibby LogSnag