Duplicate posts on AJAX call in WordPress - javascript

I've attempted to setup a 'load more' button in WordPress. Simple idea, you press the button and it loads more posts using AJAX without reloading the page or needing to use pagination.
I followed a previous article on SO and have managed to get it to mostly work.
So far, I've been able to get additional posts loading fine, but for some reason, they are being duplicated. I had a look in the Networks tab and it seems each time I press the button, admin-ajax.php runs twice which I suspect is what's causing the duplication. Unfortunately, I'm not too sure what I need to change to resolve this.
It would also be really helpful to know how to get this working for custom post types as well as normal posts. On my website, I've got two post types, Standard blog posts and a custom 'Projects' post type. Each has its own page and own loop, how would I modify the above to get it to work for both? Would I need to write out the whole thing twice or maybe It's something simpler?
Any ideas guys?
Here is the HTML:
<section id="ajax-posts" class="layout">
<?php get_template_part( 'content', 'blog' ); ?>
</section>
<div class="load-more layout">
<a id="more_posts" class="button"><span class="icon-plus"></span></a>
</div>
Here is the main loop:
<?php
$postsPerPage = 1;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_post_thumbnail();?>
<div class="inner-text">
<h4 class="post-title"><?php the_title(); ?></h4>
<h5><span class="icon-calendar"></span> <?php the_date(); ?></h5>
<?php the_excerpt(); ?>
Read More<span class="icon-arrow-right2"></span>
</div>
</article>
<?php endwhile; wp_reset_postdata(); ?>
Here is my functions.php:
function wpt_theme_js() {
wp_enqueue_script( 'bigredpod-script', get_template_directory_uri() . '/js/main.js', array( 'jquery' ), '', true );
wp_localize_script( 'bigredpod-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'bigredpod'),
));
}
wp_localize_script( 'bigredpod-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'bigredpod'),
));
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 1;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'posts_per_page' => $ppp,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .=
'<article id="post-'. get_the_ID().'" class="'. implode(' ', get_post_class()) .'">
'.get_the_post_thumbnail().'
<div class="inner-text">
<h4 class="post-title">'.get_the_title().'</h4>
<h5><span class="icon-calendar"></span> '.get_the_date().'</h5>
<p>'.get_the_excerpt().'</p>
Read More<span class="icon-arrow-right2"></span>
</div>
</article>';
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 is my JS:
jQuery(document).ready(function($) {
var ppp = 1; // Post per page
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&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").addClass('posts_loading');
} else{
$("#more_posts").removeClass('posts_loading').addClass('no_more_posts');
}
},
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();
});
});

You have put twice
wp_localize_script( 'bigredpod-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'bigredpod'),
));
In your wpt_theme_js() function. This is probably what causes the ajax to load twice.

Related

Wordpress unable to save featured image

this is Nadeem I am a beginner on PHP and WordPress, I stuck on one point during custom plugin development, my problem is, I am unable to save Featured image and custom taxonomy tag and category from the frontend. In the meantime, I already Search on Google, StackOverflow, etc. too much for this error solution about this but unfortunately, this does not work and I am stuck at this point from the last 2 weeks.
This is my Plugin PHP code
/**
* The Template for displaying car archives, including the main car-data page which is a post type archive.
*
* Override this template by copying it to yourtheme/car_data/archive-car-data.php
*
* #author Shaikh Nadeem
* #package Car_Data
* #subpackage Car_Data/Templates
* #version 1.0.0
*/
class Car_Frontend_Form
{
function __construct()
{
add_shortcode( 'submit_car', array($this, 'submit_car') );
add_action( 'wp_enqueue_scripts', array( $this, 'my_enqueue' ) );
add_action( 'save_post_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_nopriv_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'init', array( $this, 'submit_car_data_post' ) );
}
public function submit_car() {
echo '<div id="submit_car_form">';
echo '<form id="cd_car" name="cd_car" class="cd_car" method="post" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data" >';
wp_nonce_field( "car-frontend-post" );
echo '<p><label for="title">Title</label><br />';
echo '<input type="text" id="title" value="" size="60" name="title" />';
echo '</p>';
echo '<p>';
echo '<label for="content">Post Content</label><br />';
echo '<textarea id="content" name="content" cols="40" rows="4"></textarea>';
echo '</p>';
echo '<p><label for="feature">Feature:</label><br />';
wp_dropdown_categories( "show_option_none=Feature&tab_index=3&taxonomy=feature&name=feature&id=feature&class=feature" ) .'</p>';
echo '<p><label for="make">Make:</label><br />';
wp_dropdown_categories( "show_option_none=Make&tab_index=4&taxonomy=make&name=make&id=make&class=make" ) .'</p>';
echo '<p><label for="post_tags">Tags</label><br />';
echo ' <input type="text" value="" size="60" name="post_tags" id="post_tags" /></p>';
echo '<p><label for="post_tags">Car Image</label><br />';
echo '<input type="file" name="file" id="file"></p>';
echo '<p align="left"><input type="submit" tabindex="6" id="submit_car" name="submit_car" /></p>';
echo '</form>';
echo '</div>';
return;
}
public function submit_car_data_post() {
if ( isset($_POST['title']) ) {
echo '<script>console.log("file error: '.$fileerror.'<br>");</script>';
$title = sanitize_text_field( $_POST['title'] );
$content = sanitize_text_field( $_POST['content'] );
$author_id = sanitize_text_field( $_POST['author_id'] );
$tags_input = sanitize_text_field( array($_POST['post_tags']) );
$feature = sanitize_text_field( array($_POST['feature']) );
$make = sanitize_text_field( array($_POST['make']) );
// $image = $_POST['file'];
$args = array(
'post_title' => $title,
'post_content' => $content,
'tags_input' => $_POST['post_tags'],
'author' => $author_id,
'post_status' => 'publish',
'post_type' => 'car-data',
'tax_input' => array(
$feature,
$make
),
// 'post_category' => array(
// 'feature' => array($_POST['feature']),
// 'make' => array($_POST['make'])
// )
);
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'car-frontend-post') ) {
return;
}
if( is_wp_error( $posts ) ){
echo json_encode( $posts->get_error_messages() );
}
// save frontend Post
$posts = wp_insert_post( $args );
// save frontend Texonomy
wp_set_object_terms( $posts, $feature, 'feature' );
wp_set_object_terms( $posts, $make, 'make' );
// save Atachment on featured image for the current custom post
$uploaddir = wp_upload_dir();
$file = $_FILES[$image];
$uploadfile = $uploaddir['path'] . '/' . basename( $file );
move_uploaded_file( $_FILES['file']['tmp_name'], $uploaddir['path'] . '/' . $filename );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => preg_replace('/\.[^.]+$/', '', $filename),
'post_excerpt' => preg_replace('/\.[^.]+$/', '', $filename),
'post_status' => 'inherit',
'post_type' => 'attachment',
'menu_order' => $_i + 1000,
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata($attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
wp_die();
}
}
public function my_enqueue() {
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
}
and i use javascript for the ajax alert message when form is submit
jQuery(document).ready(function($) {
$('.cd_car').on('submit', function(event) {
event.preventDefault();
var message = document.getElementById("file").value;
var empt = document.forms["cd_car"]["title"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
else
{
$.ajax({
type: 'post',
// url : ajax_object.ajaxurl,
data : $('.cd_car').serialize(),
success : function(data){
alert(message);
console.log(data);
},
error : function(data){
alert(message);
alert('fail');
}
});
}
});
});
Also i have there one error on this line code if ( isset($_POST['title']) ) unable to use submit key on isset post only title is working here.
I believe your issue is due to sanitize_text_field( array( .. )). sanitize_text_field only accepts strings as the parameter, so I assume by sending in an Array it's actually always seeing the string "Array" - not your POST values.
To sanitize the array, could do something like:
$tags_input = array();
if ( isset($_POST['post_tags']) && !empty($_POST['post_tags']) ) {
foreach ($_POST['post_tags'] as $val)
$tags_input[] = sanitize_text_field( $val );
}
// [ .. repeat for feature & make .. ]
Or, if they're single values only (not arrays), simply remove the array wrapper.

Getting AJAX load more to work with custom Wordpress related posts Query?

I"m using the tutorial from this blog post to implement Ajax Load More functionality. https://rudrastyh.com/wordpress/load-more-posts-ajax.html
I've successfully implemented this on my archive page for all blog posts. However, I've got several "RElated Posts" sections that use custom WP Queries that I can't get to work. I've tried the solution in this comment: https://rudrastyh.com/wordpress/load-more-posts-ajax.html#comment-1055
It loads new posts, but they are not adhering to the argumenets of the custom query (specifically displaying posts only in the same category).
The custom query is working (it displays 4 related posts from the same category). When i'm loading more, it is not respecting pagination (it's loading 6 posts instead of 4) and it is not respecting the query (it is loading posts not in the same category).
<div class="related-blog-posts gray-bg pt-5 pb-5 blog">
<div class="related-title pb-3">
<h1 class="mb-2">Related Stories</h1>
<img src="/dcustom/wp-content/uploads/2019/04/Path-137#2x.png" />
</div><!-- scroll-down-->
<div class="container">
<div class="row">
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query_args = array(
'category__in' => wp_get_post_categories( $post->ID ),
'paged' => $paged,
'post_type' => 'post',
'posts_per_page' => 4,
'post__not_in' => array( $post->ID ),
'orderby' => 'date',
'order' => 'DESC'
);
$third_query = new WP_Query( $query_args ); ?>
<?php
//Loop through posts and display...
if($third_query->have_posts()) : ?>
<?php while ($third_query->have_posts() ) : $third_query->the_post(); ?>
<?php get_template_part('template-parts/content-related-blog-posts'); ?>
<?php endwhile; ?><!-- end the loop-->
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<?php // don't display the button if there are not enough posts
if ( $third_query->max_num_pages > 1 )
echo '<a class="custom_loadmore btn btn-primary">More posts</a>'; // you can use <a> as well
?>
<?php endif; ?><!-- end loop if--->
</div><!-- row -->
</div><!-- container -->
</div><!-- related-case-studies-->
<script>
var test = '<?php echo serialize( $third_query->query_vars ) ?>',
current_page_myajax = 1,
max_page_myajax = <?php echo $third_query->max_num_pages ?>
</script>
<script src="<?php bloginfo('template_url')?>/js/myloadmore.js"></script>
jQuery(function($){ // use jQuery code inside this to avoid "$ is not defined" error
$('.misha_loadmore').click(function(){
var button = $(this),
data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
'page' : misha_loadmore_params.current_page
};
$.ajax({ // you can also use $.post here
url : misha_loadmore_params.ajaxurl, // AJAX handler
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...'); // change the button text, you can also add a preloader image
},
success : function( data ){
if( data ) {
button.text( 'More posts' ).prev().after(data); // insert new posts
misha_loadmore_params.current_page++;
if ( misha_loadmore_params.current_page == misha_loadmore_params.max_page )
button.remove(); // if last page, remove the button
// you can also fire the "post-load" event here if you use a plugin that requires it
// $( document.body ).trigger( 'post-load' );
} else {
button.remove(); // if no data, remove the button as well
}
}
});
});
$('.custom_loadmore').click(function(){
//custom query on front-page.php
var button = $(this),
data = {
'action': 'loadmore',
'query': test,
'page' : current_page_myajax
};
$.ajax({
url : '/dcustom/wp-admin/admin-ajax.php', // AJAX handler
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...'); // change the button text, you can also add a preloader image
},
success : function( data ){
if( data ) {
button.text( 'More posts' ).prev().after(data); // insert new posts
current_page_myajax++;
if ( current_page_myajax == max_page_myajax )
button.remove(); // if last page, remove the button
} else {
//button.remove(); // if no data, remove the button as well
}
}
});
});
});
function misha_my_load_more_scripts() {
global $wp_query;
// In most cases it is already included on the page and this line can be removed
wp_enqueue_script('jquery');
// register our main script but do not enqueue it yet
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js', array('jquery') );
// now the most interesting part
// we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
// you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
wp_localize_script( 'my_loadmore', 'misha_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' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
) );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
/* AJAX LOOP FOR THE ARCHIVE PAGE */
function misha_loadmore_ajax_handler(){
// prepare our arguments for the query
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
// it is always better to use WP_Query but not here
query_posts( $args );
if( have_posts() ) :
// run the loop
while( have_posts() ): the_post();
// look into your theme code how the posts are inserted, but you can use your own HTML of course
// do you remember? - my example is adapted for Twenty Seventeen theme
get_template_part( 'template-parts/content-index', get_post_format() );
// for the test purposes comment the line above and uncomment the below one
// the_title();
endwhile;
endif;
die; // here we exit the script and even no wp_reset_query() required!
}
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}

Filter category ajax in wordpress

I'm trying to make a custom category filter with ajax on frontpage.When I click on any of the custom taxonomy the content dissapears and I don't get any content.Custom post type are aranzman.
This is the page-usluge.php
<ul class="categories-filters">
<?php $args= array(
'show_option_all' => 'All posts', //Text for button All
'title_li' => __(''),
'taxonomy' => 'vrsta-aranzmana',
'post_type' => 'aranzman' );
wp_list_categories( $args ); ?> </ul>
<?php $query = new WP_query ( $args );
if ( $query->have_posts() ) { ?>
<div id="main-content" class="row">
<div id="inside">
<div class="container">
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<article>
<a class="xiong-articlebox" href="<?php the_permalink();?>">
<header>
<h3><?php the_title( );?></h3> <p><em><?php the_date( 'j.n.Y'); ?> </em></p> </header>
<p><?php the_excerpt();?></p> </a> </article>
<?php endwhile; }?>
</div><!-- container-->
</div><!--inside -->
</div> <!--row -->
This is the ajax.js
jQuery(function(){
var mainContent = jQuery('#main-content'),
cat_links = jQuery('ul.categories-filters li a');
cat_links.on('click', function(e){
e.preventDefault();
el = jQuery(this);
var value = el.attr("href");
mainContent.animate({opacity:"0.5"});
mainContent.load(value + " #inside", function(){
mainContent.animate({opacity:"1"});
});
});
});
And this is the functions.php calling the ajax.js
function ajax_theme_scripts() {
//Ajax filter scripts
wp_register_script( 'ajax', get_stylesheet_directory_uri() . '/js/ajax.js', array( 'jquery' ), '1.0.0', true );
wp_enqueue_script( 'ajax' );
}
add_action( 'wp_enqueue_scripts', 'ajax_theme_scripts' );
The 'not' working demo or example is on this link
DEMO
First of all, Wordpress already comes with an ajax handler (admin-ajax.php).
Here is the link to documentation for that: https://codex.wordpress.org/AJAX_in_Plugins.
Briefly, what you have to do is:
1) add_action('wp_ajax_nopriv_{your_action_id}', callback)
Your call back here is supposed to be the filter function
2) Write a javascrip ajax:
$.ajax({
method: "expected method(POST)",
url: "wp-admin/admin-ajax.php (should be called dynamically with wp_localize_script => https://codex.wordpress.org/Function_Reference/wp_localize_script)"
dataType: "expected dataType(JSON)",
data: {
action: {your_action_id},
"other data that you want to send"
}
success: function(response){}
});
To be able to handle the content of the response, you need to send as part of your response the html/text of the result. In this way, all you need to do is to use the simple jquery method $(selector).html(htmlOfResult);
To send data to your javascript success callback, you can use wp_send_json() https://codex.wordpress.org/Function_Reference/wp_send_json.
Here is for ajax.js
jQuery(document).ready(function($) {
$('ul.categories-filters li a').on('click', function(event) {
event.stopPropagation();
event.preventDefault();
$.ajax({
method: "POST",
url: Object_var.ajax_url_attr,
dataType: "JSON",
data: {
action: "myfilter_action",
// I think you are using the href to check filter
filter_req: $(this).attr('href')
},
success: function(response) {
if(typeof response != "undefined")
$('#inside .container').html(response.html_text);
}
});
});
});
here is for the function.php
<?php
add_action('wp_enqueue_scripts', function(){
// Register first the ajax.js script
wp_enqueue_script('handle_of_script', 'link/to/ajax.js');
// Now send variable to the script
wp_localize_script('handle_of_script', "Object_var", [
"ajax_url_attr" => admin_url( 'admin-ajax.php' )
]);
});
add_action("wp_ajax_nopriv_myfilter_action", function(){
$filter_req = $_POST['filter_req'];
// Run filter of whatever
$query_result = your_filter();
// Convert values to html/text
$html_text = convert_to_html_text($query_result);
// Send data to jQuery AJAX
wp_send_json(
"html_text" => $html_text
);
wp_exit();
});
function convert_to_html_text($query) {
$html = "";
ob_start();
// Maybe check if query is valid or have post ...
?>
<?php while ( $query->have_posts() ): $query->the_post(); ?>
<article>
<a class="xiong-articlebox" href="<?php the_permalink(); ?>">
<header>
<h3><?php the_title(); ?></h3>
<p>
<em><?php the_date( 'j.n.Y'); ?></em>
</p>
</header>
<p><?php the_excerpt();?></p>
</a>
</article>
<?php endwhile;?>
<?
$html_text = ob_get_contents();
return $html;
}
I think this could help!

Updating / refreshing custom mini-cart with ajax in Woocommerce

I am trying to build a simple interface in Woocommerce where a product gets added straight to the mini cart next to it with AJAX, rather than having the page refresh every time you add an item to the cart. Unfortunately I cannot get the AJAX to work and the page just keeps refreshing.
woocommerce.php - the default woocommerce page:
<?php
//LOOP THROUGH ALL PRODUCTS
$args = array( 'post_type' => 'product');
$loop = new WP_Query( $args );
echo "<ul class='mylisting'>";
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$id = $product->get_id();
$item_name = $product->get_name();
if( $product->is_type( 'variable' ) ){
$class = "variable-product";
} else {
$class = NULL;
}
//OUTPUT PRODUCTS
?>
<li>
<a class="menu-link <?php echo $class; ?>" data-product_id="<?php echo $id; ?>" href="/wpdev/shop/?add-to-cart=<?php echo $id; ?>"><?php echo $item_name." - ".$id; ?></a>
</li>
<?php if( $product->is_type( 'variable' ) ) : ?>
<div id="product-popup-<?php echo $id; ?>" class="product-popup">
<div class="popup-inner">
<?php woocommerce_variable_add_to_cart(); ?>
</div>
</div>
<?php endif; ?>
<?php
endwhile;
echo "</ul>";
wp_reset_query();
?>
<!-- DISPLAY MINI CART -->
<div id="mini-cart-container">
<?php woocommerce_mini_cart(); ?>
</div>
main.js - Main javascript file:
$('.menu-link').click(function(){
jQuery.ajax({
url : woocommerce_params.ajax_url,
type : 'post',
data : {
'action': 'ajax_update_mini_cart'
},
success : function( response ) {
$('#mini-cart-container').html(response);
}
});
});
functions.php
function ajax_update_mini_cart() {
echo wc_get_template( 'cart/mini-cart.php' );
die();
}
add_filter( 'wp_ajax_nopriv_ajax_update_mini_cart', 'ajax_update_mini_cart' );
add_filter( 'wp_ajax_ajax_update_mini_cart', 'ajax_update_mini_cart' );
The goal is to get the woocommerce_mini_cart() function to update with ajax. Is this possible?
I suspect the problem lies with the way I have coded the javascript ajax function, but I'm not sure. Any help would be greatly appreciated.
UPDATE: Moe's solution below has now been added, which has stopped the page reloading but the cart still doesn't update. Echoing some text inside the ajax_update_mini_cart() function does ajax that text inside the mini-cart-container div where the mini-cart should be, which proves (I think) that the javascript function and the php function is working. I think for some reason the problem comes when the echo wc_get_template( 'cart/mini-cart.php' ); is placed inside the function. Does anyone know why this is?
its following the href. try the following
$('.menu-link').click(function(e){
e.preventDefault();
jQuery.ajax({
url : woocommerce_params.ajax_url,
type : 'post',
data : {
'action': 'ajax_update_mini_cart'
},
success : function( response ) {
$('#mini-cart-container').html(response);
}
});
});

Can you remove wordpress post tags with js/php after certain date (ACF date time picker)?

So my website lists upcoming film screenings in my area.
I'm using the ACF date time picker to only show posts/film screenings that are in the future in the wordpress loop.
I have tags filtering the results dynamically using ajax (thanks to https://www.bobz.co/ajax-filter-posts-tag/) except there are tags that aren't relevant to the results because they belong to posts that are older than the current date (past screenings).
*For example on the website, the 'animated film festival' is still coming up with the other tags.
I don't know if it's possible to delete a posts tags with PHP (within the post template while it loops through other posts) - and to delete the posts tags if the ACF date time field for that post is older than the current date.
I haven't found much luck googling this and I am a bit of a noob so...
This is my site: http://pigcine.pamrosel.com/
This is what I'm doing in my functions.php file at the moment:
// Get all tags and display
function tags_filter() {
$tax = 'post_tag';
$terms = get_terms( $tax );
$count = count( $terms );
if ( $count > 0 ): ?>
<div class="post-tags">
<?php
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $tax );
echo '' . $term->name . ' ';
} ?>
</div>
<?php endif; }
// Script for getting posts
function ajax_filter_get_posts( $taxonomy ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce($_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
// WP Query
$args = array(
'tag' => $taxonomy,
'post_type' => 'post',
'posts_per_page' => -1,
'meta_key' => 'datetime',
'orderby' => array(
'datetime' => 'ASC'
),
);
// If taxonomy is not set, remove key from array and get all posts
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while($query->have_posts()) : $query>the_post();
$today = date('Y-m-d H:i:s', strtotime('+9 hours'));
$event_date = get_field('datetime');
if (strtotime($today) <= strtotime($event_date)) {
?>
<div class="sl">
<div class="sl_closed">
<div class="col-2-8"><div class="modulepad">
<p><?php the_field('datetime'); ?></p>
</div></div>
<div class="col-3-8"><div class="modulepad">
<p><?php the_title(); ?><br>
<?php $wpmovieinput = get_field('movie_title'); $movie = imdb_connector_get_movie($wpmovieinput); echo implode(", ", $movie["directors"]); ?>
</p>
</div></div>
<div class="col-3-8"><div class="modulepad">
<p><?php the_field('location_name'); ?><br>
<?php $wpmovieinput = get_field('movie_title'); $movie = imdb_connector_get_movie($wpmovieinput); echo implode(", ", $movie["countries"]) . " "; echo $movie["released"] . " "; echo implode(", ", $movie["runtime"]); ?>
</p>
</div></div>
</div><!--SL_CLOSED-->
<?php } endwhile; ?>
<?php else: ?>
<h2>No posts found</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');

Categories