ARTICLE AD BOX
I'm building a website in Wordpress. To resume, I would like to load posts (from my custom post type 'project') dynamically with AJAX inside the div .js-panel-content, by clicking a button with the same ID than the post loaded.
The issue is, when clicking the button it doesn't load the post requested by ID but all the posts of my custom post type.
I tried to print the ID of the post via AJAX just to see if the ID was loaded correctly. I did it by replacing the line panelContent.innerHTML = data; with panelContent.innerHTML = post_id; The result is, the ID is undefined.
The HTML to display the div and the loop in PHP to display the list of buttons
<?php $args = array( 'post_type' => 'project', 'posts_per_page' => -1, ); $query = new WP_Query( $args ); while( $query->have_posts() ) : $query->the_post(); echo '<button id="post-'. get_the_ID() .'" class="js-btn-load-post">'. get_the_title() .'</button>'; endwhile; ?> <div class="c-panel js-panel" data-ajax-url='<?php echo esc_url( home_url( '/' ) ); ?>wp-admin/admin-ajax.php'> <div class="c-panel__content js-panel-content"> </div> </div>The JS
const loadPanelBtn = document.querySelectorAll('.js-btn-load-post'); const ajax_url = panel.dataset.ajaxUrl; var i; for( i = 0; i < loaderPanelBtn.length; i++ ){ loaderPanelBtn[i].addEventListener('click', function(e){ e.preventDefault(); let post_id = this.dataset.id; const panelContent = document.querySelector(".js-panel-content"); const data = new FormData(); data.append( 'action', 'load_panel' ); data.append( 'post_id', post_id ); fetch(ajax_url, { method: "POST", body: data }) .then((response) => response.text()) .then((data) => { if (data) { panelContent.innerHTML = data; } }) .catch((error) => { }); }); };The AJAX handler
function load_panel_content() { $args = array( 'p' => $_POST['post_id'], 'post_type' => 'project' ); $query = new WP_Query( $args ); while( $query->have_posts() ) : $query->the_post(); get_template_part( 'template-parts/content', 'post' ); endwhile; wp_die(); } add_action ( 'wp_ajax_nopriv_load_panel', 'load_panel_content' ); add_action ( 'wp_ajax_load_panel', 'load_panel_content' );Thank you.
