I've been trying (and failing annoyingly) to get an Ajax post loader to work.
This is the jQuery i'm using (its from this previous StackOverflow post: "Load More Posts" with Ajax in wordpress ), but its just not working.. I'm just trying to get an isotope list to ajax load more but everything i'm trying is failing.
jQuery(document).ready(function($){
$('.pagination a').click(function(e) {
e.preventDefault();
$('.filtered-posts').append("<div class=\"loader\"> </div>");
var link = jQuery(this).attr('href');
var $content = '.filtered-posts';
var $nav_wrap = '.pagination';
var $anchor = '.pagination a';
var $next_href = $($anchor).attr('href'); // Get URL for the next set of posts
$.get(''+link+' .item', function(data){
var $timestamp = new Date().getTime();
var $new_content = $($content, data).wrapInner('').html(); // Grab just the content
$('.filtered-posts .loader').remove();
$next_href = $($anchor, data).attr('href'); // Get the new href
$($nav_wrap).before($new_content); // Append the new content
$('#rtz-' + $timestamp).hide().fadeIn('slow'); // Animate load
$('.pagination a').attr('href', $next_href); // Change the next URL
$('.pagination:last').remove(); // Remove the original navigation
});
});});
This is what I'm using for my js but its just not loading anything when I click on the standard previous_posts_link/next_posts_link.
I've put a div container around them to force the .pagination above.. It briefly worked but was only calling the same 9 posts once and then didn't work.
Any help would be great. Or if someone has a different Ajax Pagination guide that they know works ..
Thanks in advance :)
/* We will edit our javascript snippet with a variable to keep track of the current page, and we add the $ajax call to our ajax function that we will write in the next chapter. */
let currentPage = 1;
jQuery('#load-more').on('click', function() {
currentPage++; // Do currentPage + 1, because we want to load the next page
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
dataType: 'html',
data: {
action: 'weichie_load_more',
paged: currentPage,
},
success: function (res) {
jQuery('.publication-list').append(res);
}
});
});
/* The WordPress query to load posts from a (custom) post type */
<?php
$publications = new WP_Query([
'post_type' => 'publications',
'posts_per_page' => 6,
'orderby' => 'date',
'order' => 'DESC',
'paged' => 1,
]);
?>
<?php if($publications->have_posts()): ?>
<ul class="publication-list">
<?php
while ($publications->have_posts()): $publications->the_post();
get_template_part('parts/card', 'publication');
endwhile;
?>
</ul>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<div class="btn__wrapper">
Load more
</div>
functions.php:
function weichie_load_more() {
$ajaxposts = new WP_Query([
'post_type' => 'publications',
'posts_per_page' => 6,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $_POST['paged'],
]);
$response = '';
if($ajaxposts->have_posts()) {
while($ajaxposts->have_posts()) : $ajaxposts->the_post();
$response .= get_template_part('parts/card', 'publication');
endwhile;
} else {
$response = '';
}
echo $response;
exit;
}
add_action('wp_ajax_weichie_load_more', 'weichie_load_more');
add_action('wp_ajax_nopriv_weichie_load_more', 'weichie_load_more');
Related
-- Edit 1 --
Found out some new things. I'm adding them on top since they might be more relevant than the code below.
I've rerun the scripts a few times. I now get different findings actually.
Running var_dump($wp_query->query); right after $the_query = new WP_Query($queryArgs);In the first render of the post loop gives me the query vars of the page the loop is rendered on. Calling it with ajax it reruns the same part of the code, right? So than it returns empty.
My thoughts:
Pages is called, runs funtions.php.
Runs the part of the wp_enqueue_script('rtt_scripts');
This is the moment it gets the current $wp_query values. Which are the values of the page.
Than renders the page with the post loop.
This is the moment the post loop runs $the_query = new WP_Query($queryArgs);
On press of the load more the ajax than calls it to rerun the post loop. With the query vars set with wp_enqueue_script('rtt_scripts');
This made me think. Am I running the code in a wrong order? Are the query vars for ajax set on the wrong moment? Other thought. Should I focus on how to get the query vars on the first post loop to the ajax query vars?
-- End Edit --
I’m having trouble with a load more button in Wordpress. The code below is the basic code I have right now.
As far as I can see this should be a working code :) Problem is though that this doesn’t work.
My problem is that I don’t know where to start debugging. Closest I know where the problem lies is this:
In rtt_loadmore_ajax_handler() there is the var $queryArg
When var_dumping the var $queryArg in both rtt_post_grid() and rtt_loadmore_ajax_handler()
It gives different results. Here I would expect the same results. In the Ajax call it returns the arguments
of the current rendered page and not of the post query on this page.
Would the global $wp_query; be the problem? And how do I go from here?
The basic post code:
function rtt_post_grid()
{
$queryArgs = Array(
"post_type" => Array(
'news',
'agenda'
),
'posts_per_page' => 4,
'post_status' => 'publish',
'paged' => 1
);
// post grid wrap
echo '<div id="rtt_posts_wrap" >';
rtt_post_grid_query($queryArgs);
echo '</div>';
// load more button
echo '<form>';
echo '<button id="rtt_loadmore" class=" button">Load more post</button> ';
echo '<input type="hidden" name="action" value="loadmore" />'; // this line might be obsolete
echo '</form>';
}
function rtt_post_grid_query($queryArgs)
{
// The Query
$the_query = new WP_Query($queryArgs);
// The Loop
if ($the_query->have_posts()) {
echo '<ul>';
while ($the_query->have_posts()) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
echo 'no posts found';
}
}
Setting the JS:
if(!has_action('rtt_post_grid_script_and_styles')) {
add_action('wp_enqueue_scripts', 'rtt_post_grid_script_and_styles', 1);
function rtt_post_grid_script_and_styles()
{
global $wp_query;
wp_register_script('rtt_scripts', plugin_dir_url( __FILE__ ) . 'js/script.js', array('jquery'), time());
wp_enqueue_script('rtt_scripts');
wp_localize_script('rtt_scripts', 'rtt_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode($wp_query->query_vars), // everything about your loop is here
'current_page' => $wp_query->query_vars['paged'] ? $wp_query->query_vars['paged'] : 1,
'max_page' => $wp_query->max_num_pages
));
wp_enqueue_script('rtt_scripts');
}
}
The JS/Ajax:
jQuery(function($){
$(window).ready(function() {
$('#rtt_loadmore').click(function () {
$.ajax({
url: rtt_loadmore_params.ajaxurl,
data: {
'action': 'loadmore', // the parameter for admin-ajax.php
'query': rtt_loadmore_params.posts, // loop parameters passed by wp_localize_script()
'page': rtt_loadmore_params.current_page, // current page
},
dataType: 'json',
type: 'POST',
beforeSend: function (xhr) {
$('#rtt_loadmore').text('Bezig met laden...'); // some type of preloader
},
success: function (data) {
if (data) {
$('#rtt_loadmore').text('More posts');
$('#rtt_posts_wrap').append(data.content); // insert new posts
rtt_loadmore_params.current_page++;
if (rtt_loadmore_params.current_page == rtt_loadmore_params.max_page){
$('#rtt_loadmore').hide(); // if last page, HIDE the button
}
} else {
$('#rtt_loadmore').hide(); // if no data, HIDE the button as well
}
}
});
return false;
});
});
});
The Ajax handler:
add_action('wp_ajax_loadmore', 'rtt_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'rtt_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}
function rtt_loadmore_ajax_handler(){
$postData = $_POST;
// prepare our arguments for the query
$queryArgs = json_decode( stripslashes( $postData['query'] ), true );
$queryArgs['paged'] = $postData['page'] + 1; // we need next page to be loaded
$queryArgs['post_status'] = 'publish';
ob_start();
rtt_post_grid_query($queryArgs);
$output = ob_get_contents();
ob_end_clean();
global $the_query;
echo json_encode( array(
'posts' => serialize( $the_query->query_vars ),
'max_page' => $the_query->max_num_pages,
'found_posts' => $the_query->found_posts,
'content' => $output
) );
die;
}
So, I've figured it out. I'll explain for it might be useful to somebody else.
The reason it did not work is because the code above is more useful in a template. But I use it in a shortcode. The wp_localize_script() was run on rendering the page and not on running the shortcode. That's why it didn't had the right variables.
I've moved the code below inside the shortcode. Right after the new WP_query:
// The Query
$the_query = new WP_Query($queryArgs);
// The Loop
if ($the_query->have_posts()) {
wp_enqueue_script_ajax_vars($the_query);
Than passed the new query
function wp_enqueue_script_ajax_vars($the_query)
{
wp_register_script('rtt_scripts', plugin_dir_url(__FILE__) . 'js/script.js', array('jquery'), time());
wp_localize_script('rtt_scripts', 'rtt_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode($the_query->query_vars), // everything about your loop is here
'query_vars' => json_encode($the_query->query),
'current_page' => $the_query->query_vars['paged'] ? $the_query->query_vars['paged'] : 1,
'max_page' => $the_query->max_num_pages,
));
wp_enqueue_script('rtt_scripts', '', '', '', true); // note the last 'true' this sets it inside the footer
}
Resulting in wp_localize_script() creating the variable in the footer. It was in the header before. But by getting it within the shortcode, sending the new query arguments and putting them inside the footer (since the header is already rendered by then) I have set the JS var for Ajax.
Add the two order arguments to $queryArgs.
// prepare our arguments for the query
$queryArgs = json_decode( stripslashes( $postData['query'] ), true );
$queryArgs['paged'] = $postData['page'] + 1; // we need next page to be loaded
$queryArgs['post_status'] = 'publish';
$queryArgs['orderby'] = 'date'; // add this to order by date
$queryArgs['order'] = 'DESC'; // add this to display the most recent
I have a PHP code that creates a JSON data from wordpress posts in the database.
I load this JSON on my html page using AJAX.
The above works fine.
Now I need to add a "Load More" button so everytime its pressed, we load another 10 posts and append/add them to the ones that were already loaded WITHOUT having to delete the old ones and re-adding them.
So this my AJAX code for loading more:
var i = 0;
$(document).on("click", ".loadMoreBtn", function () {
$.ajax({
url: 'https://some-domain.com/index.php?t=' + mainCat + '&page=' + i + '',
dataType: 'json',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
if (!$.trim(data)) {
}
else {
}
$.each(data, function (pi, item) {
var id = item.id;
var img = item.img;
var title = item.title;
var date_added = item.date_added;
var item = '' + title + '';
$('.myDiv').before(item);
i++;
});
},
error: function () {
//error handling////
}
});
});
And this is my PHP code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
$t = $_GET['t'];
$page = $_GET['page'];
$posts = get_posts(array(
'posts_per_page' => $page, //add -1 if you want to show all posts
'post_type' => 'post',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $t //pass your term name here
)
))
);
$output= array();
foreach( $posts as $post ) {
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
$mysqldate = $post->post_date;
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'F d Y', $phpdate );
// Pluck the id and title attributes
$output[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'date_added' => $mysqldate, 'img' =>$feat_image );
}
echo json_encode( $output );
When I click on the 'Load More' button, it acts strangely! it basiclaly adds the old data and multiplies the same ones and adds/loads some new ones as well.
I know I am missing something in my PHP code but I couldn't figure out what.
Could someone please advice on this issue?
Thanks in advance.
The error is in your wordpress query. "posts_per_page" set how many posts will be loaded. Set that as how many post should be loaded like 12 or something.
The parameter your want to set as your $page parameter is "paged".
Eg. $query = new WP_Query( array( 'paged' => 6 ) ); // page number 6
https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters
You could also use WP API instead of rolling your own
I have custom post types displaying on a static front page, initially showing 8 posts, where I have now created a load more button using an example of jQuery and AJAX that I found online that will show 4 more posts when the button is clicked. I am wondering how I can add 4 to the offset each time so it keeps moving through the next posts. As it is now every time I click the load more button it shows the same 4 over again. My code in my front-page.php:
<script>
var now=2; // when click start in page 2
jQuery(document).on('click', '#load_more_btn', function () {
jQuery.ajax({
type: "POST",
url: "<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php",
data: {
action: 'my_load_more_function', // the name of the function in functions.php
paged: now, // set the page to get the ajax request
posts_per_page: 4, //number of post to get (use 1 for testing)
},
success: function (data) {
if(data!=0){
jQuery("#ajax").append(data); // put the content into ajax container
now=now+1; // add 1 to next page
}else{
jQuery("#load_more_btn").html("<h4>No more
results</h4>");
}
},
error: function (errorThrown) {
alert(errorThrown); // only for debuggin
}
});
});
and the code in my functions.php file:
add_action('wp_ajax_my_load_more_function', 'my_load_more_function');
add_action('wp_ajax_nopriv_my_load_more_function',
'my_load_more_function');
function my_load_more_function() {
$offset = 8;
$page = (get_query_var('page')) ? get_query_var('page') : 1;
$query = new WP_Query( [
'posts_per_page' => $_POST["posts_per_page"],
'order'=>'ASC',
'offset'=> $offset,
'post_type' => 'videos',
'page' => get_query_var('page', $_POST["paged"])
] );
if ($query->have_posts()) {
$offset = (($page - 1) * 8) - $offset;
$query->set( 'offset', $offset );
while ($query->have_posts()) {
$query->the_post();
$img1 = get_field('video_thumbnail'); ?>
<div class="col-6 col-sm-3 box no-gutters" style="background-
image: url('<?php echo $img1['url']; ?>')"><a href="<?php
the_field('video_link'); ?>" data-lity><div class="overlay"><span
class="title"><?php the_field('name'); ?></span></div></a></div>
<?php
}
wp_reset_query();
}else{
return 0;
}
exit;
}
I'm wondering how I can get offset to be +4 each time the query is run after the initial time where it is set at 8. I'm fairly new to thsi type of thing and can not seem to get it working properly.
I've had a look through the old questions and tried many of the different methods that there seems to be to do this. The closest I've got to working is this one here: How to implement pagination on a custom WP_Query Ajax
I've tried everything and it just doesn't work. Absolutely nothing changes on the page. If you inspect the Load More Button and click it, the jQuery is making the Load More Button action as it changes from <a id="more_posts">Load More</a> to <a id="more_posts" disables="disabled">Load More</a> which even that doesn6't seem right to me anyway. It's not adding the posts, I think I'm missing something simple but for the life of me I can't work it out.
The code in my template file is:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = [
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 1
];
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post(); ?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
echo '<a id="more_posts">Load More</a>';
wp_reset_postdata();
?>
</div>
The code in my functions file is:
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = [
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 1,
'offset' => $offset,
];
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_content();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
And my jQuery in the footer is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready( function($) {
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
// What page we are on.
var page = 5;
// Post per page
var ppp = 3;
$("#more_posts").on("click", function() {
// When btn is pressed.
$("#more_posts").attr("disabled",true);
// Disable the button, temp.
$.post(ajaxUrl, {
action: "more_post_ajax",
offset: (page * ppp) + 1,
ppp: ppp
})
.success(function(posts) {
page++;
$("#ajax-posts").append(posts);
// CHANGE THIS!
$("#more_posts").attr("disabled", false);
});
});
});
</script>
Can anybody see something I'm missing or able to help?
UPDATE 24.04.2016.
I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)
EDIT
I've tested this on Twenty Fifteen and it's working, so it should be working for you.
In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 8
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<div id="more_posts">Load More</div>
This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with
$cat_id = get_query_var('cat');
This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like
<div id="more_posts" data-category="<?php echo $cat_id; ?>">Load More</div>
And pull the category with
var cat = $('#more_posts').data('category');
But for now, you can leave this out.
Next in functions.php I added
wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'twentyfifteen'),
));
Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.
At the end of the functions.php file I added the function that will load your posts:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-12 large-4 columns">
<h1>'.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.
If you've added your category in the loader, you'd add:
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.
Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment
var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Saved it, tested it, and it works :)
Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD
UPDATE
For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer
$(window).on('scroll', function(){
if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
load_posts();
}
}
});
Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.
You can easily check it by putting console.logs in your code and see in the inspector what they throw out
$(window).on('scroll', function () {
console.log($(window).scrollTop() + $(window).height());
console.log($(document).height() - 100);
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
And just adjust accordingly ;)
Hope this helps :) If you have any questions just ask.
If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.
Im using wordpress theme that has different parts like for example footer.php or header.php. What I want to do is reload one part of the whole page using jquery so that the whole page does not refresh. Below is my code with the php part that I want to reload and the jquery Im using.
Jquery code inside a php code block
<script type="text/javascript">
jQuery(document).ready(function(){
var thedata = '.json_encode($this->query_args).';
jQuery( ".facetwp-page" ).click(function() {
jQuery.ajax({
type: "post",
url: "'.admin_url("admin-ajax.php").'",
data: { "action" : "query_for_map", "mydata" : thedata },
success: function(response, data){
console.log(response);
console.log(data);
jQuery("#map-head").load("'.get_template_directory_uri().'/banners/map_based_banner.php");
google.maps.event.trigger(map, "resize");
}
});
});
});
</script>
php template part to be reloaded
<?php
session_start();
include('/home/javy1103/public_html/wp-blog-header.php');
global $paged;
$properties_for_map = array(
'post_type' => 'property',
'posts_per_page' => 12,
'paged' => $paged
);
if( is_page_template('template-search.php') || is_page_template('template-search-sidebar.php') ){
/* Apply Search Filter */
$properties_for_map = apply_filters( 'real_homes_search_parameters', $properties_for_map );
}elseif(is_page_template('template-home.php')){
/* Apply Homepage Properties Filter */
$properties_for_map = apply_filters( 'real_homes_homepage_properties', $properties_for_map );
}elseif(is_tax()){
global $wp_query;
/* Taxonomy Query */
$properties_for_map['tax_query'] = array(
array(
'taxonomy' => $wp_query->query_vars['taxonomy'],
'field' => 'slug',
'terms' => $wp_query->query_vars['term']
)
);
}
function query_for_map() {
return json_decode($_POST['mydata']);
}
add_action('wp_ajax_query_for_map', 'query_for_map');
add_action('wp_ajax_nopriv_query_for_map', 'query_for_map');
$mapdata = $_SESSION['queryMap'];
$properties_for_map_query = new WP_Query( $mapdata );
$properties_data = array();
if ( $properties_for_map_query->have_posts() ) :
while ( $properties_for_map_query->have_posts() ) :
$properties_for_map_query->the_post();
$current_prop_array = array();
/* Property Title */
$current_prop_array['title'] = get_the_title();
/* Property Price */
$current_prop_array['price'] = get_property_price();
/* Property Location */
$property_location = get_post_meta($post->ID,'REAL_HOMES_property_location',true);
if(!empty($property_location)){
$lat_lng = explode(',',$property_location);
$current_prop_array['lat'] = $lat_lng[0];
$current_prop_array['lng'] = $lat_lng[1];
}
/* Property Thumbnail */
if(has_post_thumbnail()){
$image_id = get_post_thumbnail_id();
$image_attributes = wp_get_attachment_image_src( $image_id, 'property-thumb-image' );
if(!empty($image_attributes[0])){
$current_prop_array['thumb'] = $image_attributes[0];
}
}
/* Property Title */
$current_prop_array['url'] = get_permalink();
/* Property Map Icon Based on Property Type */
$property_type_slug = 'single-family-home'; // Default Icon Slug
$type_terms = get_the_terms( $post->ID,"property-type" );
if(!empty($type_terms)){
foreach($type_terms as $typ_trm){
$property_type_slug = $typ_trm->slug;
break;
}
}
if(file_exists(get_template_directory().'/images/map/'.$property_type_slug.'-map-icon.png')){
$current_prop_array['icon'] = get_template_directory_uri().'/images/map/'.$property_type_slug.'-map-icon.png';
}else{
$current_prop_array['icon'] = get_template_directory_uri().'/images/map/single-family-home-map-icon.png';
}
$properties_data[] = $current_prop_array;
endwhile;
wp_reset_query();
?>
You can generate all server side(PHP) work without refreshing page by Ajax, Then you can use it in HTML, you can't replace PHP of your page.
ex: If you want some data from database then you can send an ajax request to PHP file then fetch the data and get the result, then show it in HTML.