Save Selected Option in Meta Box - wordpress

i am going to build my own theme
I try to add select to post_type meta box, but every update post my select not on selected option but show the first option (blank value)
here is my code
function mhs_data() {
global $post;
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
$nisn = get_post_meta($post->ID, '_nisn', true);
$rel = get_post_meta($post->ID, '_rel', true);
}
echo '<p>NISN</p>';
echo '<input type="text" name="_nisn" value="' . $nisn . '" class="widefat" />';
echo '<p>Relationship</p>'; ?>
<select name="_rel" id="_rel">
<option value="">Relationship</option>
<option value="Single" <?php selected( $rel, 'Single' ); ?>>Single</option>
<option value="Marry" <?php selected( $rel, 'Marry' ); ?>>Marry</option>
</select>
<?php
}
function mhs_data_meta($post_id, $post) {
if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
$events_meta['_nisn'] = $_POST['_nisn'];
$events_meta['_rel'] = $_POST['_rel'];
foreach ($events_meta as $key => $value) {
if( $post->post_type == 'revision' ) return;
$value = implode(',', (array)$value);
if(get_post_meta($post->ID, $key, FALSE)) {
update_post_meta($post->ID, $key, $value);
} else {
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key);
}
}
add_action('save_post', 'mhs_data_meta', 1, 2);
Please help me to correct my code

Using Codestar Framework its very simple tu add metaboxes to your custom post, create configuration page, plugins, taxonomies and use the customizer if you prefer use it instead of a configuration page. see the documentation here for more information.
in your example, to add a select metabox shuld use a code similar to:
load the framework on your functions.php
require_once __DIR__ . '/'.$FRAMEWORK_PATH.'/cs-framework/cs-framework.php';
edit the cs-framekork.php configuration file to active only the features you need:
defined('CS_ACTIVE_FRAMEWORK') or define('CS_ACTIVE_FRAMEWORK', false); // if you need it for plugin or configuration page
defined('CS_ACTIVE_METABOX') or define('CS_ACTIVE_METABOX', true); // if you only need it for metabox
defined('CS_ACTIVE_TAXONOMY') or define('CS_ACTIVE_TAXONOMY', false);
defined('CS_ACTIVE_SHORTCODE') or define('CS_ACTIVE_SHORTCODE', false);
defined('CS_ACTIVE_CUSTOMIZE') or define('CS_ACTIVE_CUSTOMIZE', false);
and then in your function.php or as I prefer on another file included in your function.php register your metabox
function register_this_metabox($options)
{
$options = array(); // this will clean the default cs-framework configuration
$options[] = array(
'id' => 'the_metabox',
'title' => 'Meta Box title',
'post_type' => 'post', // the post type where the metabox appears
'context' => 'side', // metabox position
'priority' => 'high',
'sections' => array( // metabox fields, see the documentation
array(
'name' => 'the_metabox_fields',
'fields' => array(
array(
'id' => 'the_metabox_select_field',
'type' => 'select',
'title' => 'Select Field',
'options' => array(
'opt1' => 'Option 1',
'opt2' => 'Option 2',
'opt3' => 'Option 3',
),
'default_option' => 'Select a option',
),
),
),
),
);
return $options;
}
add_filter('cs_metabox_options', 'register_this_metabox');
And now you only have to get the values in your theme:
$post_metabox = get_post_meta($post->ID, 'the_metabox', true);
$selected_option = $post_metabox['the_metabox_select_field']

Related

I want to make woocomerce field required

