it-swarm.com.de

Aktualisieren Sie das benutzerdefinierte Postfeld von Ajax auf der zwischengespeicherten Site

Meine Seite wird vom Plugin "wp-supper cache" und "cloudflare.com" zwischengespeichert

Also meine PHP Funktion um Post Views zu zählen funktioniert falsch.

Ich versuche, Ajax dafür zu verwenden, aber ich bin kein Neuling mit JS-Code, daher kann ich nicht wissen, wo es falsch ist.

In functions.php erstelle ich eine einfache Funktion:

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);
}

Code in ajax.js Datei:

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) {
    }
});

Die page.php in meinem Theme:

<div id="<?php the_ID(); ?>" <?php post_class('view_detail'); ?>>

Bitte sag mir, wie kann ich das machen? Vielen Dank!

1
Zen Nguyễn

Ich habe hier einige Fehler entdeckt:

jQuery.ajax({
     type: "POST",
     contentType: "application/json; charset=utf-8", // default: 'application/x-www-form-urlencoded; charset=UTF-8'. you can not set
     url: "http://localhost/wp-admin/admin-ajax.php", // if you have correctly enabled ajax in wp, you should use the object you set up with the url
     data: "{'action':'get_PostViews(" + idpost + ")'}", // you can use a PlainObject notation, so you don't need to double quoted. action property is the name of your function as you written in function.php
     success: function (result) {
       alert('Update Success!');
     }
});

Schauen Sie sich hier um jQuery.ajax () . Um Ajax in WordPress zu verwenden, gehen Sie folgendermaßen vor:

  1. aktivieren Sie die Ajax-Funktionalität
  2. deklarieren Sie Ihre Funktion in function.php
  3. verwenden Sie Javascript/JQuery, um Daten an den Server zu senden und die abgerufenen Daten abzuhören

Aktivieren von Ajax

Der beste Weg, dies zu erreichen, ist (meiner Meinung nach):

//File functions.php
    add_action('template_redirect', 'ajax_activation');
    function ajax_activation(){
       //optional 
       wp_enqueue_script( 
          'ajax_script', 
           get_template_directory_uri() . '/js/jquery.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
       ); 
    }

Funktion deklarieren

//File functions.php
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;
    // your code here
    wp_die(); // | die(); you need this to avoid trailing zero
}

jQuery/Javascript

$.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: // you can store it in html attribute for an easy access like: jQuery(element).attr('id');
    },
    success: function (result) {

    }
});

Ich vermute, Sie verwenden diese Funktion für alle Posts in einer Schleife. Sie können Ajax einmal aufrufen, um die Arbeit für alle Posts zu erledigen. Zum Beispiel möchte ich mit Ajax die Titel meiner Beiträge abrufen:

HTML

<html>
<!-- some stuff here -->
<h3 id="<?php echo get_the_ID(); ?>" class="spyhole"></h3> <!-- there are many of this :  ) -->
<!-- some stuff here -->
</html>

jQuery

ids = [];
items = $('.spyhole');
$.each( items, function( i, v){
    ids.Push( $(v).attr( 'id' ) ); // each value is added to array
});
$.ajax({
    type: "POST",
    url: ajax_object.ajaxurl,
    data: {
      action: 'getMyTitleAjax',
      id: ids
    },
    success: function (result) {
      data = $.parseJSON( result ); // Takes a well-formed JSON string and returns the resulting JavaScript object.
      $.each( data, function( i, v ){
        $('.spyhole[id="' + i + '"]').html( v ); // print the title
      });
    }
});

PHP

// Enabling ajax - functions.php
add_action('template_redirect', 'ajax_activation');
function ajax_activation(){
   //optional 
   wp_enqueue_script( 
      'ajax_script', 
       get_template_directory_uri() . '/js/jquery.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
   ); 
}

// Declare my function
add_action('wp_ajax_getMyTitleAjax', 'getMyTitleAjax', 3);
add_action('wp_ajax_nopriv_getMyTitleAjax', 'getMyTitleAjax', 3);
function getMyTitleAjax() {
    $ids = isset( $_POST['id'] ) ? $_POST['id'] : false; // check if there is something in global $_POST
    if( $ids && is_array( $ids ) ){
      foreach( $ids as $id ){
        $titles[$id] = get_the_title( $id ); 
      }
    }
    echo json_encode( $titles ); // prints the result
    wp_die(); // avoid trailing zero
}

Hoffe, es hilft, wenn etwas nicht klar ist, zögern Sie nicht zu fragen

Update

Ändern Sie dies entsprechend Ihrer Fragenaktualisierungen:

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);
}

mit diesem:

function get_PostViews() {
$id = isset( $_POST['id'] ) ? $_POST['id'] : false;
$count_key = 'post_views_count'; 
$count = get_post_meta($id, $count_key, true);
if( empty($count) ){ $count = 1; } else { $count++; }
update_post_meta($id, $count_key, $count);
}
2
iEmanuele

single.php

// ------------Post  views----------          
<script type="text/javascript">
    // get post views
    (function($) {
        function mostViews() {
             $.getJSON("<?php bloginfo('template_directory'); ?>/ajax.php",
                    {
                        action: 'get_mostViewedPost',
                        postid: <?php echo get_the_ID() ?>
                    }, function (data) {
                    })
        }
        var mostViews = new mostViews();
    })(jQuery);

</script>

functions.php

// ------------Post  views----------
// function to display number of posts.
function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}

// function to count views.
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

// Add it to a column in WP-Admin
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
    $defaults['post_views'] = __('Views');
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
    if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

function postViews_callback(){
    setPostViews($_GET['postid']) ;
    echo "Success, Post id: ".$_GET['postid'];
    die();
}
add_action('ajax_get_mostViewedPost', 'postViews_callback');
add_action('ajax_nopriv_get_mostViewedPost', 'postViews_callback');

// -----------end Post views----------

ajax.php

<?php
//mimic the actuall admin-ajax
define('DOING_AJAX', true);

//make sure you update this line
//to the relative location of the wp-load.php

require_once(dirname(dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME'])))) . '/wp-load.php');
//Typical headers
header('Content-Type: text/html');
send_nosniff_header();

//Disable caching
header('Cache-Control: no-cache');
header('Pragma: no-cache');

$action = esc_attr(trim($_GET['action']));


//A bit of security
$allowed_actions = array( 
    'get_mostViewedPost'
);

//For logged in users 
add_action('ajax_get_mostViewedPost', 'postViews_callback');
//For guests 
add_action('ajax_nopriv_get_mostViewedPost', 'postViews_callback');

if(in_array($action, $allowed_actions)) {
    if(is_user_logged_in())
        do_action('ajax_'.$action);
    else
        do_action('ajax_nopriv_'.$action);
} else {
    die('-1');
}
0
ji_feraou
single.php //post views -=================================================================================<br> <br> 




<script type="text/javascript"> <br> 
    // get post views <br> 
    (function($) { <br> 
        function mostViews() { <br> 
             $.getJSON("<?php bloginfo('template_directory'); ?>/ajax.php", <br> 
                    { <br> 
                        action: 'get_mostViewedPost', <br> 
                        postid: <?php echo get_the_ID() ?> <br> 
                    }, function (data) { <br> 
                    }) <br> 
        } <br> 
        var mostViews = new mostViews(); <br> 
    })(jQuery); <br> 
 <br> 
</script> <br> 





functions.php  <br> -=================================================================================   <br> 
// ------------Post  views---------- <br> 
// function to display number of posts. <br> 
function getPostViews($postID){ <br> 
    $count_key = 'post_views_count'; <br> 
    $count = get_post_meta($postID, $count_key, true); <br> 
    if($count==''){ <br> 
        delete_post_meta($postID, $count_key); <br> 
        add_post_meta($postID, $count_key, '0'); <br> 
        return "0 View"; <br> 
    } <br> 
    return $count.' Views'; <br> 
} <br> 
 <br> 
// function to count views. <br> 
function setPostViews($postID) { <br> 
    $count_key = 'post_views_count'; <br> 
    $count = get_post_meta($postID, $count_key, true); <br> 
    if($count==''){ <br> 
        $count = 0; <br> 
        delete_post_meta($postID, $count_key); <br> 
        add_post_meta($postID, $count_key, '0'); <br> 
    }else{ <br> 
        $count++; <br> 
        update_post_meta($postID, $count_key, $count); <br> 
    } <br> 
} <br> 
 <br> 
// Add it to a column in WP-Admin <br> 
add_filter('manage_posts_columns', 'posts_column_views'); <br> 
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2); <br> 
function posts_column_views($defaults){ <br> 
    $defaults['post_views'] = __('Views'); <br> 
    return $defaults; <br> 
} <br> 
function posts_custom_column_views($column_name, $id){ <br>  <br> 
    if($column_name === 'post_views'){ <br> 
        echo getPostViews(get_the_ID()); <br> 
    } <br> 
} <br> 
 <br> 
function postViews_callback(){ <br> 
    setPostViews($_GET['postid']) ; <br> 
    echo "Success, Post id: ".$_GET['postid']; <br> 
    die(); <br> 
} <br> 
add_action('ajax_get_mostViewedPost', 'postViews_callback'); <br> 
add_action('ajax_nopriv_get_mostViewedPost', 'postViews_callback'); <br> 
 <br> 
// -----------end Post views---------- <br> 


ajax.php  <br> -=================================================================================  <br> 
<?php <br> 
//mimic the actuall admin-ajax <br> 
define('DOING_AJAX', true); <br> 
 <br> 


//make sure you update this line <br> 
//to the relative location of the wp-load.php <br> 
 <br> 
require_once(dirname(dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME'])))) . '/wp-load.php');
//Typical headers <br> 
header('Content-Type: text/html'); <br> 
send_nosniff_header(); <br> 
 <br> 
//Disable caching <br> 
header('Cache-Control: no-cache'); <br> 
header('Pragma: no-cache'); <br> 
 <br> 
$action = esc_attr(trim($_GET['action'])); <br> 
 <br> 

//A bit of security <br> 
$allowed_actions = array(  <br> 
    'get_mostViewedPost'
); <br> 

//For logged in users  <br> 
add_action('ajax_get_mostViewedPost', 'postViews_callback'); <br> 
//For guests 
add_action('ajax_nopriv_get_mostViewedPost', 'postViews_callback');
 <br> 
if(in_array($action, $allowed_actions)) { <br> 
    if(is_user_logged_in()) <br> 
        do_action('ajax_'.$action); <br> 
    else <br> 
        do_action('ajax_nopriv_'.$action); <br> 
} else { <br> 
    die('-1'); <br> 
} <br> 
0
ji_feraou