Skip to content

Instantly share code, notes, and snippets.

@artikus11
Created March 2, 2017 05:23
Show Gist options
  • Save artikus11/9322c560c1932a463abe5e830f1f41fc to your computer and use it in GitHub Desktop.
Save artikus11/9322c560c1932a463abe5e830f1f41fc to your computer and use it in GitHub Desktop.
// Add Featured meta to Publish box
add_action('post_submitbox_misc_actions', 'mts_featured_post_field');
function mts_featured_post_field () {
global $post;
/* check if this is a post, if not then we won't add the custom field */
/* change this post type to any type you want to add the custom field to */
if (get_post_type($post) != 'post')
return false;
/* get the value corrent value of the custom field */
$value = get_post_meta($post->ID, 'mts_featured', true);
?>
<div class="misc-pub-section" id="mts_featured_field">
<?php //if there is a value (1), check the checkbox
?>
<label>
<div class="dashicons dashicons-star-empty" style="padding: 0 2px 0 0; color: #888;"></div>
Лучшая статья <input type="checkbox"<?php echo(!empty($value) ? ' checked="checked"' : null) ?>value="1"
name="mts_featured" id="mts_featured" style="display: none;"/></label>
</div>
<script>jQuery(document).ready(function ($) {
$('#mts_featured').change(function () {
var $this = $(this),
$icon = $this.parent().find('.dashicons');
if ($this.is(':checked')) {
$icon.attr('class', 'dashicons dashicons-star-filled');
} else {
$icon.attr('class', 'dashicons dashicons-star-empty');
}
});
$('#mts_featured_field .dashicons').attr('class', function () {
return $('#mts_featured').is(':checked') ? 'dashicons dashicons-star-filled' : 'dashicons dashicons-star-empty';
});
});</script>
<?php
}
add_action('save_post', 'mts_save_featured_meta');
function mts_save_featured_meta ($postid) {
/* check if this is an autosave */
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return false;
/* check if the user can edit this page */
if (!current_user_can('edit_page', $postid))
return false;
// check if quick edit
if (isset($_POST['_inline_edit']) && wp_verify_nonce($_POST['_inline_edit'], 'inlineeditnonce')) {
return;
}
/* check if there's a post id and check if this is a post */
/* make sure this is the same post type as above */
if (empty($postid) || (!empty($_POST['post_type']) && $_POST['post_type'] != 'post') ||
(!empty($_GET['post_type']) && $_GET['post_type'] != 'post')
)
return false;
/* if you are going to use text fields, then you should change the part below */
/* use add_post_meta, update_post_meta and delete_post_meta, to control the stored value */
/* check if the custom field is submitted (checkboxes that aren't marked, aren't submitted) */
if (isset($_POST['mts_featured'])) {
/* store the value in the database */
add_post_meta($postid, 'mts_featured', 1, true);
} else {
/* not marked? delete the value in the database */
delete_post_meta($postid, 'mts_featured');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment