So i'm trying to make a follow button in wp, and for some reason the ajax button isn't working right.
Here are the steps of what's supposed to happen
user clicks #followbtn
Ajax goes to $_POST action that = follow
php runs wp_set_object_terms( $user_id, $author_id, 'follow', true );
when that's done the function echo's "ok"
if the data = ok reload the page
For some reason the php isn't executing and the page isn't being reloaded.
add_action( 'wp_ajax_nopriv_jk-author-follow', 'jk_author_follow' );
add_action( 'wp_ajax_jk-author-follow', 'jk_author_follow' );
function jk_author_follow() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Nope!' );
if($_POST['action'] == "follow") {
$author_id = get_the_author_meta( 'nickname' ); // get authors name
$termId = get_term_by( 'slug', $author_id, 'follow' ); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term( $termId, 'follow' ); // count followers in author term
$author_follow_count = count( $followers );
if ( is_user_logged_in() ) { // user is logged in
$user_id = get_current_user_id(); // current user
wp_set_object_terms( $user_id, $author_id, 'follow', true ); // Follow the author
echo "ok";
}
}
}
exit;
}
Front end button
function getAuthorFollowLink( $author_id ) {
$author = get_the_author_meta( 'nickname' );
$user_ID = get_current_user_id();
$termId = get_term_by( 'slug', $author, 'follow' ); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term( $termId, 'follow' ); // count followers in author term
$count = count( $followers );
$output = 'Folllow '.$count.'';
return $output;
}
js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: ajax_var.url,
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
location.reload();
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
});
Try disabling this code
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Nope!' );
If You know the implications. You might want to learn more https://codex.wordpress.org/Function_Reference/wp_verify_nonce
Related
I am using a click counter on my woocommerce product page where the counter adds the number of clicks on a specific button.
The counter works fine and counts the clicks perfectly but I want to add random pre-defined values from given range so each product has unique pre-defined values on counter which is incremented when the button is pressed.
Here are my codes:
Front end (added in through hooks PHP File):
//button that is used to count clicks
<div id="link_count">
<button id="printImage" class="single_add_to_cart_button button alt">Print this Image</button>
</div>
//output count
global $post;
print get_post_meta($post->ID,'link_check_click_counter',true);
// update counter in post database
function update_counter_ajax() {
$postID = trim($_POST['post_id']);
$count_key = 'download';
$counter = get_post_meta($postID, $count_key, true);
if($counter==''){
$count = 1;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '1');
}else{
$counter++;
update_post_meta($postID, $count_key, $counter);
}
wp_die();
}
add_action('wp_ajax_update_counter', 'update_counter_ajax');
add_action('wp_ajax_nopriv_update_counter', 'update_counter_ajax');
Functions.php:
//counter code start
add_action( 'wp_ajax_link_check_click_counter', 'link_check_click_counter');
add_action( 'wp_ajax_nopriv_link_check_click_counter', 'link_check_click_counter' );
function link_check_click_counter() {
if ( isset( $_POST['nonce'] ) && isset( $_POST['post_id'] ) && wp_verify_nonce( $_POST['nonce'], 'link_check_click_counter_' . $_POST['post_id'] ) ) {
$count = get_post_meta( $_POST['post_id'], 'link_check_click_counter', true );
update_post_meta( $_POST['post_id'], 'link_check_click_counter', ( $count === '' ? 1 : $count + 1 ) );
}
exit();
}
add_action( 'wp_footer', 'link_click' );
//add_action( 'wp_head', 'link_click' );
function link_click() {
global $post;
if( isset( $post->ID ) ) {
?>
<script type="text/javascript" >
jQuery(function ($) {
var ajax_options = {
action: 'link_check_click_counter',
nonce: '<?php echo wp_create_nonce( 'link_check_click_counter_' . $post->ID ); ?>',
ajaxurl: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
post_id: '<?php echo $post->ID; ?>'
};
$( '#link_count a' ).on( 'click', function() {
var href = $( this ).attr( "href" );
var redirectWindow = window.open(href, '_blank');
$.post( ajax_options.ajaxurl, ajax_options, function() {
redirectWindow.location;
});
return false;
});
});
</script>
<?php
}
}
function link_check_meta_values( $key = '', $type = 'post', $status = 'publish' ) {
global $wpdb;
if( empty( $key ) )
return;
$r = $wpdb->get_col( $wpdb->prepare( "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status,
$type ) );
return $r;
}
//counter code end
The code works fine and counts each click on button but, I simply want to add specific pre-defined values which are showed on random bases on each product.
E.g. the pre-defined range is: 5000 - 20000
For example:
Second product counter value would be 5523.
Third product counter value would be 15789
one button on product a should have:
The value should add one if the corresponding button is pressed once
I am still learning PHP and WordPress so any help would be appreciated.
In the update_counter_ajax() function, when you define a default value for your counter if it's empty, you could generate a random number of your choice instead of setting to "1"!
$counter = get_post_meta($postID, $count_key, true);
if(empty($counter)){
$counter = rand(5000, 20000);
// OR you could use the other php random function
// $count = mt_rand(5000, 20000);
add_post_meta($postID, $count_key, $counter);
I am trying to improve the speed of my infinite scroll code. Here is my ajax requet handling script
function ga_infinite_scroll() {//trigger this on infinite scroll
add_filter( 'woocommerce_get_price_html', 'ga_show_price' );//filter to fix price range
if(empty($_POST['search_term'] )){
$params = json_decode( stripslashes( $_POST['query'] ), true );
$params['post_status'] = 'publish';
$params['posts_per_page'] = get_option('posts_per_page');
$params['post_type'] = 'product';
$params['paged'] = $_POST['page'] + 1; // we need next page to be loaded
}
else{//search logic here
$search_query = json_decode( stripslashes( $_POST['search_posts'] ), true );
$search_query['post_status'] = 'publish';
$search_query['posts_per_page'] = get_option('posts_per_page');
$search_query['paged'] = $_POST['page'] + 1;
wc_set_loop_prop( 'total', $_POST['search_count'] );
$params = $search_query;
}
ob_start();
query_posts( $params);
if ( have_posts() ) {//product loop
if ( wc_get_loop_prop( 'total' ) ) {
while ( have_posts() ) {
the_post();
wc_get_template_part( 'content', 'product' );
}
}
}
$data = ob_get_clean();
die($data);
exit;
}
add_action( 'wp_ajax_ga_infinite_scroll', 'ga_infinite_scroll' );
add_action( 'wp_ajax_nopriv_ga_infinite_scroll', 'ga_infinite_scroll' );
Here is my javascript:-
jQuery(document).ready( function($) {
var url = window.location.origin + '/wp-admin/admin-ajax.php',
canBeLoaded=true,
bottomOffset = 2000; // the distance (in px) from the page bottom when you want to load more posts
$(window).scroll(function(){
var data = {
'action': 'ga_infinite_scroll',
'query': my_ajax_object.posts,
'page' : my_ajax_object.current_page,
//'search_results' : my_ajax_object.ga_search_results,
'search_count' : my_ajax_object.ga_search_count,
'search_posts': my_ajax_object.ga_search_posts,
'search_term' : my_ajax_object.ga_search_term,
'user_currency': my_ajax_object.user_currency,
'reg_price_slug': my_ajax_object.reg_price_field_slug
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({//limit the ajax calls
url : url,
data:data,
type:'POST',
beforeSend: function( xhr ){
// you can also add your own preloader here
// you see, the AJAX call is in process, we shouldn't run it again until complete
//console.log(data.search_term);
$('#ajax-loader').show();
canBeLoaded = false;
},
success:function(data){
if( data ) {
$('#multiple-products .columns-3 .products ').find('li:last-of-type').after( data ); // where to insert posts
//console.log(url);
canBeLoaded = true; // the ajax is completed, now we can run it again
my_ajax_object.current_page++;
$('#ajax-loader').hide();
}
else{
$('#ajax-loader').html('End of products...').delay(1000).fadeOut();
return;
}
}
});
}
});
//setting if it's a search
});
I'm wondering if it's a good idea to use query_posts and I have this filter that costly in terms of speed but if I don't use it, I end up seeing a price range like this $15-$25 like that.Any idea about how to handle this situation and to see the code of ga_show_price and my enqueued script, I've added it here Improving the speed of a custom infinite scroll and also any suggestions on improving my javascript?Thanks
You can get related products using the following:
$array = wc_get_related_products( $product_id, $limit, $exclude_ids );
Before asking question on SO, I searched a lot about what I needed to make a ajax request with WordPress. All my code and the request is working, but is not doing what I need it to do.
What I need to do is When I click at the buttom on checkout page "Novo Dependente", the information with the values to calculate total must update. "Total" value must be updated with a value which I defined at product post type page on admin panel. This value I already get, but the updating the value is real problem to me.
This is the page that I working.
This is the form, that shows up when i click the button, when i Toogle the checkbox I need to add the second value to the Total, another request with ajax.
And here my code goes
Obs: it's a plugin.
Here is the php code.
public function add_total_value()
{
if (! $_POST['action'] || $_POST['action'] !== 'add_total_value' ) :
echo json_encode(
array(
'status' => 'failed',
'message' => 'erro'
)
);
wp_die();
endif;
$woocommerce;
$quantidadeDependentes = $_POST['quantiaDependentes'];
//$produto_valor = WC()->cart->total;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )
{
$product = $cart_item['data'];
$item_id = $cart_item['product_id'];
$endereco_igual = get_post_meta( $item_id, 'adicional_mesmo', true);
$endereco_igual = str_replace(',', '.', $endereco_igual);
$endereco_igual = floatval( filter_var( $endereco_igual, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ) );
$produtoValor = floatval( get_post_meta( $item_id, '_regular_price', true) );
$valorTotal = $produtoValor + ( $endereco_igual * $quantidadeDependentes );
WC()->cart->total = $valorTotal;
WC()->cart->calculate_totals();
wc_price($valorTotal);
}
echo json_encode(
array(
'status' => 'success',
'valorTotal' => wc_price($valorTotal)
));
wp_die();
}
My Ajax request
function contagemDependentes()
{
$contagem = jQuery('.woocommerce-dependentes-contagem');
var quantiaDependentes = jQuery('.woocommerce-dependentes-card').length;
if ( quantiaDependentes <= 0 ) {
var mensagemNumeroDependentes = 'Nenhum dependente informado';
} else if ( quantiaDependentes === 1 ) {
var mensagemNumeroDependentes = '1 dependente';
} else {
var mensagemNumeroDependentes = quantiaDependentes+' dependentes';
}
jQuery($contagem).html(mensagemNumeroDependentes);
var quantiaDependentes = jQuery('.woocommerce-dependentes-card').length + 1;
var dados = {
action: 'add_total_value',
quantiaDependentes: quantiaDependentes
};
jQuery.ajax({
type: 'POST',
url: custom_values.ajaxurl,
data: dados,
dataType: 'json',
success: function(response)
{
console.log(response);
if (response.status === 'success')
{
console.log(response.status);
console.log(response.valorTotal);
var html = "<tr class='order-total'>";
html += "<th>Total</th>";
html += "<td>";
html += response.valorTotal;
html += "</td>";
html += "</tr>";
jQuery( '.order-total' ).remove();
jQuery( 'tfoot' ).append( html );
jQuery( 'body' ).trigger( 'update_checkout' );
}
}
});
}
before function() in functions.php always must be such code
add_action('wp_ajax_your_function_name', 'your_function_name');
add_action('wp_ajax_nopriv_your_function_name', 'your_function_name');
I'm using wordpress. Im working on Don't submit post if post title exists with the same TAG how can i achieve that ?
The code Below is only checking the post title and its already working if it has the same post title it will echo This post is already posted would u like to post a another one How can i achieve checking the post title with the post tag ? if the post title is existed and its using the post tag it will echo this again This post is already posted would u like to post a another one
<?php
//jQuery to send AJAX request
function duplicate_titles_enqueue_scripts( $hook ) {
if( !in_array( $hook, array( 'post.php', 'post-new.php' , 'edit.php'))) return;
wp_enqueue_script('duptitles',
wp_enqueue_script('duptitles',plugins_url().'/duplicate-title-validate/js/duptitles.js',
array( 'jquery' )), array( 'jquery' ) );
}
add_action( 'admin_enqueue_scripts', 'duplicate_titles_enqueue_scripts', 2000 );
add_action('wp_ajax_title_checks', 'duplicate_title_checks_callback');
/// callback ajax
function duplicate_title_checks_callback() {
function title_checks() {
global $wpdb;
$title = $_POST['post_title'];
$post_id = $_POST['post_id'];
$titles = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post'
AND post_title = '{$title}' AND ID != {$post_id} ";
$results = $wpdb->get_results($titles);
if($results) {
return "<span style='color:red'>". _e( 'Duplicate title detected, please change the title.' , 'dublicate-title-validate' ) ." </span>";
} else {
return '<span style="color:green">'._e('This title is unique.' , 'dublicate-title-validate').'</span>';
}
}
echo title_checks();
die();
}
// this chek backend title and if Duplicate update status draft .
function duplicate_titles_wallfa_bc( $post )
{
global $wpdb ;
$title = $_POST['post_title'] ;
$post_id = $post ;
$wtitles = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post'
AND post_title = '{$title}' AND ID != {$post_id} " ;
$wresults = $wpdb->get_results( $wtitles ) ;
if ( $wresults )
{
$wpdb->update( $wpdb->posts, array( 'post_status' =>
'draft' ), array( 'ID' => $post ) ) ;
$arr_params = array( 'message' => '10', 'wallfaerror' => '1' ) ;
$location = add_query_arg( $arr_params , get_edit_post_link( $post , 'url' ) ) ;
wp_redirect( $location ) ;
exit ;
}
}
add_action( 'publish_post',
'duplicate_titles_wallfa_bc' ) ;
/// handel error for back end
function not_published_error_notice() {
if(isset($_GET['wallfaerror']) == 1 ){
?>
<div class="updated">
<p style='color:red' ><?php _e(' This post is already posted would u like to post a another one. ' , 'dublicate-title-validate') ?></p>
</div>
<?php
}
}
add_action( 'admin_notices', 'not_published_error_notice' );
function duplicate_titles_wallfa_action_init()
{
// Localization
load_plugin_textdomain('dublicate-title-validate',false,dirname(plugin_basename(__FILE__)).'/langs/');
}
// Add actions
add_action('init', 'duplicate_titles_wallfa_action_init');
function disable_autosave()
{
wp_deregister_script( 'autosave' ) ;
}
add_action( 'wp_print_scripts', 'disable_autosave' ) ;
?>
AJAX
jQuery(document).ready(function($){
function checkTitleAjax(title, id,post_type) {
var data = {
action: 'title_checks',
post_title: title,
post_type: post_type,
post_id: id
};
$.post(ajaxurl, data, function(response) {
$('#message').remove();
$('#poststuff').prepend('<div id=\"message\" class=\"updated below-h2 fade \"><p>'+response+'</p></div>');
});
};
$('#title').change(function() {
var title = $('#title').val();
var id = $('#post_ID').val();
var post_type = $('#post_type').val();
checkTitleAjax(title, id,post_type);
});
});
This is the Explanation
Example
Post Name - Post Tag - Result
post 1 - post1 - allowed
post 2 - post1 - allowed
post 1 - post1 - This post is already posted would u like to post a another one. (because it has the same value of the first post )
I am using the following ajax to update information on a page and then resubmit the page into the database. The script is failing each time stopping at the Error parameter. Can anyone see where I have gone wrong.
AJAX -
function bookingdetails() {
var date = <?php the_time('Y-m-d');?>;
var airport = $('#FLTairport').val();
var number = $('#FLTnumber').val();
var time = $('#FLTtime').val();
var dataString = 'date=' + date + '&airport=' + airport + '&number=' + number + '&time=' + time;
$.ajax({
type: 'POST',
url: '<?php echo $thisposturl;?>?update',
data: dataString,
beforeSend: function() {
$('#airloader').html('<img id="BKloader" src="http://www.divethegap.com/update/z-images/structure/icons/blockloader.gif" alt="" width="40" height="30"/>');
},
error: function() {
$('#airloader').html('Failed to update booking, try again');
},
dataType:'json',
success: function(data) {
$('#date').val(data.date);
$('#FLTnumber').val(data.FLTnumber);
$('#airloader').val(data.FLTnumber);
$('#FLTairport').val(data.FLTairport);
$('#FLTdate').val(data.FLTdate);
$('#FLTtime').val(data.FLTtime);
}
});
}
PHP -
<?php
function __update_post_meta( $post_id, $field_name, $value = '' )
{
if ( empty( $value ) OR ! $value )
{
delete_post_meta( $post_id, $field_name );
}
elseif ( ! get_post_meta( $post_id, $field_name ) )
{
add_post_meta( $post_id, $field_name, $value );
}
else
{
update_post_meta( $post_id, $field_name, $value );
}
}
if ( is_user_logged_in() ) {
$my_post = array(
'ID' => get_the_ID(),
'post_date' => $_POST['date'],
);
$the_post_id = wp_update_post( $my_post );
__update_post_meta( $the_post_id, 'FLTairport', $_POST['airport'] );
__update_post_meta( $the_post_id, 'FLTnumber', $_POST['number'] );
__update_post_meta( $the_post_id, 'FLTtime', $_POST['time'] );
}
$FLTdate = get_the_time('d/m/Y');
$date = get_the_time('Y-m-d');
$FLTairport = $_POST['airport'];
$FLTnumber = $_POST['number'];
$FLTtime = $_POST['time'];
echo json_encode( array('FLTdate'=>$FLTdate, 'date'=>$date, 'FLTairport'=>$FLTairport, 'FLTnumber'=>$FLTnumber, 'FLTtime'=>$FLTtime));
?>
Any ideas?
Marvellous
The jQuery Documentation shows 3 arguments that can be used in your error callback, which could be very useful in debugging your error.
From the docs
so with that in mind, try changing your error callback like so...
error: function(xhr,ts,et) {
$('#airloader').html('Failed to update booking.');
$('#airloader').append('Error Text - '+ts);
},
and you should see the specific error, which should put you down the right path to fix it.
Are you able to see what your php script is sending? I would recommend using firebug in firefox to see exactly what is coming back to be consumed by your javascript. I don't see where it is outputting a success parameter for your json.