data gets updated correctly in the the database. however, when i'm in WP, the checkboxes don't get the values correctly...they all show up as unchecked. any thoughts on how to do this.
Thanks in advance
/* Fire our meta box setup function on the post editor screen. */
add_action( 'load-post.php', 'smashing_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'smashing_post_meta_boxes_setup' );
/* Meta box setup function. */
function smashing_post_meta_boxes_setup() {
/* Add meta boxes on the 'add_meta_boxes' hook. */
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_flautist_access_save_meta', 10, 2 );
}
/* Create one or more meta boxes to be displayed on the post editor screen. */
function smashing_add_post_meta_boxes() {
add_meta_box(
'smashing-flautist-access', // Unique ID
esc_html__( 'Post Viewing Permission', 'smashing_flautist' ), // Title
'smashing_flautist_access_meta_box', // Callback function
'destinations', // Admin page (or post type)
'normal', // Context
'default' // Priority
);
}
/* Display the post meta box. */
function smashing_flautist_access_meta_box( $object, $box ) { ?>
<?php wp_nonce_field( basename( __FILE__ ), 'smashing_flautist_access_nonce' ); ?>
<table class="smashing-flautist-access">
<tr align="left">
<th>Username</th>
<th> </th>
<th>Visiblity</th>
<th> </th>
<th>Name</th>
</tr>
<?php
global $post;
$users = get_users('role=subscriber');
foreach ($users as $user) {
$user_info = get_userdata( $user->ID );
if(get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login) $ifchecked = 'checked="checked" ';
echo "<tr>";
echo "<td>$user->user_login</td><td> </td>";
echo "<td align=\"center\"><input type=\"checkbox\" name=\"smashing-flautist-access\" id=\"smashing-flautist-access\" value=\"$user->user_login\" " . $ifchecked ."/></td><td> </td>";
echo "<td>$user_info->last_name, $user_info->first_name</td><td> </td>";
echo "</tr>";
unset($ifchecked);
} ?></table>
<?php }
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_flautist_access_save_meta', 10, 2 );
/* Save the meta box's post metadata. */
function smashing_flautist_access_save_meta( $post_id, $post ) {
/* Make all $wpdb references within this function refer to this variable */
global $wpdb;
/* Verify the nonce before proceeding. */
if ( !isset( $_POST['smashing_flautist_access_nonce'] ) || !wp_verify_nonce( $_POST['smashing_flautist_access_nonce'], basename( __FILE__ ) ) )
return $post_id;
/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );
/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
/* Get the posted data and sanitize it for use as an HTML class. */
$new_meta_value = ( isset( $_POST['smashing-flautist-access'] ) ? sanitize_html_class( $_POST['smashing-flautist-access'] ) : '' );
/* Get the meta key. */
$meta_key = 'smashing_flautist_access';
/* Get the meta value of the custom field key. */
$meta_value = get_post_meta( $post_id, $meta_key, true );
/* If a new meta value was added and there was no previous value, add it. */
if ( $new_meta_value && '' == $meta_value )
{
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'private' WHERE ID = ".$post_id." AND post_type ='post'"));
}
/* If the new meta value does not match the old value, update it. */
elseif ( $new_meta_value && $new_meta_value != $meta_value )
{
update_post_meta( $post_id, $meta_key, $new_meta_value );
$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'private' WHERE ID = ".$post_id." AND post_type ='post'"));
}
/* If there is no new meta value but an old value exists, delete it. */
elseif ( '' == $new_meta_value && $meta_value )
{
delete_post_meta( $post_id, $meta_key, $meta_value );
$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'public' WHERE ID = ".$post_id." AND post_type ='post'"));
}
}
Instead of:
if(get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login) $ifchecked = 'checked="checked" ';
Try:
$ifchecked = (get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login)? 'CHECKED ':'';
Using this, you can also remove the unset($ifchecked); as you are always assigning $ifchecked a new value in each iteration. The unset doesn't hurt anything, it's just not necessary.
HTH,
=C=
Related
I have a custom user profile field "association_id". I can see the field the underlying wordpess db table (usermeta) with the 'meta_key' as "association_id" and the 'meta_value' whatever that I maintain for each user.
add_action( 'show_user_profile', 'rudr_profile_fields' );
add_action( 'edit_user_profile', 'rudr_profile_fields' );
function rudr_profile_fields( $user )
{
// let's get custom field values
$association_id = get_user_meta( $user->ID, 'association_id', true );
?>
<h3>Association Information</h3>
<table class="form-table">
<tr>
<th><label for="association_id">Association_ID</label></th>
<td>
<input type="text" name="association_id" id="association_id" value="<?php echo esc_attr( $association_id ) ?>" class="regular-text" />
<span class="description"><?php _e("Please enter your Association ID (For eg. if RCIC, your license number)."); ?></span>
</td>
</tr>
</table>
<?php
}
//avoid self to edit //
//add_action( 'personal_options_update', 'rudr_save_profile_fields' ); //
add_action( 'edit_user_profile_update', 'rudr_save_profile_fields' );
function rudr_save_profile_fields( $user_id ) {
if( ! isset( $_POST[ '_wpnonce' ] ) || ! wp_verify_nonce( $_POST[ '_wpnonce' ], 'update-user_' . $user_id ) ) {
return;
}
if( ! current_user_can( 'edit_user', $user_id ) ) {
return;
}
/* HOLDING SPACE FOR ENHANCED SNIPPED */
//include in the list view of users
add_filter( 'manage_users_columns', 'column_register_association_id' );
add_filter( 'manage_users_custom_column', 'column_display_association_id', 10, 3 );
function column_register_association_id( $columns )
{
$columns['association_id'] = 'association_id';
return $columns;
}
function column_display_association_id( $value, $column_name, $user_id )
{
$user_info = get_user_meta( $user_id, 'association_id', true );
if($column_name == 'association_id') return $user_info;
return $value;
}
//Sort association_id column
function association_id_register_sortable( $columns ) {
$columns['association_id'] = 'association_id';
return $columns;
}
add_filter( 'manage_users_sortable_columns', 'association_id_register_sortable' );
function association_id_orderby( $vars ) {
if ( isset( $vars['orderby'] ) && 'association_id' == $vars['orderby'] ) {
$vars = array_merge( $vars, array(
'meta_key' => 'association_id',
'orderby' => 'meta_value'
) );
}
return $vars;
}
add_filter( 'request', 'association_id_orderby' );
The preceding works fine and creates a meta key for storing meta value in the metadata wp table.
I want this custom user profile field value that I enter in the user admin page to be unique, verifying with the underlying wordpress database table. So I enhanced the code at the time of creation with the additional lines below. I tried these two snippets in the wordpress child theme, but it throws a critical error. I am on PHP version 8.
I tried two options below at the placeholder location in the above code, replacing the line below.
/* HOLDING SPACE FOR ENHANCED SNIPPED */
Option 1 that I tried.
$checkMeta=$wpdb->get_results("SELECT user_id FROM $wpdb->usermeta WHERE meta_key='association_id' AND meta_value=".$association_id,ARRAY_A);
if (empty($checkMeta)) {
update_user_meta( $user_id, 'association_id', sanitize_text_field( $_POST[ 'association_id' ] ) );
}
Option 2 that I tried.
$mysqli = new mysqli(SERVER, DBUSER, DBPASS, DATABASE); $result = $mysqli->query("SELECT user_id FROM usermeta WHERE meta_key='association_id' && meta_value=$association_id "); if($result->num_rows == 0) { // row not found, do stuff update_user_meta( $user_id, 'association_id', sanitize_text_field( $_POST[ 'association_id' ] ) ); } else { // row found, do stuff echo ' This ID is already used.'; } $mysqli->close();
Both failed to activate when I tried to create or change the 'association_field' value, throwing critical errors and aborting.
I succeed in creating a metabox with custom field inside, and I restrict it to appear in a custom post type.
//define metabox
function product_info_en() {
add_meta_box( 'english_info', 'English Info', 'english_product_name_callback', array('product'), 'normal', 'high' );
}
//add to hook
add_action( 'add_meta_boxes', 'product_info_en' );
The code to display it in the product page:
// display in add product admin page
function english_product_name_callback( $post ) {
//ob_start();
$content = esc_attr( get_post_meta( get_the_ID(), 'product_desc_en', true ) );
//here goes the custom field
echo '<fieldset><div><label><b>English Product Name:</b></label><br/>';
echo '<input id="product_name_en" type="text" name="product_name_en" style="width:100%; margin:10px 0px"';
echo ' value="';
echo esc_attr( get_post_meta( get_the_ID(), 'product_desc_en', true ) );
echo '"></div></fieldset>';
//here goes the wp_editor
echo '<fieldset><div><label><b>English Product Content Info:</b></label><div><br/>';
echo '<div>';
wp_editor($content, 'product_desc_en', array(
'wpautop' => true,
'media_buttons' => true,
'textarea_rows' => 10
)
);
echo '</div></fieldset>';
}
Here goes the code that do the saving job:
//save
function enginfo_save_meta_box( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( $parent_id = wp_is_post_revision( $post_id ) ) {
$post_id = $parent_id;
}
$fields = [
'product_name_en',
];
foreach ( $fields as $field ) {
if ( array_key_exists( $field, $_POST ) ) {
update_post_meta( $post_id, $field, sanitize_text_field( $_POST[$field] ) );
}
}
update_post_meta( $post_id,'product_desc_en', wp_kses_post( $_POST['product_desc_en'] ) );
}
add_action( 'save_post', 'enginfo_save_meta_box' );
However, the custom created field that supposed to be going only into the newly created metabox, will always show up in the default "custom field". And this happens to all post type.
As shown below, What could possibly be the issue here?
To hide and not show your custom fields there in default box, please prefix your custom fields with underscore _ , so product_desc_en will become _product_des_en
I mean the names of your custom fields should be prefixed with underscore and WordPress default custom metabox will ignore them and not show in WordPress default GUI, but you can use and display them in your own custom metaboxes by calling with there new Underscore prefixed names.
I had create a custom post-type called 'cliente_finale'.
I've some custom field on it and everything works fine.
I've a trouble with custom filtering 'in edit.php'.
I'had create 2 custom filters, and they works fine if used singularly or in addition with every other default WordPress filter. But when they are used togheter, I can see only the last filter results (ordered with the hook priority).
I think that my query results are in some way overrided by the 'last' (in priority) filter.
I'm not figuring out the solution, probably for a lack in the WordPress core functionalities.
Here the code for this filters...
/* =======================================
FILTRO COMM. PRINCIPALE
======================================= */
function list_filter_principale_cliente_finale(){
$type = 'cliente_finale';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
//only add filter to post type you want
if ('cliente_finale' == $type){
//change this to the list of values you want to show
//in 'label' => 'value' format
global $wpdb;
$all_commerciali = $wpdb->get_results( "SELECT meta_value FROM wp_postmeta WHERE meta_key = 'cliente-finale-commerciale-principale-commerciale_principale_commerciale_principale' " );
$values = array();
foreach($all_commerciali as $principale){
$principaleID = $principale->meta_value;
$principaleNome = get_user_meta($principaleID,'nickname',true);
if(!in_array($principaleID, $values)){
$values[$principaleNome] = $principaleID;
}
}
ksort($values);
?>
<select name="principale">
<option value=""><?php _e('Tutti i principali ', 'wose45436'); ?></option>
<?php
$current_v = isset($_GET['principale'])? $_GET['principale']:'';
foreach ($values as $label => $value) {
printf
(
'<option value="%s"%s>%s</option>',
$value,
$value == $current_v? ' selected="selected"':'',
$label
);
}
?>
</select>
<?php
}
}
add_action( 'restrict_manage_posts', 'list_filter_principale_cliente_finale' );
/**
* if submitted filter by post meta
*
* make sure to change META_KEY to the actual meta key
* and POST_TYPE to the name of your custom post type
*/
function filtra_principale_cliente_finale( $vars ){
global $pagenow;
$type = 'cliente_finale';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
if(!is_administrator()){
$_GET['principale'] = get_current_user_id();
}
if ( 'cliente_finale' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['principale']) && $_GET['principale'] != '') {
$vars['meta_key'] = 'cliente-finale-commerciale-principale-commerciale_principale_commerciale_principale';
$vars['meta_value'] = $_GET['principale'];
}
return $vars;
}
add_filter( 'request', 'filtra_principale_cliente_finale' ,2);
/* =======================================
FILTRO COMM. PRINCIPALE - END
======================================= */
/* =======================================
FILTRO COMM. PRINCIPALE STATUS APPROVATO
======================================= */
function list_filter_principale_cliente_finale_approvato(){
$type = 'cliente_finale';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
//only add filter to post type you want
if ('cliente_finale' == $type){
//change this to the list of values you want to show
//in 'label' => 'value' format
$values = array(
"Da approvare" => "da_approvare",
"Approvato" => "approvato",
"Non approvato" => "non_approvato"
);
?>
<select name="approvato">
<option value=""><?php _e('Tutti gli status', 'wose45436'); ?></option>
<?php
$current_v = isset($_GET['approvato'])? $_GET['approvato']:'';
foreach ($values as $label => $value) {
printf
(
'<option value="%s"%s>%s</option>',
$value,
$value == $current_v? ' selected="selected"':'',
$label
);
}
?>
</select>
<?php
}
}
add_action( 'restrict_manage_posts', 'list_filter_principale_cliente_finale_approvato' );
/**
* if submitted filter by post meta
*
* make sure to change META_KEY to the actual meta key
* and POST_TYPE to the name of your custom post type
*/
function filtra_approvato_cliente_finale( $vars ){
global $pagenow;
$type = 'cliente_finale';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
if ( 'cliente_finale' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['approvato']) && $_GET['approvato'] != '') {
$vars['meta_key'] = 'cliente-finale-approvato_approvato';
$vars['meta_value'] = $_GET['approvato'];
}
return $vars;
}
add_filter( 'request', 'filtra_approvato_cliente_finale',1 );
/* =======================================
FILTRO COMM. PRINCIPALE STATUS APPROVATO - END
======================================= */
Here an image of the WordPress custom post-type admin area
Thank You! 😉
I want to add a checkbox in product post type. So i wrote the code
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );
/* Create one or more meta boxes to be displayed on the post editor screen. */
function smashing_add_post_meta_boxes() {
add_meta_box(
'smashing-post-class', // Unique ID
esc_html__( 'Post Class', 'example' ), // Title
'smashing_post_class_meta_box', // Callback function
'product', // Admin page (or post type)
'side', // Context
'default' // Priority
);
}
/* Display the post meta box. */
function smashing_post_class_meta_box( $object, $box ) { ?>
<?php wp_nonce_field( basename( __FILE__ ), 'smashing_post_class_nonce' ); ?>
<p>
<label for="smashing-post-class"><?php _e( "Add a custom CSS class, which will be applied to WordPress' post class.", 'example' ); ?></label>
<br />
<input class="widefat" type="checkbox" name="smashing-post-class" id="smashing-post-class" value="<?php echo esc_attr( get_post_meta( $object->ID, 'smashing_post_class', true ) ); ?>" size="30" />What's New
</p>
<?php }
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_save_post_class_meta', 10, 2 );
/* Save the meta box's post metadata. */
function smashing_save_post_class_meta( $post_id, $post ) {
/* Verify the nonce before proceeding. */
if ( !isset( $_POST['smashing_post_class_nonce'] ) || !wp_verify_nonce( $_POST['smashing_post_class_nonce'], basename( __FILE__ ) ) )
return $post_id;
/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );
/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
/* Get the posted data and sanitize it for use as an HTML class. */
$new_meta_value = ( isset( $_POST['smashing-post-class'] ) ? sanitize_html_class( $_POST['smashing-post-class'] ) : '' );
/* Get the meta key. */
$meta_key = 'smashing_post_class';
/* Get the meta value of the custom field key. */
$meta_value = get_post_meta( $post_id, $meta_key, true );
/* If a new meta value was added and there was no previous value, add it. */
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
/* If the new meta value does not match the old value, update it. */
elseif ( $new_meta_value && $new_meta_value != $meta_value )
update_post_meta( $post_id, $meta_key, $new_meta_value );
/* If there is no new meta value but an old value exists, delete it. */
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, $meta_key, $meta_value );
}
How can i change the code to get the checkbox value and checked if someone check the checkbox before.
Here, i changed only the input box "text" to "checkbox". But i do not know what to do to create a single checkbox. Please help me. I am new in wordpress.
you prob need to assign a value for the checkbox. You might want to think what this value is if not already set.
value="<?php echo esc_attr( get_post_meta( $object->ID, 'smashing_post_class', true ) ); ?>"
on a new post this is not set. So you could do something like
value="<?php if ($x=get_post_meta( $object->ID, 'smashing_post_class', true ) ) {echo $x;}else{echo "whatever";} ?>"
You are already saving the value to post_meta(see $new_meta_value) so the code to set the value already pulls it from the database if it exists.
you might want to rethink the way you are doing the above. The checkbox value is always going to be the same from now on. You might as well set the value to whatever you want it to be right now. E.g.
<input type="checkbox" name="whatever" value="true"> select me for fun
you can access the posted value in your save meta box function
$value= $_POST['whatever'];
and save to post meta (a seperate database table for custom values and a few other values that dont fit wp_posts)
update_post_meta($post_id, '_keyname', $value);
I know how to create a custom template for a specific page. However I would like to create a template for a specific custom post type. Is that possible and if true how can I do that?
If I create a new template it will show in admin only when I'm adding a page, but when I'm adding a new post type I don't have the option to select a certain template.
Problem resolved:
/*
Show the list of available custom templates templates in the Custom Post Type admin section
*/
/**
* Post_type
*/
define( 'MY_THEME_POST_TYPE', 'cases' );
/**
* Load the page template for any post object
* having the appropriate meta key set.
*/
add_action( 'template_redirect', 'mytheme_template_redirect' );
function mytheme_template_redirect() {
global $wp_query;
$id = (int) $wp_query->get_queried_object_id();
$template = get_post_meta( $id, '_wp_page_template', true );
if ( $template && 'default' !== $template ) {
$file = STYLESHEETPATH . '/' . $template;
if( is_file( $file ) ) {
require_once $file;
exit;
}
}
}
/**
* Process the Meta Box
* #todo Permissions check.
* #todo Filter input.
* #todo Nonces.
*/
add_action( 'save_post', 'mytheme_process_resource_template' );
function mytheme_process_resource_template() {
global $post;
/* Sanitize $_POST array. */
$clean_id = ( isset( $_POST['ID'] ) ) ? intval( $_POST['ID'] ) : 0;
if ( !empty( $_POST['page_template'] ) && MY_THEME_POST_TYPE == $post->post_type ) {
$page_templates = get_page_templates();
if ( 'default' != $page_template && !in_array( $_POST['page_template'], $page_templates ) ) {
if ( $wp_error )
return new WP_Error('invalid_page_template', __('The page template is invalid.'));
else
return 0;
}
update_post_meta( $clean_id, '_wp_page_template', $_POST['page_template'] );
}
}
/**
* Registers the Meta Box
* #uses mytheme_page_attributes_meta_box()
*/
add_action( 'admin_init', 'mytheme_register_meta_boxes', 10 );
function mytheme_register_meta_boxes() {
add_meta_box(
'mytheme_post_type_template',
'Template',
'mytheme_page_attributes_meta_box',
MY_THEME_POST_TYPE,
'side',
'low'
);
}
/**
* Creates the Meta Box
*/
function mytheme_page_attributes_meta_box() {
global $post;
$post_type_object = get_post_type_object($post->post_type);
if ( 0 != count( get_page_templates() ) ) {
$template = get_post_meta( $post->ID, '_wp_page_template', true );
?>
<p><strong><?php _e('Template') ?></strong></p>
<label class="screen-reader-text" for="page_template"><?php _e('Page Template') ?></label><select name="page_template" id="page_template">
<option value='default'><?php _e('Default Template'); ?></option>
<?php page_template_dropdown( $template ); ?>
</select>
<?php
}
}
Create page that is called:
single-{cpt-slug}.php e.g. single-product.php
It will be used when showing a page of a custom post type. i.e. when someone goes to http://example.com/product/awesome-shoes/