0

I like to use ajax to fetch the content of a wordpress page inside my custom templates. I've read that it's necessary to pass all the call to fetch or get data throught the admin-ajax.php of wordpress. I'm a bit confused on how to proceed, for example if I need to get the content of a post because I want to display it, I need to setup a call to admin ajax or a call to a function file that will hold the php query?Someone guide me.

Sorry for the dumb question, I've never used ajax inside my custom themes or in wordpress in general. for now I try to use the get_template_part() function to load custom html code and wp loops, but it's not very suitable for certain theme or app design where ajax will be more smooth and user friendly.

An example of my code for now:

<?php get_header(); ?>

<?php if( have_posts() ); while( have_posts() ): the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
// here fetch the content inside a div instead of using the loop directly

<?php get_footer(); ?>

Is the REST API a good approach?

  • you can start by trying examples here : codex.wordpress.org/AJAX_in_Plugins – Kaperto Nov 10 at 17:23
  • It's not necessary to use admin-ajax.php, that's an old way of doing things. The REST API is superior, and already provides endpoints for retrieving posts and pages – Tom J Nowell Nov 10 at 19:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.