How to add default value in custom taxonomy field in wordpress - wordpress

I've created custom taxonomy name "Front List" using Custom Post Type UI then add a custom field called "Order". I'm trying to set a default value for order. When I create any frontlist using the frontlist panel,
it's adding a default value, but when I create frontlist from "Add Post" page it's not adding any default value for "Order field".
How to I add default value when "Front List" created from "Add Post" page?
This is the code for adding a custom field to Frontlist taxonomy.
<?php
/**
* Adding Custom Field to Taxonomy
* #return void
*/
function frontlists_add_order( $term ) {
?>
<div class="form-field">
<label for="taxOrder"><?php _e( 'Order', 'yourtextdomain' ); ?></label>
<input type="text" name="taxOrder" id="taxOrder" value="">
<p>Your front List item will be sorted by this "Order". The default value is "1".</p>
</div>
<?php
}
add_action( 'frontlists_add_form_fields', 'frontlists_add_order', 10, 2 );
/**
* Adding Custom Field to Taxonomy in Edit Panel
* #return void
*/
function frontlists_edit_order( $term ) {
$term_order = get_term_meta( $term->term_id, 'order', true );
?>
<tr class="form-field">
<th><label for="taxOrder"><?php _e( 'Order', 'yourtextdomain' ); ?></label></th>
<td>
<input type="text" name="taxOrder" id="taxOrder" value="<?php echo esc_attr( $term_order ) ? esc_attr( $term_order ) : ''; ?>">
<p>Your front List item will be sorted by this "Order".</p>
</td>
</tr>
<?php
}
add_action( 'frontlists_edit_form_fields', 'frontlists_edit_order', 10 );
/**
* Saving Custom Field to Taxonomy
*/
function frontlists_save_order( $term_id ) {
if ( isset( $_POST['taxOrder'] ) ) {
$term_order = $_POST['taxOrder'];
if( $term_order ) {
update_term_meta( $term_id, 'order', $term_order );
} else {
update_term_meta( $term_id, 'order', 1 );
}
}
}
add_action( 'edited_frontlists', 'frontlists_save_order' );
add_action( 'create_frontlists', 'frontlists_save_order' );

You can use the created_term action hook to add the new taxonomy term once it's already been added to the database. This action hook is inside the wp_insert_term function. Either put this in your theme (not advised), or inside a plugin.
function so_add_order_field( $term_id, $tt_id, $taxonomy ) {
// The default order value
$default = 1;
// Stop if it's not the right taxonomy
if ( 'frontlists' != $taxonomy ) {
return false;
}
// Get the existing value if exists
$order = get_term_meta( $term_id, 'taxOrder', true );
if ( false === $order ) {
// Add the term meta default
add_term_meta( $term_id, 'taxOrder', $default );
}
}
add_action( 'created_term', 'so_add_order_field', 10, 3 );
Then change the $default value to whatever you'd like it to be. This uses the add_term_meta function which safely adds the meta data to the database for you. Check out the documentation for further info.

Related

Custom Field created in add_meta_boxes reappearing itself again in the default Custom Metabox

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.

How to change add-to-cart form?

Is there a way to change the WooCommerce add-to-cart form through functions.php?
The goal is to add a checkbox for an additional product. When the checkbox is checked this product will also be added to the cart after a click on the add to cart button.
I am looking for a solution which doesn't rely on javascript.
A better title would be "WooCommerce up-sells as checkboxes".
A lot of research and several strategies to tackle this problem lead me to a solution which I thought was not even possible in the beginning.
The solution is now exactly what I wanted. A non-JavaScript, no-template-override, but a simple and pure addition to functions.php. It works for simple and variable products (and probably with grouped and external products too).
It misses some nice features still. It won't work yet if an up-sell is a variable product. Quantity selection and limiting up-sells per item or order would be nice additions too. Based on the code below adding those features should not be a big deal anymore.
// create the checkbox form fields and add them before the cart button
add_action( 'woocommerce_before_add_to_cart_button', 'action_woocommerce_before_add_to_cart_form', 10, 0 );
function action_woocommerce_before_add_to_cart_form(){
global $woocommerce, $product;
// get the product up-sells
$upsells = $product->get_upsells();
// store the number of up-sells and pass it on to the add-to-cart hook
?>
<input type="hidden" name="upsells_size" value="<?php echo(sizeof($upsells)); ?>">
<div id="wb-upsell-div">
<?php
// iterate through all upsells and add an input field for each
$i = 1;
foreach( $upsells as $value ){
$product_id = $value;
?>
<input id="wb-upsell-checkboxes" type="checkbox" name="upsell_<?php echo($i) ?>" value="<?php echo($product_id); ?>"><?php echo( '' . get_the_title( $product_id ) . "". " ($" . get_post_meta( $product_id, '_regular_price', true) . ")"); ?><br>
<?php
$i++;
}
?>
</div>
<?php
}
// function to add all up-sells, where the checkbox have been checked, to the cart
add_action('woocommerce_add_to_cart', 'custom_add_to_cart', 10, 3);
function custom_add_to_cart() {
global $woocommerce;
// get the number of up-sells to iterate through
$upsell_size = $_POST['upsells_size'];
// iterate through up-sell fields
for ($i=1; $i<=$upsell_size; $i++){
// get the product id of the up-sell
$product_id = $_POST['upsell_' . $i];
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
And here is the CSS for formatting the <div>and the checkboxes. It goes into the style.css file:
#wb-upsell-div {
margin-top: 10px;
margin-bottom: 20px;
}
#wb-upsell-checkboxes{
}
So there's an actual answer to this question, you can add whatever you want inside the add to cart <form> using hooks. For example:
add_action( 'woocommerce_before_add_to_cart_button', 'so_34115452_add_input' );
function so_34115452_add_input(){
echo '<input type="checkbox" name="something"/>' . __( 'Some Checkbox', 'text-domain' );
}

