mmm

Developer
2 Min Read

<?php
if (!defined(‘ABSPATH’)) exit;

/* Admin settings page */
add_action(‘admin_menu’, function () {
add_options_page(
‘Fake Post Views’,
‘Fake Post Views’,
‘manage_options’,
‘fake-post-views-settings’,
‘cnt_fake_post_views_settings_page’
);
});

add_action(‘admin_init’, function () {
register_setting(‘cnt_fake_post_views_group’, ‘cnt_default_fake_post_views’, [
‘type’ => ‘string’,
‘sanitize_callback’ => function ($value) {
$value = trim($value);
return ($value === ”) ? ” : absint($value);
},
‘default’ => ”,
]);
});

function cnt_fake_post_views_settings_page() {
?>

Fake Post Views Settings

Default Fake ViewsLeave empty if you do not want default fake views on publish.

<?php
}

/* Meta box for posts */
add_action(‘add_meta_boxes’, function () {
add_meta_box(
‘cnt_fake_post_views_meta’,
‘Fake Post Views’,
‘cnt_fake_post_views_meta_callback’,
‘post’,
‘side’,
‘default’
);
});

function cnt_fake_post_views_meta_callback($post) {
wp_nonce_field(‘cnt_save_fake_post_views’, ‘cnt_fake_post_views_nonce’);
$value = get_post_meta($post->ID, ‘_cnt_fake_post_views’, true);
?>

Post Fake Views

Leave empty to show no fake views.
<?php
}

/* Save post meta */
add_action(‘save_post’, function ($post_id) {
if (defined(‘DOING_AUTOSAVE’) && DOING_AUTOSAVE) return;
if (!isset($_POST[‘cnt_fake_post_views_nonce’]) || !wp_verify_nonce($_POST[‘cnt_fake_post_views_nonce’], ‘cnt_save_fake_post_views’)) return;
if (!current_user_can(‘edit_post’, $post_id)) return;
if (get_post_type($post_id) !== ‘post’) return;

if (isset($_POST['cnt_fake_post_views_field']) && trim($_POST['cnt_fake_post_views_field']) !== '') {
    update_post_meta($post_id, '_cnt_fake_post_views', absint($_POST['cnt_fake_post_views_field']));
} else {
    delete_post_meta($post_id, '_cnt_fake_post_views');
}

});

/* Only set default on first publish if admin entered a value */
add_action(‘save_post_post’, function ($post_id, $post, $update) {
if (wp_is_post_revision($post_id)) return;
if ($post->post_status !== ‘publish’) return;

$existing = get_post_meta($post_id, '_cnt_fake_post_views', true);
$default  = get_option('cnt_default_fake_post_views', '');

if (($existing === '' || $existing === null) && $default !== '') {
    update_post_meta($post_id, '_cnt_fake_post_views', absint($default));
}

}, 20, 3);

/* Get fake views */
function cnt_get_fake_post_views($post_id = null) {
$post_id = $post_id ? $post_id : get_the_ID();
$custom = get_post_meta($post_id, ‘_cnt_fake_post_views’, true);

if ($custom === '' || $custom === null) {
    return '';
}

return absint($custom);

}

/* Shortcode: */
add_shortcode(‘fake_post_views’, function () {
if (!is_singular(‘post’)) return ”;
$views = cnt_get_fake_post_views(get_the_ID());
return ($views === ”) ? ” : number_format_i18n($views);
});

Author
Total Views: 0
Share This Article
Leave a review