I am using AJAX to load next set of posts on homepage. The posts load fine but the shortcodes are not rendered. I am trying to use the do_shortcode function on the content the ajax call fetches (although experts have suggested not to use do_shortcode) but apparently it is failing.
Here’s my function that processes the request:
function theme_load_more_posts() {
check_ajax_referer( 'theme-load-more-posts-nonce', 'nonce' );
$args = isset( $_POST['query'] ) ? array_map( 'esc_attr', $_POST['query'] ) : array();
$args['post_type'] = isset( $args['post_type'] ) ? esc_attr( $args['post_type'] ) : 'post';
$args['paged'] = esc_attr( $_POST['page'] );
$args['post_status'] = 'publish';
ob_start();
$loop = new WP_Query( $args );
if( $loop->have_posts() ): while( $loop->have_posts() ): $loop->the_post();
get_content_template();
endwhile;
endif;
$data = ob_get_clean();
wp_send_json_success( do_shortcode($data) ); // Performing do_shortcode here but it doesn't work.
wp_reset_postdata();
wp_die();
}
add_action( 'wp_ajax_theme_load_more_posts', 'theme_load_more_posts' );
add_action( 'wp_ajax_nopriv_theme_load_more_posts', 'theme_load_more_posts' );
The get_content_template()
function loads a template file that contains the regular wordpress code for displaying post contents.
I tried using do_shortcode_in_html()
on get_content_template()
but it doesn’t work either.
I also saw similar threads related to this but they mostly addressed issues with the ajax call itself. I believe my problem lies within this function. Any guesses?