Last active
January 31, 2023 07:39
-
-
Save emilysnothere/943ea6274dc160cec271 to your computer and use it in GitHub Desktop.
Adding fields to the WordPress post submit box
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| add_action('post_submitbox_misc_actions', createCustomField); | |
| add_action('save_post', saveCustomField); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function createCustomField() | |
| { | |
| $post_id = get_the_ID(); | |
| if (get_post_type($post_id) != 'post') { | |
| return; | |
| } | |
| $value = get_post_meta($post_id, '_my_custom_field', true); | |
| wp_nonce_field('my_custom_nonce_'.$post_id, 'my_custom_nonce'); | |
| ?> | |
| <div class="misc-pub-section misc-pub-section-last"> | |
| <label><input type="checkbox" value="1" <?php checked($value, true, true); ?> name="_my_custom_field" /><?php _e('My Custom Checkbox Field', 'pmg'); ?></label> | |
| </div> | |
| <?php | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function saveCustomField($post_id) | |
| { | |
| if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { | |
| return; | |
| } | |
| if ( | |
| !isset($_POST['my_custom_nonce']) || | |
| !wp_verify_nonce($_POST['my_custom_nonce'], 'my_custom_nonce_'.$post_id) | |
| ) { | |
| return; | |
| } | |
| if (!current_user_can('edit_post', $post_id)) { | |
| return; | |
| } | |
| if (isset($_POST['_my_custom_field'])) { | |
| update_post_meta($post_id, '_my_custom_field', $_POST['_my_custom_field']); | |
| } else { | |
| delete_post_meta($post_id, '_my_custom_field'); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think something like this should work (using WP_Query as a reference)
This stackoverflow answer has more examples: https://wordpress.stackexchange.com/questions/30970/using-get-posts-with-arguments-found-in-meta-keys
I don't recommend using
$wpdbor writing custom queries since WordPress is already pretty flexible