How to show avatar only if it exists?

Is there any function in Wordpress that allows to hide the gravatar if id doesn't exists?
I have many authors that doesn't have a gravatar and all are displayed like this:
http://prntscr.com/98zsji
I would like to hide the default image.
I used the function validate_gravatar($email);, but it generated an error:
Fatal error: Call to undefined function validate_gravatar()
If I print $user_email it display correctly the user email.
You can use validate_gravatar which takes in the email address of the user and returns back true or false.
validate_gravatar($email); // returns true or false
How to use it in your code:
$user_email = get_the_author_meta('user_email');
if(validate_gravatar($user_email)) {
$author_avatar = get_avatar( get_the_author_meta( 'user_email', $author_id ), '78', '', get_the_author_meta( 'display_name', $author_id ) );
}
// Now just echo where ever you want the image, it will show a default image if no gravatar is present.
if(isset($author_avatar) && !empty($author_avatar)){
echo '<img src="'.$author_avatar.'" />';
}
// In your Functions.php
function validate_gravatar($email) {
$hash = md5(strtolower(trim($email)));
$uri = 'http://www.gravatar.com/avatar/' . $hash . '?d=404';
$headers = #get_headers($uri);
if (!preg_match("|200|", $headers[0])) {
$has_valid_avatar = FALSE;
} else {
$has_valid_avatar = TRUE;
}
return $has_valid_avatar;
}
Here is the filter that will do the trick:
function ns_filter_avatar($avatar, $id_or_email, $size, $default, $alt, $args)
{
$headers = #get_headers( $args['url'] );
if( ! preg_match("|200|", $headers[0] ) ) {
return;
}
return $avatar;
}
add_filter('get_avatar','ns_filter_avatar', 10, 6);
To work you have to add value 404 as third argument $default to get_avatar(). Example:
get_avatar( $user_email, 45, '404' )
I have been using the code below for a while and always work for me. The code is checked with PHPCS and WordPress Theme Standards and there is no errors or warnings.
The script profile-image.js is only enqueued on the respective page user-edit.php, that also applies for the media-upload and Thickbox scripts, this procedure will avoid any possible scripts conflict on your WordPress admin area.
/**
*
* Add custom user profile information
*
*/
add_action( 'show_user_profile', 'ns_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'ns_show_extra_profile_fields' );
function ns_show_extra_profile_fields( $user ) { ?>
<h3>Extra profile information</h3>
<table class="form-table">
<tr>
<th><label for="image">Profile Image</label></th>
<td>
<img src="<?php echo esc_attr( get_the_author_meta( 'image', $user->ID ) ); ?>" style="height:50px;">
<input type="text" name="image" id="image" value="<?php echo esc_attr( get_the_author_meta( 'image', $user->ID ) ); ?>" class="regular-text" /><input type='button' class="button-primary" value="Upload Image" id="uploadimage"/><br />
<span class="description">Please upload your image for your profile.</span>
</td>
</tr>
</table>
<?php
}
/**
* Enqueue a script in the WordPress admin user-edit.php.
*
* #param int $pagenow Hook suffix for the current admin page.
*/
function ns_selectively_enqueue_admin_script( $hook ) {
global $pagenow;
if ($pagenow != 'user-edit.php') {
return;
}
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_style('thickbox');
wp_register_script( 'profile-image', get_template_directory_uri().'/js/profile-image.js', array('jquery-core'), false, true );
wp_enqueue_script( 'profile-image' );
}
add_action( 'admin_enqueue_scripts', 'ns_selectively_enqueue_admin_script' );
/*
* Save custom user profile data
*
*/
add_action( 'personal_options_update', 'ns_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'ns_save_extra_profile_fields' );
function ns_save_extra_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
return false;
if(isset($_POST['image'])) {
$imageprofile = sanitize_text_field( wp_unslash( $_POST['image'] ) );
update_user_meta( $user_id, 'image', $imageprofile );
}
}
profile-image.js:
jQuery(document).ready(function() {
jQuery(document).find("input[id^='uploadimage']").live('click', function(){
//var num = this.id.split('-')[1];
formfield = jQuery('#image').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#image').val(imgurl);
tb_remove();
}
return false;
});
});

How to set radio buttons in custom meta box checked?

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.

Add a checkbox in the post meta box

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);

Resources