Skip to content

Instantly share code, notes, and snippets.

@elhardoum
Last active May 23, 2017 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elhardoum/9acbc09108a172dc0379 to your computer and use it in GitHub Desktop.
Save elhardoum/9acbc09108a172dc0379 to your computer and use it in GitHub Desktop.
<?php
function whatismyip() {
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = null;
return $ipaddress;
}
add_action('wp', function() {
if( is_single() ) {
global $post;
$user_ip = whatismyip();
$meta = get_post_meta( $post->ID, '_se_post_views', TRUE );
$meta = '' !== $meta ? explode( ',', $meta ) : array();
$meta = array_filter( array_unique( $meta ) );
if( ! in_array( $user_ip, $meta ) ) {
array_push( $meta, $user_ip );
update_post_meta( $post->ID, '_se_post_views', implode(',', $meta) );
}
}
});
add_shortcode('se-post-views-count', function( $atts ) {
$a = shortcode_atts( array(
'post_id' => 0
), $atts );
$post_id = esc_attr( "{$a['post_id']}" );
if( 0 == $post_id && is_single() )
$post_id = get_the_ID();
if( ! get_post( $post_id ) || ( get_post( $post_id ) && 'post' !== get_post( $post_id )->post_type ) )
return;
$meta = get_post_meta( $post_id, '_se_post_views', TRUE );
$meta = '' !== $meta ? explode( ',', $meta ) : array();
return (int) count( $meta );
});
add_filter('the_content', function( $content ) {
if( is_single() ) :;
global $post;
$meta = get_post_meta( $post->ID, '_se_post_views', TRUE );
$meta = '' !== $meta ? explode( ',', $meta ) : array();
$count = count( $meta );
$message = "This post was viewed " . do_shortcode('[se-post-views-count]') . " time";
$message .= (int) $count !== 1 ? 's' : '';
$content .= $message;
endif;
return $content;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment