Wordpress: get terms by ajax - javascript

I'm new in wordpress, but i need to collect all photos in posts, and group by categories. My Js is
function get_photos(elem)
{
$.ajax({
cache: true,
type: "GET",
timeout: 20000,
url: 'wp-content/themes/wp_theme/photos.php',
success: function(msg)
{
$(elem).append(msg);
},
error: function(msg)
{
get_photos(elem);
return false;
}
});
}
And the photos.php is the :
<?php
require('../../../wp-load.php');
$tax_terms = get_terms('media_category', 'orderby=count&order=DESC&hide_empty=0');
foreach ( $tax_terms as $tax_term ) {
?>
<div class="news">
<img src="./wp-content/themes/wp_theme/img/plus.png" class="plus">
<div class="titleNews2"><?php echo $tax_term->name; ?></div>
</div>
<?php
$posts = get_posts(array(
"post_type" => "attachment",
"post_mime_type" => "image",
"taxonomy" => $tax_term->taxonomy,
"term" => $tax_term->slug,
"numberposts" => 100,
"posts_per_page" => 100));
?>
<div class="photoRace">
<?php
$ua = #getenv( HTTP_USER_AGENT );
$touchPadApple = stripos( strtolower( $ua ), "iphone" ) !== false || stripos( strtolower( $ua ), "ipad" ) !== false ? true : false;
foreach($posts as $post){
setup_postdata($post);
$img = get_post_meta($post->ID, "_wp_attachment_metadata", true);
$dir = explode("/", $img['file']);
$link = get_bloginfo('siteurl')."/wp-content/uploads/{$dir[0]}/{$dir[1]}/";
?>
<a <?php echo !$touchPadApple ? "rel=\"photos\" " : "target=_BLANK "; ?>href="<?php echo get_bloginfo('siteurl')."/wp-content/uploads/".$img['file'];?>">
<img src="<?php echo $link.$img['sizes']['thumbnail']['file'];?>" height="<?php echo $img['sizes']['thumbnail']['height']; ?>" width="<?php echo $img['sizes']['thumbnail']['width']; ?>">
</a>
<?php } ?>
</div>
<?php } ?>
Im working on mobile interface, and this script (not via ajax) works well on non-mobile static pages of theme. But when i using it via ajax, im getting only some photos, and if i call var_dump($tax_terms); the result is
object(WP_Error)#4418 (2) { ["errors"]=> array(1) {
["invalid_taxonomy"]=> array(1)
What should i include to use terms?

You should use wp_ajax in the first place, and then you can skip the first require.

Related

Ajax Load More Code Breaks When Adding Category ID in $args (WordPress)

I implemented a AJAX Load More Posts code from one of the guides available on Internet. The code suited me and works well in archive.php. But when I try to use the same code in taxonomy-product-cat.php adding
$cat_id=get_query_var('cat'); 'cat' => $cat_id in $args
the code breaks and returns blank.
Here is the complete code I have been using. I think the error is triggered by the JS and since I am not familiar with JS, I would want some help to fix it.
My product-taxonomy-cat.php
<div class="entry-content">
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => '2',
'paged' => 1,
);
$blog_posts = new WP_Query( $args );
?>
<?php if ( $blog_posts->have_posts() ) : ?>
<div class="blog-posts">
<?php while ( $blog_posts->have_posts() ) : $blog_posts->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
</div>
<div class="loadmore">Load More...</div>
<?php endif; ?>
</div>
Registering and localizing AJAX script in functions
function blog_scripts() {
// Register the script
wp_register_script( 'custom-script', get_stylesheet_directory_uri(). '/js/custom.js', array('jquery'), false, true );
// Localize the script with new data
$script_data_array = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'security' => wp_create_nonce( 'load_more_posts' ),
);
wp_localize_script( 'custom-script', 'blog', $script_data_array );
// Enqueued script with localized data.
wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'blog_scripts' );
My AJAX Js
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore', function() {
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'security': blog.security
};
$.post(blog.ajaxurl, data, function(response) {
if($.trim(response) != '') {
$('.blog-posts').append(response);
page++;
} else {
$('.loadmore').hide();
}
});
});
});
AJAX callback function
add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');
Load More Posts Loop in Functions
function load_posts_by_ajax_callback() {
check_ajax_referer('load_more_posts', 'security');
$paged = $_POST['page'];
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => '2',
'paged' => $paged,
);
$blog_posts = new WP_Query( $args );
?>
<?php if ( $blog_posts->have_posts() ) : ?>
<?php while ( $blog_posts->have_posts() ) : $blog_posts->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<?php
endif;
wp_die();
}
Please help me load more posts with this AJAX when in category as well.

javascript array displays the name of the array not the contents (gtag, purchase event)

I am trying to create a gtag purchase event code in a Woocommerce Eshop in Thank you page.
But when I see the code in source in the browser it is displaying the name of the array and not the contents.
I can see the purchases in google dashboard but there is no track of the items.
I can only see the total price of the purchases.
Here is my code:
if( is_wc_endpoint_url( 'order-received' ) ){
$order_id = absint( get_query_var('order-received') );
$order = wc_get_order( $order_id );
$order_items = $order->get_items();
$items_data = []; // Initializing
foreach ( $order_items as $item_id => $item ) {
$variation_id = $item->get_variation_id();
$product_id = $variation_id > 0 ? $variation_id : $item->get_product_id();
//get the categories tree
foreach( wp_get_post_terms( $product_id, 'product_cat' ) as $term ){
if( $term ){
$categories .= $term->name;
$categories .= '/';
}
}
$categories = trim($categories, '/');
$product = wc_get_product( $product_id );
// Set specific data for each item in the array
array_push($items_data, array(
item_id => $product->get_sku(),
item_name => $product->get_name(),
item_category => $categories,
quantity => $item->get_quantity(),
price => $item->get_subtotal(),
));
$categories = '';
}
?>
<script>
var items_data = <?=json_encode($items_data)?>;
var my_items = [];
for(var i=0; i<items_data.length; i++){
var item = items_data[i]; console.log(item);
my_items.push({
item_id:item.item_id,
item_name:item.item_name,
item_category:item.item_category,
quantity:item.quantity,
price:item.price
});
}
</script>
<!-- Event snippet for Website sale conversion page -->
<script> gtag('event', 'conversion', { 'send_to': 'AC-898s89ds/PNdsds78dsy_ds82B', 'value': '<?php echo $order->get_total(); ?>', 'currency': 'EUR', 'transaction_id': '<?php echo $order_id; ?>' }); </script>
<script>
console.log({items:my_items}); //this displays correctly the content of the array
gtag('event', 'purchase', { 'transaction_id': '<?php echo $order_id; ?>', 'affiliation': 'eartshop.gr', 'value': '<?php echo $order->get_total(); ?>', 'currency': 'EUR', 'shipping': '<?php echo $order->get_shipping_total(); ?>', 'tax' : '<?php echo $order->get_total_tax(); ?>', 'items': my_items });
</script>
And this is what I see in the source code of Thank you page :
gtag('event', 'purchase', { 'transaction_id': '10707', 'affiliation': 'eshopdomain.com', 'value': '152.00', 'currency': 'EUR', 'shipping': '0.00', 'tax' : '29.03', 'items': my_items });
Your function can be optimized. Use the woocommerce_payment_complete and woocommerce_thankyou hooks to make sure the event fires every time an order is successful.
The woocommerce_payment_complete hook is required for payments such
as PayPal or credit card (Stripe or others). Customers do not always
wait for the redirect on the site and therefore the event may not be
activated with just the woocommerce_thankyou hoook.
// adds the Google Analytics "purchase" event to the thankyou page
add_action( 'woocommerce_payment_complete', 'set_google_tag_transaction_conversion_event' );
add_action( 'woocommerce_thankyou', 'set_google_tag_transaction_conversion_event', 99, 1 );
function set_google_tag_transaction_conversion_event( $order_id ) {
if ( ! $order_id ) {
return;
}
$order = wc_get_order( $order_id );
?>
<!-- Event snippet for Website sale conversion page -->
<script> gtag('event', 'conversion', {
'send_to': 'AC-898s89ds/PNdsds78dsy_ds82B',
'value': '<?php echo $order->get_total(); ?>',
'currency': 'EUR',
'transaction_id': '<?php echo $order_id; ?>'
});
</script>
<!-- Google Tag: Transaction conversion event -->
<script>
gtag('event', 'purchase', {
"transaction_id": "<?php echo $order_id; ?>",
"affiliation": "eartshop.gr",
"value": <?php echo $order->get_total(); ?>,
"currency": "EUR",
"tax": <?php echo $order->get_total_tax(); ?>,
"shipping": <?php echo $order->get_shipping_total(); ?>,
"items": [
<?php foreach( $order->get_items() as $item_id => $item_product ) {
$product = $item_product->get_product();
$quantity = $item_product->get_quantity();
$subtotal_line = $item_product->get_subtotal();
$price = $subtotal_line / $quantity;
$product_name = $product->get_name();
$name = str_replace( ',', '', $product_name );
$categories = array();
//get the categories tree
foreach( wp_get_post_terms( $product->get_id(), 'product_cat' ) as $term ){
if ( $term ) {
$categories[] = $term->name;
}
}
if ( ! empty($categories) ) {
$product_categories = implode( '/', $categories );
} else {
$product_categories = '';
}
?>
{
"id": "<?php echo $product->get_sku(); ?>",
"name": "<?php echo $name; ?>",
"category": "<?php echo $product_categories; ?>",
"quantity": <?php echo $quantity; ?>,
"price": "<?php echo $price; ?>",
},
<?php
} // end foreach order items
?>
]
});
</script>
<?php
}
The code has been tested and works. Add it to your active theme's functions.php.

Get json file result dynamically by url parameter

if have a json file like this example
market.json
{ topads:
[ { id: 114
, advert_type: 11
, cat_main_id: 5932
, cat_market: 1
, subcat1_id: 12
, endcat: 'Sneakers'
, description: 'Nike Air Jordan 1 '
} ] }
with php i will get the json file and show all entries with eg subcat1_id 12,15 and 23 (and max. 4 entries)
<?php
$url_json = $baseurl . 'json/market.json';
$response = file_get_contents( $url_json );
$obj = json_decode( $response, true );
//subcat1_id
$ad_types = array( 12,15,23);
$Count = 0;
shuffle($obj[ 'topads' ]);
foreach ( $obj[ 'topads' ] as $result ) {
if ( in_array( $result[ 'subcat1_id' ], $ad_types ) ) {
?>
<div class="col-xl-3 col-lg-3 col-md-4">
//some html and php content to show the output eg. echo $result[ 'description' ]
</div>
<?php
$Count++;
if ($Count == 4){
break; //stop foreach loop after 4th loop
}
}
}
?>
ok this works perfectly in php but I want a url parameter (e.g. & subcat1 = 12), instead of the hard coded $ad_types.
So every time the URL parameter changes, the json file entries should also be displayed dynamically.
But how?
js/jquery
<script>
const subcat1= urlParams.get('subcat1')
</script>
to get the url parameter subcat1
and then? Result via Ajax to show the results dynamically?
function getresults() {
$.ajax({
url: "myphpfile.php",
method: "POST",
data: subcat1,
success: function (data) {
// ...
}
});
}
Update getresults function with below:
function getresults() {
$.ajax({
url: "myphpfile.php",
method: "POST",
data: {subcat1: subcat1},
success: function (data) {
}
});
}
and get in php code like this-
$_POST["subcat1"];
Ajax data needs to contain key/value pairs, you are only sending a value
Try :
data: {subcat1 : subcat1 }
Then access it in php with:
$_POST['subcat1']
I have solved it.
Thanks for the hints on the solution!
The JS file to get the url parameter dynamically.
<script>
// get parameter from url
var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
var subcat = urlParams.get('subcat1');
//console.log(subcat);
getresult(subcat);
// ajax call
function getresult(subcat) {
$.ajax({
url: "myphpfile.php",
method: "post",
data: {
"subcat": subcat
},
success: function (data) {
$('#ad_content').html(data);
},
error: function () {
$('#ad_content').html('error');
}
});
}
</script>
and the php file to show the
myphpfile.php
<section class="mt-1 mb-1 d-none d-lg-block">
<div class="col-xl-12 col-lg-12 col-md-12 pl-0 pr-0">
<div class="row">
<?php
$url_json = '/json/market.json';
$response = file_get_contents( $url_json );
$obj = json_decode( $response, true );
if ( isset( $_POST[ 'subcat' ] ) && !empty( $_POST[ 'subcat' ] ) ) {
// this is the value from the url parameter
$adcat = array( $_POST[ 'subcat' ] );
$Count = 0;
shuffle( $obj[ 'topads' ] );
foreach ( $obj[ 'topads' ] as $result ) {
if ( in_array( $result[ 'subcat1_id' ], $adcat ) ) {
?>
<div class="col-xl-3 col-lg-3 col-md-4">
<div class="item">
<div class="card mb-0">
<?php echo $result[ 'description' ]; ?>
</div>
</div>
</div>
<?php
$Count++;
if ( $Count == 4 ) {
break; //stop foreach loop after 4th loop
}
}
}
}
?>
</div>
</div>
</section>
and of course the place to show the result
<div id="ad_content"></div>

Back button doesn't recall AJAX content location in Chrome

I am dynamically loading talent content on this page with AJAX: www.icon.pha-group.com it uses pagination to go browse the content. My problem is that in Google Chrome doesnt remember the paginated page you were on. So if I'm on page 2 of content, click an item, then go back, it goes back to page 1. Is there some way I can modify this code to solve the problem? Here is the AJAX function:
function get_posts($params) {
$container = $('#container-async');
$content = $container.find('.content-ajax');
$status = $container.find('.status');
$status.text('Fetching talent...');
$.ajax({
//url: bobz.ajax_url,
url: "/wp-admin/admin-ajax.php",
data: {
action: 'do_filter_posts',
nonce: bobz.nonce,
params: $params
},
type: 'post',
dataType: 'json',
success: function(data, textStatus, XMLHttpRequest) {
if (data.status === 200) {
$content.html(data.content);
}
else if (data.status === 201) {
$content.html(data.message);
}
else {
$status.html(data.message);
}
//all done so call cycle script
script_cycle();
// window.location.hash = $this.closest('span').find('.current');
// console.log(window.location.hash);
//angular.bootstrap(document, ['lightbox']);
},
error: function(MLHttpRequest, textStatus, errorThrown) {
$status.html(textStatus);
/*console.log(MLHttpRequest);
console.log(textStatus);
console.log(errorThrown);*/
},
complete: function(data, textStatus) {
msg = textStatus;
if (textStatus === 'success') {
msg = data.responseJSON.found;
}
// $status.text('Posts found: ' + msg);
$status.text('');
/*console.log(data);
console.log(textStatus);*/
}
});
}
Code update, heres the pagination:
function vb_ajax_pager( $query = null, $paged = 1 ) {
if (!$query)
return;
$paginate = paginate_links([
'base' => '%_%',
'type' => 'array',
'total' => $query->max_num_pages,
'format' => '#page=%#%',
'current' => max( 1, $paged ),
'prev_text' => 'Prev',
'next_text' => 'Next'
]);
if ($query->max_num_pages > 1) : ?>
<ul class="pagination">
<?php foreach ( $paginate as $page ) :?>
<li><?php echo $page; ?></li>
<?php endforeach; ?>
</ul>
<?php endif;
}
You can store/fetch the information that you need in/from javascript local storage variable.
In this way you can remember the paginated page you were on.
That's because you don't change URL after clicking on an item.
$('.youritemclicked').click(function() {
location.hash($(this).attr('id'));
});
Or you can simply wrap your item in a anchor tag:
<a href="#item2">
<!-- Your item body -->
</a>
IMPORTANT
Make sure that you don't have set preventDefault() by clicking on this item
Then you can go back and forward in your browser because now you have history saved also for this items.
UPDATE
if ($query->max_num_pages > 1) : ?>
<ul class="pagination">
<?php foreach ( $paginate as $page ) :?>
<li><?php echo $page; ?></li>
<?php endforeach; ?>
</ul>
<?php endif;

Ajax call returning 0 as response in mobile

I am trying to call ajax in wordpress. It work fine in browser but in mobile device it return response 0 . Here is my wordpress & Jquery code. please suggest where i am doing wrong
The code in functions.php file
function get_nearest_destinations()
{
$data = array();
check_ajax_referer( "getnearestdestinations" );
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$the_query = new WP_Query($args);
if($the_query->have_posts()){
while ( $the_query->have_posts() ) :
$the_query->the_post();
$data[] = array('title'=>get_the_title());
endwhile;
}
echo json_encode($data); exit();
}
add_action( 'wp_ajax_getnearest', 'get_nearest_destinations' );
Below is js code in template file....
<?php $nonce = wp_create_nonce( 'getnearestdestinations' ); ?>
jQuery.ajax({
type: "POST",
url: "<?php echo bloginfo('url').'/wp-admin/admin-ajax.php'; ?>",
data: { action: 'getnearest', _ajax_nonce: '<?php echo $nonce; ?>'},
dataType: "json",
success: function(html){
alert(html)
}
}); //close jQuery.ajax(
May be you have non logged in user issue.Pl use below syntax for non logged in users
add_action('wp_ajax_nopriv_getnearest', 'get_nearest_destinations'); // Not logged in user

Categories