Skip to content

Instantly share code, notes, and snippets.

@emilysnothere
Last active January 31, 2023 07:39
Show Gist options
  • Save emilysnothere/943ea6274dc160cec271 to your computer and use it in GitHub Desktop.
Save emilysnothere/943ea6274dc160cec271 to your computer and use it in GitHub Desktop.
Adding fields to the WordPress post submit box
add_action('post_submitbox_misc_actions', createCustomField);
add_action('save_post', saveCustomField);
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
}
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');
}
}
@zarankumar
Copy link

Thank you for this gist

@roxanneallard
Copy link

This is awesome and super helpful!
Is there a way to use it in arguments like this and ONLY select the custom posts where the checkbox is checked?

$args = array(
'post_type' => 'teamleden' ,
'orderby' => 'date' ,
'order' => 'DESC' ,
'posts_per_page' => 4,
'paged' => get_query_var('paged'),
'post_parent' => $parent
); ?>

@sagheer007
Copy link

@roxanneallard try below code.

global $wpdb;
// Getting Post ID By Meta Key Value
$user = wp_get_current_user();
$meta_key = '_my_custom_field';
$meta_value = "1";

$prepare_guery = $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta where meta_key ='_my_custom_field' and meta_value = '$meta_value' ");
$get_values = $wpdb->get_col($prepare_guery);
$post_id = $get_values[0];

@emilysnothere
Copy link
Author

emilysnothere commented Sep 17, 2019

I think something like this should work (using WP_Query as a reference)

$posts = get_posts([
    'post_type' => 'teamleden' ,
    'orderby' => 'date' ,
    'order' => 'DESC' ,
    'posts_per_page' => 4,
    'paged' => get_query_var('paged'),
    'post_parent' => $parent,
    'meta_key' => '_my_custom_field',
    'meta_value' => true
]);

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 $wpdb or writing custom queries since WordPress is already pretty flexible

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment