click count of a certain link in wordpress post

前端 未结 2 1280
故里飘歌
故里飘歌 2021-02-06 13:51

Is it possible to count how many times a certain link in post has been clicked?

(for example purpose, let\'s say that the certain link has an ID named \'bla\')



        
相关标签:
2条回答
  • 2021-02-06 14:01

    It could be done with ajax call that updates post meta field before the link is followed. Example below registers ajax action for users that are not logged in, and increases link_click_counter custom field by 1 on each click. Link must have id attribute countable_link. This is a basic example that works for only one link in post. To use it as a plugin create file like wp-content/plugins/click-counter /click-counter.php and copy-paste example code, or put the code in functions.php inside theme folder. First time the link is clicked, new custom field link_click_counter will be created for that post, and there you can track how many clicks link has.

    HTML:

    <a id="countable_link" href="#">download</a>
    

    PHP:

    <?php
    /*
    Plugin Name: Link Clicks Counter
    */
    
    if ( is_admin() ) add_action( 'wp_ajax_nopriv_link_click_counter', 'link_click_counter' );
    function link_click_counter() {
    
        if ( isset( $_POST['nonce'] ) &&  isset( $_POST['post_id'] ) && wp_verify_nonce( $_POST['nonce'], 'link_click_counter_' . $_POST['post_id'] ) ) {
            $count = get_post_meta( $_POST['post_id'], 'link_click_counter', true );
            update_post_meta( $_POST['post_id'], 'link_click_counter', ( $count === '' ? 1 : $count + 1 ) );
        }
        exit();
    }
    
    
    add_action( 'wp_head', 'link_click_head' );
    function link_click_head() {
        global $post;
    
        if( isset( $post->ID ) ) {
    ?>
        <script type="text/javascript" >
        jQuery(function ($) {
            var ajax_options = {
                action: 'link_click_counter',
                nonce: '<?php echo wp_create_nonce( 'link_click_counter_' . $post->ID ); ?>',
                ajaxurl: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
                post_id: '<?php echo $post->ID; ?>'
            };
    
            $( '#countable_link' ).on( 'click', function() {
                var self = $( this );
                $.post( ajax_options.ajaxurl, ajax_options, function() {
                    window.location.href = self.attr( "href" );
                });
                return false;
            });
        });
        </script>
    <?php
        }
    }
    ?>
    
    0 讨论(0)
  • 2021-02-06 14:19

    One possible way is to redirect all through a common PHP gateway and from there, redirect to the original page you wanted to redirect using Header('Location: yourpage.html'); In the gateway PHP page count the number by incrementing a saved value by 1.

    0 讨论(0)
提交回复
热议问题