Aggiorna il campo Post personalizzato di AJAX sul sito memorizzata nella cache
-
05-11-2019 - |
Domanda
Il mio sito memorizzata nella cache del plug-in "WP-Super Cache" e "Cloudflare.com"
Quindi la mia funzione PHP per contare le visualizzazioni dei post funzionano in modo errato.
Cerco di usare Ajax per questo, ma sono noob con il codice JS, quindi non posso sapere dove è sbagliato.
In funzioni.php Creo una funzione semplice:
add_action('template_redirect', 'ajax_activation');
function ajax_activation(){
//optional
wp_enqueue_script(
'ajax_script',
get_template_directory_uri() . '/js/ajax.js', // path to your js file for ajax operations
array( 'jquery' ), false
);
//end optional
wp_localize_script(
'ajax_script', // the name of your global.js registered file
'ajax_object', // name
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) // you can add other items for example for using a translated string in javascript/jquery context
);
}
add_action('wp_ajax_get_PostViews', 'get_PostViews');
add_action('wp_ajax_nopriv_get_PostViews', 'get_PostViews');
function get_PostViews() {
$id = isset( $_POST['id'] ) ? $_POST['id'] : false;
$count_key = 'post_views_count';
$count = get_post_meta($post_ID, $count_key, true);
if( empty($count) ){ $count = 1; } else { $count++; }
update_post_meta($post_ID, $count_key, $count);
}
Codice in ajax.js file:
var postID = $(".view_detail").attr("id");
jQuery.ajax({
type: "POST",
url: ajax_object.ajaxurl, // this is the object you defined in function.php
data: {
action: 'get_PostViews', // the name of your function
id: postID // you can store it in html attribute for an easy access like: jQuery(element).attr('id');
},
success: function (result) {
}
});
Il Page.php Nel mio tema:
<div id="<?php the_ID(); ?>" <?php post_class('view_detail'); ?>>
Per favore dimmi come posso farlo funzionare? Grazie mille!
Nessuna soluzione corretta
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange