function assets() { // enqueue your script wp_enqueue_script('handle', get_template_directory_uri() . '/path/to/main.js', ['jquery'], '$ver', true); // localize script wp_localize_script('handle', 'custom_ajaxify', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } add_action('wp_enqueue_scripts', 'assets', 100); /** * AJAX load template part */ function ajax_load_posts() { global $post; // Get the queryVars sent over from the AJAX request $query_vars = $_POST['queryVars']; $args = array( 'post_type' => $query_vars['post_type'], 'posts_per_page' => $query_vars['posts_per_page'], 'offset' => $query_vars['offset'], 'update_post_term_cache' => false, // Improves Query performance 'update_post_meta_cache' => false, // Improves Query performance ); $posts = get_posts($args); // The array of data we will return to the AJAX call $payload = array( 'posts' => array(), 'query_vars' => $query_vars // Here for debugging purposes so we can console.log later ); if ( $posts ) : foreach ( $posts as $post ) : setup_postdata( $post ); // Use object buffering to send each post as a separate string instead of all at once. ob_start(); get_template_part('templates/list-item', get_post_type()); array_push($payload['posts'], ob_get_clean() ); endforeach; wp_reset_postdata(); endif; // We always send some data, even if there are no posts. echo json_encode($payload); die(); } add_action('wp_ajax_nopriv_ajax_load_posts', 'ajax_load_posts'); add_action('wp_ajax_ajax_load_posts', 'ajax_load_posts');