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
Related
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');
I'm really struggling to find a way to create pagination with ajax for my Wordpress posts. The solutions that I have found do not work.
To be more informative about this here is a link that has bullets at the bottom for pagination. Once these are clicked I want the effect of the site to load the new posts without triggering a page refresh.
http://maxlynn.co.uk/natural-interaction/category/all/
My question is, is there any good tutorials out there that you may have had success with for this type of effect.
Let me know if you need more information.
****** UPDATE ******
function kriesi_pagination($pages = '', $range = 2) {
$showitems = ($range * 2)+1;
global $paged;
if (empty($paged)) $paged = 1;
if ($pages == '') {
global $wp_query;
$pages = $wp_query->max_num_pages;
if (!$pages) {
$pages = 1;
}
}
if (1 != $pages) {
echo "<div class='pagination'><div class='pagination-container'>";
if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>«</a>";
if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹</a>";
for ($i=1; $i <= $pages; $i++) {
if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
{
echo ($paged == $i)? "<span class='current'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='inactive' >".$i."</a>";
}
}
if ($paged < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($paged + 1)."'>›</a>";
if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>»</a>";
echo "</div>\n</div>\n";
}
}
This is my PHP that I'm using, how would I use this php to create an ajax request so that the page doesn't reload?
What you need to do is to prevent default on the pagination links, and send an AJAX request to get the posts. Wordpress works in this way for AJAX: you send all your requests to wp-admin/admin-ajax.php with an action parameter that will identify the request in order to catch it in functions.php using wp_ajax_nopriv_my_action and wp_ajax_my_action hooks.
So basically you will do this in your template file:
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.pagination a').click(function(e) {
e.preventDefault(); // don't trigger page reload
if($(this).hasClass('active')) {
return; // don't do anything if click on current page
}
$.post(
'<?php echo admin_url('admin-ajax.php'); ?>', // get admin-ajax.php url
{
action: 'ajax_pagination',
page: parseInt($(this).attr('data-page')), // get page number for "data-page" attribute
posts_per_page: <?php echo get_option('posts_per_page'); ?>
},
function(data) {
$('#content-posts').html(data); // replace posts with new one
}
});
});
});
</script>
You'll have to change classes names / attributes etc depending of your template.
And on the functions.php side:
function my_ajax_navigation() {
$requested_page = intval($_POST['page']);
$posts_per_page = intval($_POST['posts_per_page']) - 1;
$posts = get_posts(array(
'posts_per_page' => $posts_per_page,
'offset' => $page * $posts_per_page
));
foreach ($posts as $post) {
setup_postdata( $post );
// DISPLAY POST HERE
// good thing to do would be to include your post template
}
exit;
}
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_navigation' );
add_action( 'wp_ajax_nopriv_ajax_paginationr', 'my_ajax_navigation' );
The thing is to query the posts of the page requested (so we calculate the offset from the page number and the posts per page option), and display them with the template you use for single posts.
You may want to manipulate the browser history too, for that you should check on the History API.
filter.js file
$('#post-category').change(function(){
category = $(this).find('.selected').text();
postType = $('#search-form-type').val();
post_filter();
});
function post_filter(paged){
$.ajax(
{
url:ajaxUrl,
type:"POST",
data: {action:"get_post_category","category":category,'search':search, 'postType':postType, 'paged': paged},
success: function(response) {
$('#blog-post-cover').html(response);
}
});
}
$('#blog-wrapper').on('click','#pagination a',function(e){
e.preventDefault();
if ($(this).hasClass('prev')||$(this).hasClass('next')) {
paginateNum = $(this).find('.prev-next').data('attr');
post_filter(paginateNum);
}
else{
paginateNum = $(this).text();
post_filter(paginateNum);
}
$("html, body").animate({ scrollTop: 0 }, "slow");
});
postType = $('#search-form-type').val();
post_filter(1);
function.php file
add_action( 'wp_ajax_nopriv_get_post_category', 'post_category' );
add_action( 'wp_ajax_get_post_category', 'post_category' );
function post_category() {
$post_type = $_POST['postType'];
$category = $_POST['category'];
$search = $_POST['search'];
$paged = ($_POST['paged'])? $_POST['paged'] : 1;
if($post_type==="resource-center"):
$taxonomy ="resource-center-taxonomy";
else:
$taxonomy ="category";
endif;
if($category):
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $category,
),
),
'posts_per_page' => 5,
'order' => 'ASC',
's' => $search,
'paged' => $paged
);
else:
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => 5,
'order' => 'ASC',
's' => $search,
'paged' => $paged
);
endif;
$posts = new WP_Query($args);?>
<?php if ( $posts->have_posts() ) :?>
<?php while ($posts->have_posts()) : $posts->the_post(); ?>
<?php echo $post->post_title; ?>
<?php endwhile;?>
<?php
$nextpage = $paged+1;
$prevouspage = $paged-1;
$total = $posts->max_num_pages;
$pagination_args = array(
'base' => '%_%',
'format' => '?paged=%#%',
'total' => $total,
'current' => $paged,
'show_all' => false,
'end_size' => 1,
'mid_size' => 2,
'prev_next' => true,
'prev_text' => __('<span class="prev-next" data-attr="'.$prevouspage.'">«</span>'),
'next_text' => __('<span class="prev-next" data-attr="'.$nextpage.'">»</span>'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<div id='pagination' class='pagination'>";
echo $paginate_links;
echo "</div>";
}?>
<?php wp_reset_query(); ?>
<?php else:?>
<div class="no-post-cover">
<div class="container">
<h1 class="has-no-post-list">Posts Not Found</h1>
</div>
</div>
<?php endif;?>
<?php die(1);
}
UPDATE: My ajax function for handling the response is correct, but I have a hard time to iterate through the response object and populate the select field. I've tried and with for loop instead of each() and is working better but the select field was populated with "undefined". Any ideas?
Below is my Jquery code
jQuery(document).ready(function() {
// Avoid conflicts
$ = jQuery;
$('#nomoi-select').change(function() {
var nomos_name = $('#nomoi-select option:selected').attr('id');
var jsonMimeType = "application/json;charset=UTF-8";
type = 'POST';
data = { 'parent_id': nomos_name, action : 'get_child_categories' };
dataType = 'json';
contentType = "application/json; charset=utf-8";
processData = false;
$.post( ajaxurl, data, function(response) {
if( response ){
console.log(response);
var content = '';
var data = JSON.stringify(response);
$(data).each(function(key, value) {
content += '<option>' + value + '</option>';
});
$(content).appendTo("#town-select");
}
});
}).change();
});
My ajax function:
function get_child_categories() {
if (isset($_POST['parent_id'])) {
$parent_id = ($_POST['parent_id']);
$result = array();
$args = array(
'post_type' => 'seller',
'order_by' => 'name',
'hide_empty' => 0,
'exclude' => 1,
'taxonomy' => 'nomos',
'hierarchical' => 1,
'child_of' => $parent_id
);
$categories = get_categories( $args );
foreach ( $categories as $cat ) {
$result = array(
'town_id' => $cat->cat_ID,
'town_name' => $cat->cat_name
);
echo json_encode($result);
}
}
die();
}
add_action('wp_ajax_get_child_categories', 'get_child_categories');
add_action('wp_ajax_nopriv_get_child_categories', 'get_child_categories');
The OnChange is working fine and I get the following output from log:
{"town_id":"41","town_name":"\u0391\u0393\u0393\u0395\u039b\u039f\u039a\u0391\u03a3\u03a4\u03a1\u039f"}{"town_id":"42","town_name":"\u0391\u0393\u03a1\u0399\u039d\u0399\u039f"}{"town_id":"40","town_name":"\u0391\u0399\u03a4\u03a9\u039b\u0399\u039a\u039f"}{"town_id":"84","town_name":"\u0391\u039b\u03a5\u0396\u0399\u0391"}{"town_id":"85","town_name":"\u0391\u039c\u03a6\u0399\u039b\u039f\u03a7\u0399\u0391"}{"town_id":"86","town_name":"\u0391\u039d\u0391\u039a\u03a4\u039f\u03a1\u0399\u039f"}{"town_id":"87","town_name":"\u0391\u039d\u03a4\u0399\u03a1\u03a1\u0399\u039f"}{"town_id":"88","town_name":"\u0391\u03a0\u039f\u0394\u039f\u03a4\u0399\u0391"}{"town_id":"89","town_name":"\u0391\u03a1\u0391\u039a\u03a5\u039d\u0398\u039f\u03a3"}{"town_id":"90","town_name":"\u0391\u03a3\u03a4\u0391\u039a\u039f\u03a3"}{"town_id":"91","town_name":"\u0398\u0395\u03a1\u039c\u039f"}{"town_id":"92","town_name":"\u0398\u0395\u03a3\u03a4\u0399\u0395\u03a9\u039d"}{"town_id":"93","town_name":"\u0399\u0395\u03a1\u0391\u03a3 \u03a0\u039f\u039b\u0397\u03a3 \u039c\u0395\u03a3\u039f\u039b\u039f\u0393\u0393\u0399\u039f\u03a5"}{"town_id":"94","town_name":"\u0399\u039d\u0391\u03a7\u039f\u03a5"}{"town_id":"95","town_name":"\u039c\u0391\u039a\u03a1\u03a5\u039d\u0395\u0399\u0391\u03a3"}{"town_id":"96","town_name":"\u039c\u0395\u0394\u0395\u03a9\u039d\u039f\u03a3"}{"town_id":"97","town_name":"\u039c\u0395\u039d\u0399\u0394\u0399\u039f\u03a5"}{"town_id":"98","town_name":"\u039d\u0391\u03a5\u03a0\u0391\u039a\u03a4\u039f\u03a5"}{"town_id":"99","town_name":"\u039d\u0395\u0391\u03a0\u039f\u039b\u0397\u03a3"}{"town_id":"100","town_name":"\u039f\u0399\u039d\u0399\u0391\u0394\u03a9\u039d"}{"town_id":"101","town_name":"\u03a0\u0391\u039b\u0391\u0399\u03a1\u039f\u03a5"}{"town_id":"102","town_name":"\u03a0\u0391\u039d\u0391\u0399\u03a4\u03a9\u039b\u0399\u039a\u039f\u03a5"}{"town_id":"103","town_name":"\u03a0\u0391\u03a1\u0391\u0392\u039f\u039b\u0391\u03a3"}{"town_id":"104","town_name":"\u03a0\u0391\u03a1\u0391\u039a\u0391\u039c\u03a0\u03a5\u039b\u0399\u03a9\u039d"}{"town_id":"105","town_name":"\u03a0\u039b\u0391\u03a4\u0391\u039d\u039f\u03a5"}{"town_id":"106","town_name":"\u03a0\u03a5\u039b\u039b\u0397\u039d\u0397\u03a3"}{"town_id":"107","town_name":"\u03a3\u03a4\u03a1\u0391\u03a4\u039f\u03a5"}{"town_id":"108","town_name":"\u03a6\u03a5\u03a4\u0395\u0399\u03a9\u039d"}{"town_id":"109","town_name":"\u03a7\u0391\u039b\u039a\u0395\u0399\u0391\u03a3"}
Taking the hint from Tom Kriek:
You could always build all of the tags inside the php
script,and then return that to the function. This saves you iterating
it on the ajax side. All you have to do then is stick the html in the
right spot. Namely in the select tag.
I've used $(#town-select).html(response); in the JQuery response and worked perfectly. Thanx everybody!
I've made a form with two select fields. The first field is populated with the parents of a custom taxonomy. The second field is populated with the children of each one. I used AJAX to do that but does not seem to work. Nothing happens on change.
Below is my PHP code:
function products_selection()
{
$args = array(
'post_type' => 'seller',
'taxonomy' => 'category',
'hide_empty' => 0,
'exclude' => 1,1078,1079
);
$products = get_categories( $args );
if ( $products ) {
echo '<select id="products-select">';
echo '<option selected="" disabled="" value="0"><span>Προϊόντα</span></option>';
foreach ($products as $product) {
echo '<option class="product-name" id="'. $product->term_id .'">'. $product->name .'</option>';
}
echo '</select>';
}
}
function nomoi()
{
$args = array(
'post_type' => 'seller',
'taxonomy' => 'nomos',
'hide_empty'=> 0,
'parent' => 0
);
$categories = get_categories( $args );
if ( $categories ) {
echo '<select id="nomoi-select">';
echo '<option selected="0" value="-1"><span>Νομοί</span></option>';
foreach ( $categories as $category ) {
$id = $category->term_id;
$name = $category->name;
$taxonomy = $category->taxonomy;
echo '<option class="nomos" id="'. $id .'">'. $name .'</option>';
}
echo '</select>';
}
echo '<select id="town-select">';
echo '<option selected="" disabled="" value="0"><span>Πόλεις</span></option>';
echo '</select>';
}
function my_ajax() {
if(isset($_POST['main_catid']))
{
$args = array(
'order_by' => 'name',
'hide_empty' => 0,
'exclude' => 1,
'taxonomy' => 'nomos',
'name' => 'town-select',
'hierarchical' => 1,
'show_option_none' => 'Πόλεις',
'selected' => -1,
'child_of' => $_POST['main_catid'],
'echo' => 1
);
$categories = get_categories( $args );
foreach ( $categories as $cat ) {
$cat_name = $cat->name;
$id = $cat->cat_ID;
echo '<option class="town" id="'. $category->id .'">'. $category->name .'</option>';
}
die();
} // end if
}
My script:
jQuery(document).ready(function() {
// Avoid conflicts
$ = jQuery;
$('#nomoi-select').change(function() {
$mainCat = $('#nomoi-select option:selected').attr('id');
console.log('$mainCat: ' + $mainCat);
// call ajax
$("#town-select").empty();
$.ajax
(
{
url:'index.php',
type:'POST',
// Use an object literal
data: {
"action" : "my_ajax()",
"main_catid" : $mainCat
},
success:function( results )
{
// alert(results);
alert('Successfully called');
$("#town-select").append( results );
},
error:function( exception )
{
alert('Exception: ' + exception);
}
}
);
});
});
And the function to register my script:
function my_scripts() {
wp_enqueue_script( 'header-form', get_template_directory_uri() . '/js/headerform.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
Since you are working with WordPress, I suspect you could be having jQuery conflict issues. To confirm this, you can try changing all instances of $ to jQuery and see if you get the same errors.
Also - if you are running this script from a .js file, the PHP wont evaluate, but keeping the URL relative should still work fine.
I have made a few changes to the script which you can try:
jQuery(document).ready(function() {
// Avoid conflicts
$ = jQuery;
$('#main_cat').change(function() {
$mainCat = $('#main_cat option:selected').val();
// call ajax
$("#sub_cat").empty();
$.ajax
(
{
url:"/wp-admin/admin-ajax.php",
type:'POST',
// Use an object literal
data: {
"action" : "my_ajax",
"main_catid" : $mainCat
},
success:function( results )
{
// alert(results);
$("#sub_cat").removeAttr("disabled").append( results );
}
}
);
});
});
From the fiddle you provided, simply adding console.log('$mainCat: ' + $mainCat); (see this modified fiddle) ensures that the change event fires as expected.
Beyond that we get a 404 not found error, which is pretty normal in the current state of the fiddle example.
So it is certain that your issue comes from something with the Ajax called script or its returned data.
You only said that "Nothing happens on change", without any precision. In fact you should now use Firebug or similar to look at error messages, which may be, either:
an URL generation error: in this case you should get a 404 not found error too
an error in the server script you're invoking: in this case you should get a 500 server error error
a bad (malformed) return from the server: in this case you should get a JS error
Also note that:
it cannot be an empty return from the server, or your #sub_cat element would have already lost its disabled attribute before a JS error happens
at the opposite (even if unlikely) it also might be an Ajax error: so to be sure you should add an error: or always: member to the $.ajax() argument
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.