Forum Replies Created

Viewing 1 replies (of 1 total)
  • Thread Starter DaHermitLife

    (@dahermitlife)

    I was finally able to fix the problem, so will share my updated working code for anyone who may find it useful.

    “link-out” is added to any post’s link where counting outgoing clicks is needed. For example:

    <a href="<?php echo $link; ?>" link-out="<?php echo $post->ID ?>">

    It could be added to any link on the site, but for my purposes I’m counting links associated with a post ID. jQuery grabs the postID contained in “link-out” and sends it to the php file for database update when clicked.

    Code inside .js file:

    jQuery(document).ready(function($) {
    
    	$("a[link-out]").click(function() {
        	var linkout = $(this).attr("link-out");
        	var data = {
    			action: 'my_action',
    			postid: linkout
          	};
        	$.post(MyAjax.ajaxurl, data);
      	});
    
    });

    Code in plugin file .php:

    // embed the javascript file that makes the AJAX request
    wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/countclicks.js', array( 'jquery' ) );
    // declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
    wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    
    add_action('wp_ajax_my_action', 'my_action_callback');
    add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
    
    function my_action_callback() {
    	global $wpdb;
    	$post_id = $_POST['postid'];
    	$post_id = mysql_real_escape_string($post_id);
    	$wpdb->query("UPDATE wp_postmeta SET meta_value = meta_value+1 WHERE post_id = '$post_id' AND meta_key = 'clicks_out'");
    }
Viewing 1 replies (of 1 total)