// Checkbox Meta
add_action("admin_init", "checkbox_init");
function checkbox_init(){
add_meta_box("checkbox", "Checkbox", "checkbox", "post", "normal", "high");
}
function checkbox(){
global $post;
$custom = get_post_custom($post->ID);
$field_id = $custom["field_id"][0];
?>
<label>Check for yes</label>
<?php $field_id_value = get_post_meta($post->ID, 'field_id', true);
if($field_id_value == "yes") $field_id_checked = 'checked="checked"'; ?>
<input type="checkbox" name="field_id" value="yes" <?php echo $field_id_checked; ?> />
<?php
}
// Save Meta Details
add_action('save_post', 'save_details');
function save_details(){
global $post;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post->ID;
}
update_post_meta($post->ID, "field_id", $_POST["field_id"]);
}
I needed to add a custom meta checkbox on the posts page to enable certain content. The code above is from another stackoverflow answer. When I hit update post, it does save the check value, but I don't understand how to test if it's checked on a page I want to display the content.
doing if (isset()) tests if there is a value, so it's always returning true even if it's not checked. Is there a way I can test for the checked="checked" value? That is what is updating if I inspect element.
Check for on
if($field_id_value == "on") $field_id_checked = 'checked="checked"';
Related
I am adding a custom metabox for WordPress, I am able to save the value but unable to display the value in a page template.
Code in function.php
//Custome MetaBox
function custom_metabox() {
add_meta_box("custom_metabox_01", "Custom Metabox", "custom_metabox_field", "page", "side", "default", null);
}
add_action("admin_init", "custom_metabox");
function custom_metabox_field() {
wp_nonce_field(basename(__FILE__), "custom_metabox_01_nonce");
global $post;
$data = get_post_custom($post->ID);
$val = isset($data['custom_input']) ? esc_attr($data['custom_input'][0]) : 'no value';
echo '<input type="text" name="custom_input" id="custom_input" value="'.$val.'" />';
}
function save_detail() {
global $post;
if (!isset($_POST["custom_metabox_01_nonce"]) || !wp_verify_nonce($_POST["custom_metabox_01_nonce"], basename(__FILE__))){
return $post->ID;
}
if(!current_user_can("edit_post", $post->ID)){
return $post->ID;
}
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) {
return $post->ID;
}
update_post_meta($post->ID, "custom_input", $_POST["custom_input"]);
}
add_action("save_post", "save_detail");
Code in template-parts/content/content-page.php
<div class="metabox">
<?php
$custom_post_type = get_post_meta($post->ID, 'custom_input', true);
echo 'meta box value: ' . $custom_post_type;
?>
</div>
Also please suggest to me how to implement the same only for "theme-template/default.php( Custom Page Template)"
Thanks in advance.
New to Wordpress and struggling with the meta boxes. Unable to get my piece of code to work/show, nor was I able find examples that work. Nothing just wants to show up in the admin panel and have no clue what I'm missing / doing wrong.
Until now it looks like it's not triggering the callback function or something.
What I want to do:
Show a checkbox to hide the page's title
What I see:
No checkbox is showing up on the page edit screen
My code in functions.php:
function twentyseventeenchild_hide_title() {
add_meta_box(
'no-title', // Unique id
__( 'Hide title' ), // Title
'twentyseventeenchild_hide_title_callback', // Callback
'post', // Screen (such as post type, link or comment)
'normal', // Context (normal, advanced, side)
'default' // Priority (default, core, high, low)
// Callback arguments
);
}
add_action( 'add_meta_boxes', 'twentyseventeenchild_hide_title' );
/**
* Meta box display callback.
*
* #param WP_Post $post Current post object.
*/
function twentyseventeenchild_hide_title_callback( $post ) {
$meta = get_post_meta($post->ID, '_title', true);
?>
<label><?php __('Hide title') ?></label>
<input id="no_title" type="checkbox" autocomplete="off" value="<?=esc_attr($meta)?>" name="page_title">
<?php
}
You're using checkbox incorrectly.
See input checkbox: https://www.w3schools.com/tags/att_input_type_checkbox.asp
Your method need to be like:
function twentyseventeenchild_hide_title_callback( $post ) {
$meta = get_post_meta($post->ID, '_title', true);
?>
<input id="no_title" type="checkbox" <?php ($meta === '1' ? 'selected' : ''); ?> name="page_title">
<label for="no_title"><?php _e('Hide title') ?></label>
<?php
}
_e() is for translate and echo, __() only return string and not print it.
($meta === '1' ? 'selected' : ''); is because when you save metabox value truewill be saved as string 1. With this ternary you can show as selected this metabox if value is euqals 1 (as string).
I created a custom meta box where you can choose a value from some radio buttons and save it to the post_meta table in the wordpress database. With the following code I save the value:
function save_value_of_my_custom_metabox ($post_id, $post){
$post_id = get_the_ID();
$new_meta_value = ( isset( $_POST['the_name_of_the_radio_buttons'] ) ? sanitize_html_class( $_POST['the_name_of_the_radio_buttons'] ) : '' );
$meta_key = 'my_key';
update_post_meta( $post_id, $meta_key, $new_meta_value );
}
But if the post will be edited again I want the radio button with the current value to set checked. What is the best way to do that? Here is the function to display the meta box:
function my_custom_meta_box( $object, $box ) {
$post_id=get_the_ID();
$key='my_key';
$the_value_that_should_be_set_to_checked=get_post_meta( $post_id, $key);
//$the_value_that_should_be_set_to_checked[0] returns the value as string
?>
<label for="my_custom_metabox"><?php _e( "Choose value:", 'choose_value' ); ?></label>
<br />
<input type="radio" name="the_name_of_the_radio_buttons" value="value1">Value1<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value2">Value2<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value3">Value3<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value4">Value4<br>
<?php
}
I could write something like if(isset($the_value_that_should_be_set_to_checked[0])=="value of that line") echo "checked='checked'"; in every line but that doesn't seem very elegant to me. Using javascript is also pretty complicated in wordpress because I would have to use the hooks, enqueue the script and just for changing the checked property with one line of javascript it's not worth it. What's the best practice for that?
I am assuming that you are trying to add custom meta box for 'Posts'. Below code will work for you. It will show Radio buttons on add new post or edit post screen. Please read the comments in the code. It will help you in understanding the code.
You can use WordPress's checked function to decide whether to select the radio button or not.
Feel free to ask if you have any doubts.
/**
* Adds a box to the main column on the Post add/edit screens.
*/
function wdm_add_meta_box() {
add_meta_box(
'wdm_sectionid', 'Radio Buttons Meta Box', 'wdm_meta_box_callback', 'post'
); //you can change the 4th paramter i.e. post to custom post type name, if you want it for something else
}
add_action( 'add_meta_boxes', 'wdm_add_meta_box' );
/**
* Prints the box content.
*
* #param WP_Post $post The object for the current post/page.
*/
function wdm_meta_box_callback( $post ) {
// Add an nonce field so we can check for it later.
wp_nonce_field( 'wdm_meta_box', 'wdm_meta_box_nonce' );
/*
* Use get_post_meta() to retrieve an existing value
* from the database and use the value for the form.
*/
$value = get_post_meta( $post->ID, 'my_key', true ); //my_key is a meta_key. Change it to whatever you want
?>
<label for="wdm_new_field"><?php _e( "Choose value:", 'choose_value' ); ?></label>
<br />
<input type="radio" name="the_name_of_the_radio_buttons" value="value1" <?php checked( $value, 'value1' ); ?> >Value1<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value2" <?php checked( $value, 'value2' ); ?> >Value2<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value3" <?php checked( $value, 'value3' ); ?> >Value3<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value4" <?php checked( $value, 'value4' ); ?> >Value4<br>
<?php
}
/**
* When the post is saved, saves our custom data.
*
* #param int $post_id The ID of the post being saved.
*/
function wdm_save_meta_box_data( $post_id ) {
/*
* We need to verify this came from our screen and with proper authorization,
* because the save_post action can be triggered at other times.
*/
// Check if our nonce is set.
if ( !isset( $_POST['wdm_meta_box_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( !wp_verify_nonce( $_POST['wdm_meta_box_nonce'], 'wdm_meta_box' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( !current_user_can( 'edit_post', $post_id ) ) {
return;
}
// Sanitize user input.
$new_meta_value = ( isset( $_POST['the_name_of_the_radio_buttons'] ) ? sanitize_html_class( $_POST['the_name_of_the_radio_buttons'] ) : '' );
// Update the meta field in the database.
update_post_meta( $post_id, 'my_key', $new_meta_value );
}
add_action( 'save_post', 'wdm_save_meta_box_data' );
I found a working solution but I think this is not how you should do it. Still open for better solutions ;)
This code was added under the php code from above:
if(isset($$the_value_that_should_be_set_to_checked[0])){
$the_value_that_should_be_set_to_checked= $the_value_that_should_be_set_to_checked[0];
}
else{
$the_value_that_should_be_set_to_checked='';
}
Here's the code that I added below the radiobuttons:
<script type="text/javascript">
jQuery(document).ready(function () {
var checked_value= <?php echo json_encode($the_value_that_should_be_set_to_checked);?>;
if(checked_value!==''){
jQuery("input[name=the_name_of_the_radio_buttons][value="+checked_value+"]").attr('checked', 'checked');
}
});
</script>
P.S.: The $ selector will not work but that maybe depends on the theme you use.
I have Wordpress installed and I have this form on each category page sidebar:
<form name="tags" onChange="document.forms.tags.submit();">
<input type="checkbox" name="tag" value="tag1" <?php if((isset($_GET["tag"])) && $_GET["tag"] == "tag1") { echo "checked";}?>>tag1<br>
<input type="checkbox" name="tag" value="tag2" <?php if((isset($_GET["tag"])) && $_GET["tag"] == "tag2") { echo "checked";}?>>tag2
</form>
The goal is to create an url like /?tag=tag1+tag2 and so on.
With the above code I get the url like this: /?tag=tag1&tag=tag2.
I've searched for two weeks and tried a lot, but nothing works for me. I've tried for example
<input type="checkbox" name="tag[]" value="tag1" <?php if((isset($_GET["tag"])) && $_GET["tag"] == "tag1") { echo "checked";}?>>tag1
but then i get ?tag%5B%5D=tag1 and Wordpress don't find any results.
The form submit each time a checkbox is checked.
If I use radio input fields, then it works great, because then there's one value each time, but I want to pass multiple values with the same name and render a url like /?tag=tag1+tag2+tag3+tag4 etc.
Can anybody help me with this problem, because I don't know how to get this work for me. Thanks!
this is what you want:
// This would output '/client/?s=word&foo=bar'
echo add_query_arg( 'foo', 'bar' );
take a look on add_query_arg() and get_query_var()
Consider on this example http://codepad.org/s08Jmseg
$url_string = $_SERVER['QUERY_STRING'];
// reuturn: tag=tag1+tag2+tag3
parse_str($url_string);
// $tag holds the value tag1+tag2+tag3
$string = urldecode( $tag );
$arr = explode(" ", $string);
$my_tag = "tag2";
if( in_array( $my_tag, $arr ) ) {
// $key
echo $my_tag . ' found!';
}
else {
echo "Tag Not Found!";
}
//print_r($arr);
I created a couple meta fields in Wordpress for a Custom Post Type. They are 'Price' and 'Details'. If I got to the 'edit post' page, and i change something in one of these fields, but then decide to just leave the page by hitting 'back' in the browser or closing the window, i get a warning from my browser "are you sure you want to leave the page?". When I hit 'Yes', it erases anything that's in those 2 fields, even what was previously stored before my editing.
Any idea why this could be?
Here's some of my code in functions.php:
add_action("admin_init", "admin_init");
function admin_init()
{
add_meta_box("price", "Price", "price_field", "product", "normal", "high");
add_meta_box("details", "Details", "details_field", "product", "normal", "high");
}
function price_field()
{
global $post;
$custom = get_post_custom($post->ID);
$price = $custom["price"][0];
?>
<label>Price: $</label>
<input name="price" value="<?php echo $price; ?>" />
<?php
}
function details_field()
{
global $post;
$custom = get_post_custom($post->ID);
$details = $custom["details"][0];
?>
<label>Details:</label>
<input name="details" rows='5' value="<?php echo $details; ?>" />
<?php
}
/*--------------------------------*/
/* Save PRICE and DETAILS fields */
/*--------------------------------*/
add_action('save_post', 'save_details');
function save_details()
{
global $post;
update_post_meta($post->ID, "price", $_POST["price"]);
update_post_meta($post->ID, "details", $_POST["details"]);
}
This is because you didnt add filtering in your save details method. Remember action hook "save_post" is also called once the post is auto save in draft even if you didnt click the update or the publish button. Try this
add_action('save_post', 'save_details');
function save_details($post_id){
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// uncomment if youre using nonce
//if ( !wp_verify_nonce( $_POST['my_noncename'], plugin_basename( __FILE__ ) ) )
// return;
// Check permissions
//change the "post" with your custom post type
if ( 'post' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
//if success go to your process
//you can erase your global $post and dont use $post->ID rather change it with $post_id since its our parameter
update_post_meta($post_id, "price", $_POST["price"]);
update_post_meta($post_id, "details", $_POST["details"]);
}
NOTE: in if ( 'post' == $_POST['post_type'] ) line, change "post" to your post type