点击wordpress帖子中某个链接的计数

Lea*_*der 5 php wordpress counter custom-fields

是否可以计算点击帖子中某个链接的次数?

(例如,让我们说某个链接有一个名为'bla'的ID)

<a id="bla" href="#">download</a>
Run Code Online (Sandbox Code Playgroud)

我觉得应该可以使用custom-fields/post-meta(保持计数),就像ever-so-popular"访客数"一样.不幸的是,我对PHPs 很无能为力.

Dan*_*jel 10

它可以通过ajax调用来完成,该调用在遵循链接之前更新post meta字段.下面的示例为未登录的用户注册ajax操作,并link_click_counter在每次单击时将自定义字段增加1.链接必须具有id属性countable_link.这是一个基本示例,仅适用于帖子中的一个链接.要将它用作插件,请创建文件wp-content/plugins/click-counter /click-counter.php并复制粘贴示例代码,或将代码functions.php放在主题文件夹中.首次点击链接时,系统link_click_counter会为该帖子创建新的自定义字段,您可以在其中跟踪链接的点击次数.

HTML:

<a id="countable_link" href="#">download</a>
Run Code Online (Sandbox Code Playgroud)

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
    }
}
?>
Run Code Online (Sandbox Code Playgroud)