Wordpress user profile display name - change from selectbox to textbox - wordpress

Im trying to change the user profile "Display name publicly as" from a select box to a textbox. Any ideas on how this can be done? Couldnt find anything all all.

Two way to solve it. You edit the wordpress core file, which is not a good way. Or you can add an extra field on profile box using wordpress hook.
I am giving you the first way:
Go to wp-admin/user-edit.php
Open the file. Then find
<td>
<select name="display_name" id="display_name">
<?php
$public_display = array();
$public_display['display_nickname'] = $profileuser->nickname;
$public_display['display_username'] = $profileuser->user_login;
if ( !empty($profileuser->first_name) )
$public_display['display_firstname'] = $profileuser->first_name;
if ( !empty($profileuser->last_name) )
$public_display['display_lastname'] = $profileuser->last_name;
if ( !empty($profileuser->first_name) && !empty($profileuser->last_name) ) {
$public_display['display_firstlast'] = $profileuser->first_name . ' ' . $profileuser->last_name;
$public_display['display_lastfirst'] = $profileuser->last_name . ' ' . $profileuser->first_name;
}
if ( !in_array( $profileuser->display_name, $public_display ) ) // Only add this if it isn't duplicated elsewhere
$public_display = array( 'display_displayname' => $profileuser->display_name ) + $public_display;
$public_display = array_map( 'trim', $public_display );
$public_display = array_unique( $public_display );
foreach ( $public_display as $id => $item ) {
?>
<option id="<?php echo $id; ?>"<?php selected( $profileuser->display_name, $item ); ?>><?php echo $item; ?></option>
<?php
}
?>
</select>
</td>
Change it with
<th><label for="display_name"><?php _e('Display name publicly as'); ?> </label></th>
<td><input type="text" name="display_name" id="display_name" value="<?php echo esc_attr( $profileuser->display_name ); ?>" class="regular-text" /></td>
But still this is not a good solution.

I came across this same issue and used a bit of javascript to solve it. Wordpress allows you to set the display_name field to anything you want, so you can use the following script (in your theme's functions.php file) to convert the select to a text field.
function change_display_name_to_textfield() {
echo "><div>"; // don't remove '>'
?>
<script>
jQuery(function($) {
// replace display_name select with input
$('select#display_name').after( '<input type="text" name="display_name" id="display_name" value="' + $('#display_name').val() + '" class="regular-text">' ).remove();
})
</script>
<?php
echo "</div"; // don't add '>'
}
// hook into new user and edit user pages
add_action( "user_new_form_tag", "change_display_name_to_textfield" );
add_action( "user_edit_form_tag", "change_display_name_to_textfield" );
Note the weird use of opening/closing tags. This is because those particular hooks execute just before the end of the opening form tag. So you need to close the form tag, print your script, then print a final tag without closing it.

For admin user edit pages, I found one of the easiest way:
add_action( 'personal_options', 'rm_personal_options' );
function rm_personal_options($profileuser){
if( !is_admin() ) return; ?>
<script type="text/javascript">
jQuery(document).ready(function($){
//$("input#nickname").parent().parent().hide();
$("select#display_name").replaceWith(function(){
return '<input type="text" name="display_name" id="display_name" value="'+$(this).val()+'" class="regular-text" style="width:25em" />';
});
});
</script>
<?php
}
Simply paste it into the functions.php of the theme file :)

Related

No access to the created input

I added an extra field to the cart.php using Snippet plugin.
function action_woocommerce_cart_coupon() {
echo '<input type="text" name="card" class="input-text" id="card" value="" placeholder="Card" />';
};
add_action( 'woocommerce_cart_coupon', 'action_woocommerce_cart_coupon');
And I would my own validation when the Apply coupon button is clicked. Unfortunately, There is no way I can get value of this new field.
I downloaded the post in several places but I don't have access to this field.
if ( ! empty( $_POST['card'] ) ) {
echo '<script>console.log("' . $_POST['card'] . '")</script>';
} else {
echo '<script>console.log("PHP error")</script>';
}
function action_woocommerce_applied_coupon( $coupon_code ) {
foreach ($_POST as $key => $value) {
echo '<script>console.log("' . $key . " " . $value . '")</script>';
}
};
add_action( 'woocommerce_applied_coupon', 'action_woocommerce_applied_coupon');
Output:
security ac228a43c2
coupon_code 1
I understand this is called in class-wc-cart.php but I can't understand how I could pass this field to this method. Is anyone able to tell me something about this?
I will also appreciate any other ideas to solve this problem.

