Last active
February 21, 2024 06:44
-
-
Save hmowais/ef636b90ee3bb6959df3399c77a401d2 to your computer and use it in GitHub Desktop.
Get User Role Field in Woocommerce Product
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Add meta box to Products post type | |
function add_product_user_role_meta_box() { | |
add_meta_box( | |
'product_user_role_meta_box', | |
'User Role', | |
'render_product_user_role_meta_box', | |
'product', | |
'side', | |
'default' | |
); | |
} | |
add_action( 'add_meta_boxes', 'add_product_user_role_meta_box' ); | |
// Render meta box content | |
function render_product_user_role_meta_box( $post ) { | |
// Retrieve the selected user role for the current product | |
$selected_role = get_post_meta( $post->ID, '_product_user_role', true ); | |
// Get all user roles | |
$roles = wp_roles()->get_names(); | |
// Output the select box | |
?> | |
<label for="product_user_role">Select User Role:</label> | |
<select name="product_user_role" id="product_user_role"> | |
<?php foreach ( $roles as $role_id => $role_name ) : ?> | |
<option value="<?php echo esc_attr( $role_id ); ?>" <?php selected( $selected_role, $role_id ); ?>> | |
<?php echo esc_html( $role_name ); ?> | |
</option> | |
<?php endforeach; ?> | |
</select> | |
<?php | |
} | |
// Save meta box data in Product | |
function save_product_user_role_meta_box( $post_id ) { | |
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { | |
return; | |
} | |
if ( isset( $_POST['product_user_role'] ) ) { | |
$selected_role = sanitize_key( $_POST['product_user_role'] ); | |
update_post_meta( $post_id, '_product_user_role', $selected_role ); | |
} | |
} | |
add_action( 'save_post_product', 'save_product_user_role_meta_box' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment