Custom Checkout Field for Woocommerce with dynamic options - wordpress

I want to have dynamic options for my checkout dropdown field. The options must be users of specific roles that are in WordPress users. How can I achieve it? Below is the code that I am working with. In the first function, we can get all administrator users. I want users to be in options of the dropdown in the select field of checkout.
**User Roles**
function get_users_by_role($role, $orderby, $order) {
$args = array(
'role' => 'administrator',
'orderby' => 'user_nicename',
'order' => 'ASC'
);
$users = get_users( $args );
return $users;
}
**Dropdown Field**
function everest_custom_dropdown_fields( $fields ) {
$fields['everestmerchant_extra_dropdown_fields']['dropdown'] = array(
'label' => __('Leader Name', 'woocommerce'),
'placeholder' => _x('Leader Name', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array( 'wps-drop' ),
'clear' => true,
'type' => 'select',
'options' => array(
'option 1' => __('option 1', 'woocommerce' ),
'option 2' => __('option 2', 'woocommerce'
)//end of options
);
return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'everest_custom_dropdown_fields' );

Get All Leaders
function get_leaders($role) {
$args = array(
'role' => $role,
'orderby' => 'user_nicename',
'order' => 'ASC'
);
$leaders = ['' => 'Please Select'];
$users = get_users( $args );
if($users){
foreach($users as $user){
$leaders[$user->data->ID] = $user->data->display_name;
}
}
return $leaders;
}
Add Leader field in checkout page
function leader_name_select_field( $checkout ){
woocommerce_form_field( 'leader_name', array(
'type' => 'select',
'required' => true,
'class' => array('form-row-wide'),
'label' => 'Leader Name',
'options' => get_leaders('administrator')
), $checkout->get_value( 'leader_name' ) );
}
add_action( 'woocommerce_after_checkout_billing_form', 'leader_name_select_field' );
Save Selected field in database.
function save_leader_name_of_order( $order_id ){
if( !empty( $_POST['leader_name'] ) )
update_post_meta( $order_id, 'leader_name', sanitize_text_field( $_POST['leader_name'] ) );
}
add_action( 'woocommerce_checkout_update_order_meta', 'save_leader_name_of_order' );
Show saved field in order page in dashboard
function leader_name_show_on_order_detail_page($order){
$leader_id = get_post_meta($order->get_id(), 'leader_name', true );
$leader = get_user_by( 'ID', $leader_id );
if($leader_id && $leader){
echo '<p class="form-field form-field-wide">';
echo '<label>Leader Name</label>';
echo '<p> ' . $leader->data->display_name . '</p>';
echo '</p>';
}
}
add_action( 'woocommerce_admin_order_data_after_order_details', 'leader_name_show_on_order_detail_page', 10, 1 );

Related

User Selection for Order

I am assigning a manager to an order with the code below. But I do this with manual IDs. What I want to do is "wp_dropdown_users(['role' => 'shop_manager']);" To make a selection with dropdown. How should I go about this.
woocommerce_wp_select( array(
'id' => '_store_manager_id',
'label' => 'Manager:',
'value' => $manager,
'options' => array(
'1' => 'Manager 1',
'2' => 'Manager 2',
'3' => 'Manager 3'
),
'wrapper_class' => 'form-field-wide'
) );
add_action( 'woocommerce_process_shop_order_meta', 'manager_save' );
function manager_save( $order_id ){
update_post_meta( $order_id, '_store_manager_id', wc_clean( $_POST[ '_store_manager_id' ] ) );
// wc_clean() and wc_sanitize_textarea() are WooCommerce sanitization functions
}

Can't add a section to a Woocommerce Custom Setting Tab [duplicate]

I'm trying to add a custom settings tab to the WooCommerce settings screen. Basically I want to achieve a similar thing to the Products settings tab, with the subsections/subtabs:
I haven't been able to find any decent documentation on how to do this but I've been able to add a custom tab using this snippet:
class WC_Settings_Tab_Demo {
public static function init() {
add_filter( 'woocommerce_settings_tabs_array', __CLASS__ . '::add_settings_tab', 50 );
}
public static function add_settings_tab( $settings_tabs ) {
$settings_tabs['test'] = __( 'Settings Demo Tab', 'woocommerce-settings-tab-demo' );
return $settings_tabs;
}
}
WC_Settings_Tab_Demo::init();
Based on what I've dug up from various threads/tutorials, I've been trying to add the sections/subtabs to the new settings tab something like this:
// creating a new sub tab in API settings
add_filter( 'woocommerce_get_sections_test','add_subtab' );
function add_subtab( $sections ) {
$sections['custom_settings'] = __( 'Custom Settings', 'woocommerce-custom-settings-tab' );
$sections['more_settings'] = __( 'More Settings', 'woocommerce-custom-settings-tab' );
return $sections;
}
// adding settings (HTML Form)
add_filter( 'woocommerce_get_settings_test', 'add_subtab_settings', 10, 2 );
function add_subtab_settings( $settings, $current_section ) {
// $current_section = (isset($_GET['section']) && !empty($_GET['section']))? $_GET['section']:'';
if ( $current_section == 'custom_settings' ) {
$custom_settings = array();
$custom_settings[] = array( 'name' => __( 'Custom Settings', 'text-domain' ),
'type' => 'title',
'desc' => __( 'The following options are used to ...', 'text-domain' ),
'id' => 'custom_settings'
);
$custom_settings[] = array(
'name' => __( 'Field 1', 'text-domain' ),
'id' => 'field_one',
'type' => 'text',
'default' => get_option('field_one'),
);
$custom_settings[] = array( 'type' => 'sectionend', 'id' => 'test-options' );
return $custom_settings;
} else {
// If not, return the standard settings
return $settings;
}
}
I've been able to add new subsections to the Products tab using similar code to the above, but it isn't working for my new custom tab. Where am I going wrong here?
1) To add a setting tab with sections, you can firstly use the woocommerce_settings_tabs_array filter hook:
// Add the tab to the tabs array
function filter_woocommerce_settings_tabs_array( $settings_tabs ) {
$settings_tabs['my-custom-tab'] = __( 'My custom tab', 'woocommerce' );
return $settings_tabs;
}
add_filter( 'woocommerce_settings_tabs_array', 'filter_woocommerce_settings_tabs_array', 99 );
2) To add new sections to the page, you can use the woocommerce_sections_{$current_tab} composite hook where {$current_tab} need to be replaced by the key slug that is set in the first function:
// Add new sections to the page
function action_woocommerce_sections_my_custom_tab() {
global $current_section;
$tab_id = 'my-custom-tab';
// Must contain more than one section to display the links
// Make first element's key empty ('')
$sections = array(
'' => __( 'Overview', 'woocommerce' ),
'my-section-1' => __( 'My section 1', 'woocommerce' ),
'my-section-2' => __( 'My section 2', 'woocommerce' )
);
echo '<ul class="subsubsub">';
$array_keys = array_keys( $sections );
foreach ( $sections as $id => $label ) {
echo '<li>' . $label . ' ' . ( end( $array_keys ) == $id ? '' : '|' ) . ' </li>';
}
echo '</ul><br class="clear" />';
}
add_action( 'woocommerce_sections_my-custom-tab', 'action_woocommerce_sections_my_custom_tab', 10 );
3) For adding the settings, as well as for processing/saving, we will use a custom function, which we will then call:
// Settings function
function get_custom_settings() {
global $current_section;
$settings = array();
if ( $current_section == 'my-section-1' ) {
// My section 1
$settings = array(
// Title
array(
'title' => __( 'Your title 1', 'woocommerce' ),
'type' => 'title',
'id' => 'custom_settings_1'
),
// Text
array(
'title' => __( 'Your title 1.1', 'text-domain' ),
'type' => 'text',
'desc' => __( 'Your description 1.1', 'woocommerce' ),
'desc_tip' => true,
'id' => 'custom_settings_1_text',
'css' => 'min-width:300px;'
),
// Select
array(
'title' => __( 'Your title 1.2', 'woocommerce' ),
'desc' => __( 'Your description 1.2', 'woocommerce' ),
'id' => 'custom_settings_1_select',
'class' => 'wc-enhanced-select',
'css' => 'min-width:300px;',
'default' => 'aa',
'type' => 'select',
'options' => array(
'aa' => __( 'aa', 'woocommerce' ),
'bb' => __( 'bb', 'woocommerce' ),
'cc' => __( 'cc', 'woocommerce' ),
'dd' => __( 'dd', 'woocommerce' ),
),
'desc_tip' => true,
),
// Section end
array(
'type' => 'sectionend',
'id' => 'custom_settings_1'
),
);
} elseif ( $current_section == 'my-section-2' ) {
// My section 2
$settings = array(
// Title
array(
'title' => __( 'Your title 2', 'woocommerce' ),
'type' => 'title',
'id' => 'custom_settings_2'
),
// Text
array(
'title' => __( 'Your title 2.2', 'text-domain' ),
'type' => 'text',
'desc' => __( 'Your description 2.1', 'woocommerce' ),
'desc_tip' => true,
'id' => 'custom_settings_2_text',
'css' => 'min-width:300px;'
),
// Section end
array(
'type' => 'sectionend',
'id' => 'custom_settings_2'
),
);
} else {
// Overview
$settings = array(
// Title
array(
'title' => __( 'Overview', 'woocommerce' ),
'type' => 'title',
'id' => 'custom_settings_overview'
),
// Section end
array(
'type' => 'sectionend',
'id' => 'custom_settings_overview'
),
);
}
return $settings;
}
3.1) Add settings, via the woocommerce_settings_{$current_tab} composite hook:
// Add settings
function action_woocommerce_settings_my_custom_tab() {
// Call settings function
$settings = get_custom_settings();
WC_Admin_Settings::output_fields( $settings );
}
add_action( 'woocommerce_settings_my-custom-tab', 'action_woocommerce_settings_my_custom_tab', 10 );
3.2) Process/save the settings, via the woocommerce_settings_save_{$current_tab} composite hook:
// Process/save the settings
function action_woocommerce_settings_save_my_custom_tab() {
global $current_section;
$tab_id = 'my-custom-tab';
// Call settings function
$settings = get_custom_settings();
WC_Admin_Settings::save_fields( $settings );
if ( $current_section ) {
do_action( 'woocommerce_update_options_' . $tab_id . '_' . $current_section );
}
}
add_action( 'woocommerce_settings_save_my-custom-tab', 'action_woocommerce_settings_save_my_custom_tab', 10 );
Result:
Based on:
Implement a custom WooCommerce settings page, including page sections
woocommerce/includes/admin/settings/

Add woocommerce variation GTIN to structured data

If a webshop has variable products, in some cases the variations have unique GTINs. In our case, it is EAN.
How to add these different GTINS to the structured data? I made a function to insert multiple "offer" in "offers", but the GTIN is not recognized here.
This is the function:
//add structured data to the markup
function set_structured_data( $markup, $product ) {
if ($product->is_type('simple')){
$markup['brand'] = array('#type' => 'Brand', 'name' => get_post_meta( $product->get_id(), '_brand', true ) );
$markup['gtin8'] = get_post_meta( $product->get_id(), '_EAN', true );
}
if ($product->is_type('variable')){
$available_variations = $product->get_available_variations();
foreach ($available_variations as $variation) {
$variation_id = $variation['variation_id'];
$variproduct = wc_get_product($variation_id);
$i++;
$stock = $product->get_stock_status();
$offers[] = array(
'type' => 'Offer',
'price' => $variproduct->get_price(),
'priceValidUntil' => $priceuntil,
'priceSpecification' => array(
'price' => $variproduct->get_price(),
'priceCurrency' => get_woocommerce_currency(),
'valueAddedTaxIncluded' => 'http://schema.org/True'
),
'priceCurrency' => get_woocommerce_currency(),
'availability' => 'http://schema.org/'.$stock.'',
'url' => get_the_permalink(),
'seller' => array (
'type' => 'Organization',
'name' => 'HeatPerformance®',
'url' => get_the_permalink(),
));
}
$markup['offers'] = $offers;
$markup['brand'] = array('#type' => 'Brand', 'name' => get_post_meta( $product->get_id(), '_brand', true ) );
}
return $markup;
}
add_filter( 'woocommerce_structured_data_product', 'set_structured_data', 99, 2 );
Any ideas?
Ok after a couple of days puzzling i found the path to a solution here:
https://support.google.com/merchants/answer/6386198?hl=en
Result is that i corrected the standardized method from woocommerce and made each variation a unique product.
So first remove the markup in case of a variable product like this:
function set_structured_data( $markup, $product ) {
if ($product->is_type('variable')) {
$markup = array();
}
return $markup;
}
add_filter( 'woocommerce_structured_data_product', 'set_structured_data', 99, 2 );
And then build up the ld+json script again, but then the desired way:
function set_structured_data_variable() {
global $product;
if (isset($product)){
if ($product->is_type('variable') && !empty($product)){
$available_variations = $product->get_available_variations();
$date = date("Y-m-d",strtotime(" + 3months"));
$commenttext = '';
$commentauthor = '';
$commentdate = '';
$comments = get_comments(array( 'post_id' => $product->get_id(), 'number' => '1' ));
foreach($comments as $comment) {
$commenttext = $comment->comment_content;
$commentauthor = $comment->comment_author;
$commentdate = $comment->comment_date;
}
foreach ($available_variations as $variation) {
$variation_id = $variation['variation_id'];
$variproduct = wc_get_product($variation_id);
$i++;
$gtin = 0000000000001;
if (!empty(get_post_meta( $variation_id, '_EAN', true ))){
$gtin = get_post_meta( $variation_id, '_EAN', true );
}
$stock = $product->get_stock_status();
$arrays[$i] = array(
'#context' => 'https://schema.org/',
'#type' => 'Product',
'sku' => $variproduct->get_sku(),
'gtin13' => $gtin,
'image' => get_the_post_thumbnail_url($product->get_id()),
'name' => implode(" / ", $variproduct->get_variation_attributes()),
'description' => wp_strip_all_tags(get_the_excerpt($product->get_id())),
'brand' => array('#type' => 'Brand', 'name' => get_post_meta( $product->get_id(), '_brand', true ) ),
'review' => array(
'#type' => 'Review',
'reviewRating' => array (
'#type' => 'Rating',
'ratingValue' => $product->get_review_count(),
'bestRating' => '5',
'worstRating' => '1',
),
'author' => array(
'#type' => 'person',
'name' => $commentauthor,
'reviewBody' => $commenttext,
'datePublished' => $commentdate,
)),
'aggregateRating' => array (
'#type' => 'AggregateRating',
'ratingValue'=> $product->get_average_rating(),
'reviewCount' => $product->get_rating_count(),
),
'inProductGroupWithID' => $product->get_sku(),
'offers' => array(
'#type' => 'Offer',
'price' => $variproduct->get_price(),
'priceValidUntil' => $date,
'priceSpecification' => array(
'price' => $variproduct->get_price(),
'priceCurrency' => get_woocommerce_currency(),
'valueAddedTaxIncluded' => 'http://schema.org/True'
),
'priceCurrency' => get_woocommerce_currency(),
'availability' => 'http://schema.org/'.$stock.'',
'url' => get_the_permalink(),
'seller' => array (
'type' => 'Organization',
'name' => 'HeatPerformance®',
'url' => get_the_permalink(),
)));
}
echo '<script type="application/ld+json" class="buronoort">[';
$i = 0;
foreach ($arrays as $array){
$i++;
echo json_encode($array);
if ($i < array_key_last($arrays)){
echo ',';
}
}
echo ']</script>';
}
}
}
add_action('wp_head','set_structured_data_variable', 19);
Tested in the test tool for structured data and it is working.
A little concern is the product review however, i have to look into that what happens after multiple reviews.
Another concern is the EAN, i have set it standard to "0000000000001" as not all EANS are inputted yet. So this is a debatle solution, but if someone has a better idea, keep me posted.

WordPress WooCommerce API: Update/insert custom taxonomy terms

I am trying to update a products custom taxonomy term via the wp-json api.
I have added the below function to handle taxonomies:
function wp_api_add_tax($post, $data, $update){
foreach( $data['custom_tax'] as $tax => $val ){
wp_set_post_terms( $post['ID'], $val, $tax );
}
}
add_filter('json_insert_post', 'wp_api_add_tax', 10, 3);
And then add then taxonomy term like this:
$api_response = wp_remote_post( 'https://example.com/wp-json/wc/v2/products/4286', array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'xxxxxxxxxxxx:xxxxxxxxxx' )
),
'body' => array(
'stock_quantity' => '0',
'categories' => array(
array(
'id' => 373
),
array(
'name' => 'Build Lean Muscle'
)
),
'custom_tax' => array(
'My Taxonomy Here' => 'My Term Here'
),
'meta_data' => array(
array(
'key' => 'nutritional',
'value' => 'nutritional description by the api 2'
)
)
)
) );
Is this the correct way of doing things? The custom taxonomy term does not get updated.

WordPress login form: rename label submit field

I have created login form for a shortcode. I could rename the label for the username and the submit field. But I would also like to rename the submit field. Any suggestions?
Php:
add_action( 'init', 'my_add_shortcodes' );
function my_add_shortcodes() {
add_shortcode( 'my-login-form', 'my_login_form_shortcode' );
}
function my_login_form_shortcode( $attr ) {
if ( is_user_logged_in() )
return 'you0re already logged in';
$defaults = array(
'label_username' => 'num dutilisader',
'label_password' => 'plaid clav'
);
$attr = shortcode_atts( $defaults, $attr );
$attr['echo'] = false;
return wp_login_form( $attr );
}
Shortcode:
[my-login-form label_username="num d'utilisader" label_password="plaid clav" label_submit="s'annunziar"]
You can try the attribute label_log_in for the submit text
you can see the available parameters in the following code
`function wpfa_login_form( $args ) {
$defaults = shortcode_atts( array(
'echo' => false,
'redirect' => site_url( '/wp-admin/' ),
'form_id' => 'loginform',
'label_username' => __( 'Username', 'wpfa-textdomain' ),
'label_password' => __( 'Password', 'wpfa-textdomain' ),
'label_remember' => __( 'Remember Me', 'wpfa-textdomain' ),
'label_log_in' => __( 'Log In', 'wpfa-textdomain' ),
'id_username' => 'user_login',
'id_password' => 'user_pass',
'id_remember' => 'rememberme',
'id_submit' => 'wp-submit',
'remember' => true,
'value_username' => NULL,
'value_remember' => false
), $args, 'wpfa_login' );
$login_args = wp_parse_args( $args, $defaults );
return wp_login_form( $login_args );
} add_shortcode( 'wpfa_login', 'wpfa_login_form' );`
Here you can create a shortcode: [wpfa_login label_log_in="Show Me The Way"].
You can try altering your code based on this

Resources