I've got simple loop in standard-loop.php
file (which, the file, is located in inc/loop
folder):
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
the_content();
endwhile;
endif;
Then in index.php
I'm getting that file as a part of a template:
get_header();
get_template_part( 'inc/loop/standard', 'loop' );
get_footer();
Now I've got my wp_ajax function in functions.php
:
function blank_frontend_ajax() {
$url = $_POST['postUrl'];
$post_id = url_to_postid( $url );
$post_data = get_post( $post_id );
get_template_part( 'inc/loop/standard', 'loop' );
wp_die();
}
add_action( 'wp_ajax_nopriv_frontend_ajax', 'blank_frontend_ajax' );
add_action( 'wp_ajax_frontend_ajax', 'blank_frontend_ajax' );
And finally my jQuery AJAX:
function desktopAjax() {
jQuery( 'body' ).on( 'click', '.menu-item a', function( event ) {
var postUrl = jQuery( this ).attr( 'href' );
event.preventDefault();
jQuery.ajax({
url: blankAjax.ajaxUrl,
type: 'post',
data: {
action: 'frontend_ajax',
postUrl: postUrl,
},
success: function( postObject ) {
// jQuery( '#main' ).empty().append( postObject );
console.log( postObject );
}
});
});
}
Now, I'd like to use the same template part in index.php and my AJAX function. I know that I could pass query arguments (i.e. post ID) via set_query_var()
into get_template_part()
and retrieve it later on with get_query_var()
but doing the same inside of index.php wouldn't be a bit of overkill (we have a post ID inside of index.php already hence no need to pass post ID into get_template_part()
)? How could I rewrite whatever is inside of get_template_part() to work properly in case of loading in index.php and my AJAX fuction as well, and omit all unnecesary bits of code at the same time?