So this goes in your themes functions.php file. This adds a metabox on the right side of your editscreen within posts called “Enable Post Views on this Post”:
// Hook into WordPress
add_action( 'admin_init', 'add_custom_metabox' );
add_action( 'save_post', 'wpse_16722_save_post_views_value' );
/**
* Add meta box
*/
function add_custom_metabox() {
add_meta_box( 'enable_post_views', __( 'Enable Post Views on this Post' ), 'wpse_16722_enable_post_views', 'post', 'side', 'low' );
}
/**
* Display the metabox
*/
function wpse_16722_enable_post_views() {
global $post;
$enable_views = get_post_meta( $post->ID, 'enable_views', true );
?>
<p>
<input type="checkbox" id="enable-views" name="enable_views" value="1" <?php checked( $enable_views, 1 ); ?> style="margin-right: 10px;">
<label for="enable-views"><?php _e('Enable Post Views on this Post', 'domain'); ?></label>
</p>
<?php
}
/**
* Process the custom metabox fields
*/
function wpse_16722_save_post_views_value( $post_id ) {
global $post;
if( isset( $_POST['enable_views'] ) ? $_POST['enable_views'] : '' ) {
update_post_meta( $post->ID, 'enable_views', $_POST['enable_views'] );
} else {
delete_post_meta( $post->ID, 'enable_views' );
}
}
/**
* Get and return the values for the URL and description
*/
function wpse_16722_get_post_views_box() {
global $post;
$enable_views = get_post_meta( $post->ID, 'enable_views', true );
return $enable_views;
}
It saves the value as metadata on your posts. The meta_key
is “enable_views” and you can see it in your database under yourprefix_postmeta
.
When you have the value saved on a post as true. You can simpley just check this on the post where you want the counter like this:
// Inside the loop add this
// Get the values from "enable_views"
// If true add the views counter
$is_enabled = get_post_meta( $post->ID, 'enable_views', true );
if( $is_enabled ) {
echo getPostViews( post->ID );
}
Update New 19.11
Only show views when options is “Yes” put this in your single.php
// Get the options
$options = get_option('to_post_views');
// Echo if options is Yes
if( $options == 'Yes' ) {
echo getPostViews( get_the_ID() );
}