Add plus and minus buttons to WooCommerce

WooCommerce decided to remove the + and - buttons from the product and cart pages to increase or decrease quantity. They say it was redundant to have and if anyone wants them back just install another plugin from them.
I, like others, don't wish to install a plugin when using code is the wiser option. Better yet, we should've been given the choice to keep them or not. I digress...
I've scoured the net for a solution, tried a couple, but no joy. Would really appreciate assistance with code needed to bring them back and where that code should be placed.
Found an answer on another thread here, though not sure exactly where it goes or if this is what I need to bring the buttons back
// Input +- tweak
$(function(a){
a(".woocommerce-ordering").on("change", "select.orderby", function(){
a(this).closest("form").submit();
}),
a("div.quantity:not(.buttons_added), td.quantity:not(.buttons_added)").addClass("buttons_added").append('<input type="button" value="+" class="plus" />').prepend('<input type="button" value="-" class="minus" />'), a("input.qty:not(.product-quantity input.qty)").each(function(){
var b=parseFloat(a(this).attr("min"));b&&b>0&&parseFloat(a(this).val())<b&&a(this).val(b);
}),
a(document).on("click", ".plus, .minus", function(){
var b=a(this).closest(".quantity").find(".qty"),
c=parseFloat(b.val()),
d=parseFloat(b.attr("max")),
e=parseFloat(b.attr("min")),
f=b.attr("step");c&&""!==c&&"NaN"!==c||(c=0),
(""===d||"NaN"===d)&&(d=""),
(""===e||"NaN"===e)&&(e=0),
("any"===f||""===f||void 0===f||"NaN"===parseFloat(f))&&(f=1),
a(this).is(".plus")?b.val(d&&(d==c||c>d)?d:c+parseFloat(f)):e&&(e==c||e>c)?b.val(e):c>0&&b.val(c-parseFloat(f)),
b.trigger("change");
});
});
Thanks in advance!
Yes, I know the issue, really anoying, every theme that I create I need to fix this... Here is how I did it:
Create a folder in your theme folder: /woocommerce/global/
Create a file: quantity-input.php
Put the following content inside this file:
<?php
/**
* Product quantity inputs
*
* #author WooThemes
* #package WooCommerce/Templates
* #version 2.1.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
?>
<div class="quantity">
<input type="text" pattern="[0-9]*" step="<?php echo esc_attr( $step ); ?>" <?php if ( is_numeric( $min_value ) ) : ?>min="<?php echo esc_attr( $min_value ); ?>"<?php endif; ?> <?php if ( is_numeric( $max_value ) ) : ?>max="<?php echo esc_attr( $max_value ); ?>"<?php endif; ?> name="<?php echo esc_attr( $input_name ); ?>" value="<?php echo esc_attr( $input_value ); ?>" title="<?php _ex( 'Qty', 'Product quantity input tooltip', 'moto' ) ?>" class="input-text qty text" size="4" />
<span class="td-quantity-button plus">+</span>
<span class="td-quantity-button min">-</span>
</div>
And of course you would need some jQuery to make the buttons work:
$('.td-quantity-button').on('click', function () {
var $this = $(this);
var $input = $this.parent().find('input');
var $quantity = $input.val();
var $new_quantity = 0;
if ($this.hasClass('plus')) {
var $new_quantity = parseFloat($quantity) + 1;
} else {
if ($quantity > 0) {
var $new_quantity = parseFloat($quantity) - 1;
}
}
$input.val($new_quantity);
});
Please note that you will have to style these buttons and input field yourself.
Please also note you need jquery enqueud in your theme or plugin:
function theme_name_scripts() {
wp_enqueue_script( 'jquery' );
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
If you want a clean solution to add "-" and "+" increment buttons to WooCommerce product and cart page, with easy customization options, I created a plugin which does it without overriding templates, through hooks only:
Qty Increment Buttons for WooCommerce
PHP and jQuery code is only part of solution, because multiple CSS manipulations are required to make these inserted buttons presentable. WooCommerce 3.0 comes with additional hooks for product page, so implementation is even easier, but they are not a must and I got it to work for older versions as well.
Here is my jQuery code:
// Make code work on page load (this js file is executed only on product and cart page).
$(document).ready(function(){
QtyChng();
});
// Make code work after executing AJAX on cart page. Support for default WooCommerce and plugins using AJAX on cart page.
$( document.body ).on( 'updated_cart_totals', function(){
QtyChng();
});
function QtyChng() {
$('.woocommerce form.cart, .woocommerce td.product-quantity').on( 'click', '.qib-button', function() {
// Find quantity input field corresponding to increment button clicked.
var qty = $( this ).siblings( '.quantity' ).find( '.qty' );
// Read value and attributes 'min', 'max', 'step'.
var val = parseFloat(qty.val());
var max = parseFloat(qty.attr( 'max' ));
var min = parseFloat(qty.attr( 'min' ));
var step = parseFloat(qty.attr( 'step' ));
// Change input field value if result is in min and max range.
if ( $( this ).is( '.plus' ) ) {
if ( val === max ) return false;
if ( val + step > max ) {
qty.val( max );
} else {
qty.val( val + step );
}
} else {
if ( val === min ) return false;
if ( val - step < min ) {
qty.val( min );
} else {
qty.val( val - step );
}
}
$( this ).siblings( '.quantity' ).find( '.qty' ).trigger("change");
});
}
})(jQuery);
<?php
/**
* Product quantity inputs
*
* #author WooThemes
* #package WooCommerce/Templates
* #version 2.1.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
?>
<div class="quantity">
<input type="text" pattern="[0-9]*" step="<?php echo esc_attr( $step ); ?>" <?php if ( is_numeric( $min_value ) ) : ?>min="<?php echo esc_attr( $min_value ); ?>"<?php endif; ?> <?php if ( is_numeric( $max_value ) ) : ?>max="<?php echo esc_attr( $max_value ); ?>"<?php endif; ?> name="<?php echo esc_attr( $input_name ); ?>" value="<?php echo esc_attr( $input_value ); ?>" title="<?php _ex( 'Qty', 'Product quantity input tooltip', 'moto' ) ?>" class="input-text qty text" size="4" />
<span class="td-quantity-button plus">+</span>
<span class="td-quantity-button min">-</span>
</div>

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.

Adding "Add Friend Button" anywhere in the buddypress site

I'm trying to place an "Add Friend" button outside of the members page, inside a loop, so the button appears next to the author's avatar in a post.
I tried adding ;
<?php if ( bp_is_active( 'friends' ) ) { ?>
<?php bp_add_friend_button( $user_ids['users'][$i]->id ) ?>
<?php } ?>
Inside the loop but it didn't return any results.
Then I placed the following action hook in functions.php, it displayed the button inside the loop but once clicked, all the buttons in the post list got clicked as well.
add_action( ‘the_content’, ‘bp_add_friend_button’, 5 );
So now I'm stuck. I thought, adding a template tag inside the template would work since it had worked for "Send Message" button.
try
<?php if ( function_exists( 'bp_add_friend_button' ) ) : ?>
<?php bp_add_friend_button() ?>
<?php endif; ?>
Here is an example that works for me, hope its helps.
$id_or_email = $result -> user_ID;
$avatar_default = get_avatar($id_or_email, $size, $default = '', $alt = '', $args = null);
$potential_friend_id = $id_or_email;
$friend_status = false;
$friend_button = bp_add_friend_button($potential_friend_id, $friend_status);
echo '<li>'. $avatar_default. $user_info->user_nicename . $friend_button . '</li> ';
There may be a plugin that solve this, but to followup on Rafa's solution.
This complete code worked for me.
In bp-custom.php ( this is a file you need to create)
function my_id_text_processor($friend_id)
{
//Return string id without 'uid-' attached
$search = 'uid-';
$replace_with = '';
return str_replace($search, $replace_with, $friend_id);
}
In the file you want the button to appear put this code.
< ?php $friend_id = my_id_text_processor(bp_get_group_invite_item_id()) ? >
$avatar_default = get_avatar($friend_id, $size, $default = '', $alt = '', $args = null);
$friend_status = false;
$friend_button = bp_add_friend_button($friend_id, $friend_status);
echo '<li>'. $avatar_default,bp_group_invite_user_link(),$friend_button . '</li> ';

Wordpress Settings API error

Hi I am trying to creating some custom options for a template I am developing but I seem to be getting an error:
Warning: Illegal string offset 'show_header' in C:\xampp\htdocs\wordpress\wp-content\themes\01MyWork\includes\theme-options.php on line 62
This is the line that seems to be throwing the error:
$html = '<input type="checkbox" id="show_header" name="thanathos_theme_display_options[show_header]" value="1" ' . checked(1, $options['show_header'], false) . '/>';
And this is the entire code:
<?php
function thanatos_theme_menu(){
add_theme_page(
"Thanathos Theme Options",
"Thanathos Theme",
"administrator",
"thanathos_theme_options",
"thanathos_theme_display_callback"
);
}
add_action('admin_menu' , 'thanatos_theme_menu');
function thanathos_theme_display_callback(){
?>
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>Sandbox Theme Options</h2>
<?php settings_errors(); ?>
<!--Create the form that will be used to render our options-->
<form method="post" action="options.php">
<?php settings_fields('thanathos_theme_display_options'); ?>
<?php do_settings_sections( 'thanathos_theme_display_options' ); ?>
<?php submit_button(); ?>
</form>
</div>
<?php
}
add_action('admin_init' , 'thanatos_initializa_theme_options');
function thanatos_initializa_theme_options(){
if( false == get_option( 'thanathos_theme_display_options' ) ) {
add_option( 'thanathos_theme_display_options' );
}
add_settings_section(
'general_settings_section',
'Thanatos Options',
'thanatos_general_options_callback',
'thanathos_theme_display_options'
);
add_settings_field(
'show_header',
'Header',
'thanathos_field_header_callback',
'thanathos_theme_display_options',
'general_settings_section',
array( // The array of arguments to pass to the callback. In this case, just a description.
'Activate this setting to display the header.'
)
);
register_setting('thanathos_theme_display_options', 'thanathos_theme_display_options');
}
function thanatos_general_options_callback(){
echo 'mergem la mare';
}
function thanathos_field_header_callback($args){
// First, we read the options collection
$options = get_option('thanathos_theme_display_options');
// Next, we update the name attribute to access this element's ID in the context of the display options array
// We also access the show_header element of the options collection in the call to the checked() helper function
$html = '<input type="checkbox" id="show_header" name="thanathos_theme_display_options[show_header]" value="1" ' . checked(1, $options['show_header'], false) . '/>';
// Here, we'll take the first argument of the array and add it to a label next to the checkbox
$html .= '<label for="show_header"> ' . $args[0] . '</label>';
echo $html;
}
?>
Yes, that's the problematic part:
if( false == get_option( 'thanathos_theme_display_options' ) ) {
add_option( 'thanathos_theme_display_options' );
}
That's the initial if statement at the beginning of the thanatos_initializa_theme_options() function.
You can find the solution in the very neat Theme Options API tut at http://wp.tutsplus.com/tutorials/theme-development/the-complete-guide-to-the-wordpress-settings-api-part-4-on-theme-options/#post-684925289
Or, more exactly more exactly in this article's comments section.
I'm pasting the Steve Bondy's smart solution here because for some reason making the page scroll to the appropriate comment doesn't work for me (in Chrome at least).
START quote
(...)One little issue I had - I followed along through reordering the code, up to just before adding the Social options. At that point I discovered that the code was broken. I would get an error like
Warning: Illegal string offset 'show_header' in ...\themes\Sandbox\functions.php
Warning: Illegal string offset 'show_content' in ...\themes\Sandbox\functions.php
Warning: Illegal string offset 'show_footer' in ...\themes\Sandbox\functions.php
It turns out that this error was caused by adding 'sandbox_theme_display_options' to the options table without giving it a value. If you change sandbox_initialize_theme_options as follows it will create and initialize the options, avoiding the error experienced by myself and others.
function sandbox_initialize_theme_options() {
// If the theme options don't exist, create them.
if( false == get_option( 'sandbox_theme_display_options' ) ) {
$options = array("show_header" => TRUE, "show_content" => TRUE, "show_footer" => TRUE);
add_option( 'sandbox_theme_display_options', $options);
} // end if
(...)
If the old code has been run the empty 'sandbox_theme_display_options' value must be deleted from the database first. Alternatively, the following code will also detect this case and correct it.
function sandbox_initialize_theme_options() {
// See if the options exist, and initialize them if they don't
$options = get_option( 'sandbox_theme_display_options' );
if( false == $options or $options == "" ) {
$options = array("show_header" => TRUE, "show_content" => TRUE, "show_footer" => TRUE);
update_option( 'sandbox_theme_display_options', $options);
} // end if
(...)
This checks for non-existant or empty options values and initializes the options using update_option instead of add_option.
EOF quote
You are using name="thanathos_theme_display_options[show_header]" in plain HTML. Probably you want to parse by PHP the string [show_header].
You may have to run:
delete_option('thanathos_theme_display_options');
during 'admin_init' if you think you have old plugin information mucking about in the database and need a fresh start.

Resources