I want to gender filed required in the woocommerce. I placed the field. It creates a gender field but I was unable to create gender field required. Please, suggest me any correction.
add_action( 'woocommerce_after_checkout_billing_form','my_custom_checkout_field', 10, 1 );
function my_custom_checkout_field( $checkout ) {
echo '<div id="my_custom_checkout_field">
' . __('Gender') . '';
woocommerce_form_field( 'city_custom', array(
'required' => 'true',
'clear' =>'true',
'type' => 'select',
'options' => array(
'' => __( 'Select city' ),
'Kiribathgoda' => __('Male', 'woocommerce' ),
'Wattala' => __('Female', 'woocommerce' )),
'class' => array('my-field-class form-row-wide'),
), $checkout->get_value( 'city_custom' ));
echo '</div>';
}
// Save the dropdown custom field selected value as order custom meta data:
add_action( 'woocommerce_checkout_create_order', 'my_custom_checkout_field_update_order_meta', 10, 2 );
function my_custom_checkout_field_update_order_meta( $order, $data ) {
if ( isset($_POST['city_custom']) && ! empty($_POST['city_custom']) ) {
$order->update_meta_data( 'city', sanitize_text_field( $_POST['city_custom'] ) );
}
}
// Display the custom field value on admin order pages after billing adress:
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta( $order ) {
echo '<p><strong>'.__('Gender').':</strong> ' . $order->get_meta('Gender') . '</p>';
}
// Display the custom field value on email notifications:
add_action( 'woocommerce_email_after_order_table', 'custom_woocommerce_email_order_meta_fields', 10, 4 );
function custom_woocommerce_email_order_meta_fields( $order, $sent_to_admin, $plain_text, $email ) {
echo '<p><strong>'.__('Gender').':</strong> ' . $order->get_meta('gender') . '</p>';
} ```

I would like to add country of origin to products in woocommerce

Hi I would like to add country of origin while adding products and then sort products based on country of origin
Can I achieve this?
Add these functions to your theme's 'functions.php'.
Display & Save the Custom Field in Admin
// display field in admin
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_country_field');
function woocommerce_product_country_field()
{
global $woocommerce, $post;
$countries_obj = new WC_Countries();
$options = $countries_obj->__get('countries');
echo '<div class="product_country_field">';
woocommerce_wp_select(
array(
'id' => '_country_origin',
'label' => __('Country of origin', 'woocommerce'),
'options' => $options,
'desc_tip' => 'true'
)
);
echo '</div>';
}
// save fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_country_fields_save');
function woocommerce_product_country_fields_save($post_id)
{
$woocommerce_country_origin = $_POST['_country_origin'];
if (!empty($woocommerce_country_origin))
update_post_meta($post_id, '_country_origin', esc_attr($woocommerce_country_origin));
}
Sort by Custom Field in Front-End
// sort field
function custom_add_country_ordering_args( $sort_args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
switch( $orderby_value ) {
case '_country_origin':
$sort_args['orderby'] = 'meta_value';
$sort_args['order'] = 'asc';
$sort_args['meta_key'] = '_country_origin';
break;
case '_country_origin-desc':
$sort_args['orderby'] = 'meta_value';
$sort_args['order'] = 'desc';
$sort_args['meta_key'] = '_country_origin';
break;
}
return $sort_args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_add_country_ordering_args' );
//change sort dropdown
function custom_add_country_orderby( $sortby ) {
//remove default sorting
unset($sortby["popularity"]);
unset($sortby["rating"]);
unset($sortby["date"]);
unset($sortby["price"]);
unset($sortby["price-desc"]);
$sortby['_country_origin'] = __( 'Sort by Country of origin', 'woocommerce' );
$sortby['_country_origin-desc'] = __( 'Sort by Country of origin descending', 'woocommerce' );
return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_add_country_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_add_country_orderby' );
Please note that the products which has 'Country of origin' will only be displayed while sorting.
Filter by Custom Field in Front-End
Add this if you want filter rather than sort.
//add custom filter
add_action( 'woocommerce_before_shop_loop', 'filter_loop_start' );
function filter_loop_start( $query ){
$countries_obj = new WC_Countries();
$options = $countries_obj->__get('countries');
?>
<form name="product_filter_form" class="woocommerce-filtering" method="get">
<select name="country_origin" class="filterby" onChange="document.product_filter_form.submit();">
<option value="">Filter by Country of origin</option>
<?php foreach ($options as $key => $value) { ?>
<option value="<?php echo $key; ?>"<?php if($_GET['country_origin']==$key) echo ' selected'; ?>><?php echo $value; ?></option>
<?php } ?>
</select>
<input name="paged" value="1" type="hidden">
</form>
<?php
}
//modify query for filter
add_filter( 'pre_get_posts', 'my_modify_main_query' );
function my_modify_main_query( $query ) {
if( ! isset( $_GET['country_origin'] ) ) return $query;
$meta_query_args = array(
'meta_query' => array(
array(
'key' => '_country_origin',
'value' => sanitize_text_field( $_GET['country_origin'] ),
'compare' => 'LIKE',
)
)
);
$query->set('meta_query', $meta_query_args);
return $query;
}

Output error with get_post_meta in woocommerce

I am trying to add a custom metabox in woocommerce. It has been added perfectly. My ultimate goal is to call that custom field in a function and show it in the cart.php. So I coded :
For Custom field: [I would refer http://www.remicorson.com/mastering-woocommerce-products-custom-fields/] in this regard
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_text_input(
array(
'id' => 'number_field',
'label' => __( '<strong style="color:#239804">Your Free Products</strong>', 'woocommerce' ),
'placeholder' => '',
'description' => __( 'Please enter a number', 'woocommerce' ),
'type' => 'number',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
echo '</div>';
}//woo_add_custom_general_fields
function woo_add_custom_general_fields_save( $post_id ){
$woocommerce_number_field = $_POST['number_field'];
if( !empty( $woocommerce_number_field ) )
update_post_meta( $post_id, 'number_field', esc_attr( $woocommerce_number_field ) );
}//woo_add_custom_general_fields_save( $post_id )
It has perfectly fitted in the Product Admin Page. Now I am creating another function where I am creating a counter for cart.php
function free_products(){
global $woocommerce ,$product, $post;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$free_number = get_post_meta( $post->ID, 'number_field', true );
$free_product = $cart_item['quantity'] * $free_number;
echo apply_filters( 'woocommerce_cart_item_quantity', $free_product, $cart_item_key );
}
}
In My cart.php when I add
<td class="product-quantity">
<?php
echo free_products();
?>
</td>
The output become zero in front end. Can anyone please help me what I am going wrong. Thanks in advance.
Try below code :
function free_products(){
global $woocommerce ,$product, $post;
foreach ( WC()->cart->get_cart() as $cart_item ) {
$my_var = $cart_item['product_id'];
$free_number = get_post_meta( $my_var, 'number_field', true );
$free_product = $cart_item['quantity'] * $free_number;
echo apply_filters( 'woocommerce_cart_item_quantity', $free_product);
}
}
Let me know if It is working for you or not.Its working for me.

Hierarchical taxonomy dropdown wordpress

I have some custom taxonomies built in theme, and on the taxonomy dropdown, taxonomies are not showed in hierarchy. It just show a dropdown list of all taxonomies, but not in hierarchical order.
This is what I've got:
register_taxonomy(
'recipesets',
'recipe',
array(
'public'=>true,
'hierarchical' => true,
'labels'=> $labels,
'query_var' => 'recipesets',
'show_ui' => true,
'rewrite' => array( 'slug' => 'recipesets', 'with_front' => false ),
)
);
}
and calling:
<label for="edit-title" class="control-label"><i class="fa fa-folder-o"></i><?php _e('Category:', 'agrg') ?></label>
<select name="cat" id="cat" class="postform">
<?php
$terms = get_terms("recipesets", "orderby=count&hide_empty=0");
if ( !is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
echo "<option value='" . $term->name . "'>" . $term->name . "</option>";
}
}
?>
</select>
What to do?
Why not use the Wordpress function wp_dropdown_categories() which does all the work for you
$tax_args = array(
'taxonomy' => 'destination',
'orderby' => 'name',
'show_count' => 1,
'hierarchical' => 1,
);
wp_dropdown_categories($tax_args);
This is how I would do it:
<?php
/** The taxonomy we want to parse */
$taxonomy = "category";
/** Get all taxonomy terms */
$terms = get_terms($taxonomy, array(
"orderby" => "count",
"hide_empty" => false
)
);
/** Get terms that have children */
$hierarchy = _get_term_hierarchy($taxonomy);
?>
<select name="terms" id="terms">
<?php
/** Loop through every term */
foreach($terms as $term) {
/** Skip term if it has children */
if($term->parent) {
continue;
}
echo '<option value="' . $term->name . '">' . $term->name . '</option>';
/** If the term has children... */
if($hierarchy[$term->term_id]) {
/** ...display them */
foreach($hierarchy[$term->term_id] as $child) {
/** Get the term object by its ID */
$child = get_term($child, "category");
echo '<option value="' . $term->name . '"> - ' . $child->name . '</option>';
}
}
}
?>
</select>

WP Front End Form Not Saving My Custom Taxonomies

I am trying to create a front end posting form through wordpress that will allow users to create a post when schools are closed. I have 4 custom taxonomies closed_schools, study_open, safe_arrival, hour_delay. each has the same list of 3o or so schools. The problem is that I can't display which schools have been selected under there categories after the post is created. If I build the post in the back end it works, just not from the front end, SO I know there is something wrong with how I am storing the taxonomies. Any suggestion are very welcomed, thanks
My Front End Form Template
if(isset($_POST['submit'])){
$title = $_POST['title'];
$description = $_POST['description'];
$category = $_POST['cat'];
$tags = $_POST['post_tags'];
$terms = $_POST['terms'];
$error_msg = array();
if($title == ''){
$error_msg[] = 'Please select an area and/or region.';
}
if($description == ''){
$error_msg[] = 'Please write a description for the closure and/or delay.';
}
if($category == '-1'){
$error_msg[] = 'Please identify the reason for the closure and/or delay.';
}
else if( !$error_msg && 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post"){
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags),
'tax_input' => array(
'closed_schools' => $_POST['terms'],
'study_open' => $_POST['terms'],
'safe_arrival' => $_POST['terms'],
'hour_delay' => $_POST['terms'],
),
'post_status' => 'publish', // Choose: publish, preview, future, draft, etc.
'post_type' => 'post', //'post',page' or use a custom post type if you want to
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
//SET OUR TAGS UP PROPERLY
wp_set_post_tags($pid, $_POST['post_tags']);
//SET OUR POST TERMS, CUSTOM TAXONOMIES
wp_set_post_terms($pid, $_POST['terms'], 'closed_schools', 'safe_open', 'safe_arrival', 'hour_delay', true);
//REDIRECT TO THE NEW POST ON SAVEs
$link = get_permalink( $pid );
wp_redirect( $link );
//POST THE POST
do_action('wp_insert_post', 'wp_insert_post');
}
}
Inside the Form I display the schools in check boxes from the 4 taxonomies like so. I just change the names out for each taxonomy I am showing.
<fieldset>
<label for="closed_schools" class="selection-title">Closed Schools:</label>
<?php
$closed_schools = get_terms('closed_schools', 'orderby=id&hide_empty=0');
$counter = 0;
foreach ($closed_schools as $close) {
$counter++;
$option = '<label for="'.$close->slug.'">'.$close->name.'</label>';
$option .= '<input type="checkbox" name="terms[]" id="'.$close->slug.'" value="'.$close->slug.'">';
echo $option;
}
?>
</fieldset>
Finally I show output the terms on loop.php and single.php
<?php echo get_the_term_list( $post->ID, 'closed_schools', '<strong>Closed Schools:</strong> ', ', ', '' ); ?>
<?php echo get_the_term_list( $post->ID, 'study_open', '<strong>Open For Study Purposes Only:</strong> ', ', ', '' ); ?>
<?php echo get_the_term_list( $post->ID, 'safe_arrival', '<strong>Open for Students Who Can Ariive Safely:</strong> ', ', ', '' ); ?>
<?php echo get_the_term_list( $post->ID, 'hour_delay', '<strong>2 Hour Delay:</strong> ', ', ', '' ); ?>
I figured it out! Here is my answer.
I needed to use wp_set_object_terms instead of wp_set_post_terms for each and it worked
//SET OUR POST TERMS, CUSTOM TAXONOMIES
wp_set_object_terms($pid, $_POST['terms'], 'closed_schools');
wp_set_object_terms($pid, $_POST['terms'], 'study_open');
wp_set_object_terms($pid, $_POST['terms'], 'safe_arrival');
wp_set_object_terms($pid, $_POST['terms'], 'hour_delay');

Resources