For some reason after the latest update of WooCommerce, my taxonomy slugs have changed.
They've gone from:
www.mysite.com/genre/dance to www.mysite.com/pa_genre/dance
It may be that in the backend nothing has changed, but the visualization on the frontend has. This sudden change in URL's is affecting not only how my site is linked internally, but also externally and if not fixed rapidly Google will also pick up these 404 pages.
I've looked into WooCommerce files, not sure where to look, but wc-attribute-functions.php shows the following containing references to the 'pa_' bit.
If anyone has an idea to go back to my old URL structure, that would be greatly appreciated.
/**
* Get a product attributes name.
*
* #param mixed $name
* #return string
*/
function wc_attribute_taxonomy_name( $name ) {
return 'pa_' . wc_sanitize_taxonomy_name( $name );
}
/**
* Get a product attributes label.
*
* #param mixed $name
* #return string
*/
function wc_attribute_label( $name ) {
global $wpdb;
if ( taxonomy_is_product_attribute( $name ) ) {
$name = wc_sanitize_taxonomy_name( str_replace( 'pa_', '', $name ) );
$label = $wpdb->get_var( $wpdb->prepare( "SELECT attribute_label FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_name = %s;", $name ) );
if ( ! $label ) {
$label = ucfirst( $name );
}
} else {
$label = ucwords( str_replace( '-', ' ', $name ) );
}
return apply_filters( 'woocommerce_attribute_label', $label, $name );
}
/**
* Get a product attributes orderby setting.
*
* #param mixed $name
* #return string
*/
function wc_attribute_orderby( $name ) {
global $wpdb;
$name = str_replace( 'pa_', '', sanitize_title( $name ) );
$orderby = $wpdb->get_var( $wpdb->prepare( "SELECT attribute_orderby FROM " . $wpdb->prefix . "woocommerce_attribute_taxonomies WHERE attribute_name = %s;", $name ) );
return apply_filters( 'woocommerce_attribute_orderby', $orderby, $name );
}
I've had the same problem after Woocommerce 2.3.5 update, a quick fix would be adding a rewrite rule for the attributes.
You can add this to functions.php file in your theme:
add_action('init', 'add_genre_url');
function add_genre_url()
{
add_rewrite_rule(
'^genre/([^/]*)$',
'index.php?pa_genre=$matches[1]',
'top'
);
//flush_rewrite_rules();
}
The flush_rewrite_rules() function must be called at least once after you add the rewrite rule, it's not a great idea to leave it on the init action for performance reasons. Maybe someone can clear this out.
Related
I'm using the wpjobmanager plugin.
There's a field called 'company logo' that displays a default logo on every job. I'm trying to disable it and only show a logo when a user has specifically uploaded one.
I created this IF statement, but for some reason, the default logo is not considered empty so it continues to display it. I've tried null too and get the same result.
$is_logo = get_post($post->ID, '_company_logo', true);
if (!empty($is_logo)) {
the_company_logo();
}
Could someone point me in the right direction here? I'm at a loss.
Thanks
Here is the code for get_the_company_logo which returns empty string if not set.
/**
* Gets the company logo.
*
* #since 1.0.0
* #param int|WP_Post $post (default: null).
* #param string $size
* #return string Image SRC.
*/
function get_the_company_logo( $post = null, $size = 'thumbnail' ) {
$post = get_post( $post );
if ( has_post_thumbnail( $post->ID ) ) {
$src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), $size );
return $src ? $src[0] : '';
} elseif ( ! empty( $post->_company_logo ) ) {
// Before 1.24.0, logo URLs were stored in post meta.
return apply_filters( 'the_company_logo', $post->_company_logo, $post );
}
return '';
}
So if you did
if (!empty(get_the_company_logo($post->ID)){
the_company_logo();
}
This would seem like it should work. I am not using this plugin, so I can't really test this.
Try this the_company_logo() function:
if(!empty(the_company_logo())) {
get_the_company_logo()
}
I read this function here -> https://wpjobmanager.com/document/template-tags/.
Say me if you need some help.
My request is to provide a separate copyright field for images and to display the copyright information for each image. For this purpose I have inserted a separate field in the media library based on this source (https://bavotasan.com/2012/add-a-copyright-field-to-the-media-uploader-in-wordpress/)
/**
* Adding a "Copyright" field to the media uploader $form_fields array
*
* #param array $form_fields
* #param object $post
*
* #return array
*/
function add_copyright_field_to_media_uploader( $form_fields, $post ) {
$form_fields['copyright_field'] = array(
'label' => __('Copyright'),
'value' => get_post_meta( $post->ID, '_custom_copyright', true ),
'helps' => 'Set a copyright credit for the attachment'
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'add_copyright_field_to_media_uploader', null, 2 );
/**
* Save our new "Copyright" field
*
* #param object $post
* #param object $attachment
*
* #return array
*/
function add_copyright_field_to_media_uploader_save( $post, $attachment ) {
if ( ! empty( $attachment['copyright_field'] ) )
update_post_meta( $post['ID'], '_custom_copyright', $attachment['copyright_field'] );
else
delete_post_meta( $post['ID'], '_custom_copyright' );
return $post;
}
add_filter( 'attachment_fields_to_save', 'add_copyright_field_to_media_uploader_save', null, 2 );
/**
* Display our new "Copyright" field
*
* #param int $attachment_id
*
* #return array
*/
function get_featured_image_copyright( $attachment_id = null ) {
$attachment_id = ( empty( $attachment_id ) ) ? get_post_thumbnail_id() : (int) $attachment_id;
if ( $attachment_id )
return get_post_meta( $attachment_id, '_custom_copyright', true );
}
With the above code in place, you can now use the following snippet to display your attachment’s new “Copyright” field within one of your page templates.
<?php echo get_featured_image_copyright(); ?>
Unfortunately, this snippet is only available for featured-images.
How can I use this snippet for images and galleries within articles? Would that work with the codebase? If not, how would you solve this problem without plugins? I would be very grateful for your help.
It seems that you have a parameter in the function get_featured_image_copyright($attachment_id);.
So you can call the function with an image id :
get_featured_image_copyright($image_id);.
Example with a gallery:
while ( have_posts() ) : the_post();
if ( get_post_gallery() ) :
$gallery = get_post_gallery( get_the_ID(), false );
/* Loop through all the image and output copyright one by one */
foreach( $gallery['ids'] as $id ) :
echo get_featured_image_copyright($id);
endforeach;
endif;
endwhile;
No tested but you get the idea and i'm pretty sure i didn't made any typo
How can i create breadcrumb home->page->post name when we click on main menu any page, open the list of post that time breadcrumb create home ->page name its ok but now when we click on any post that time breadcrumb create home->post category name->post name is is that when we click on post category name on breadcrumb layout shown different we want to its goes on page link, not category link. so we need to when we open any post we need to create the breadcrumb like this home->page name->post name so when we click on page name open the post list page, not category page.
WordPress doesn't provide builtin breadcrumbs functionality. Thus you'll have to either use a plugin or else code it yourself (or copy from the reference below).
As a matter of fact, the plugin or custom code, if providing similar functionality, make not much of a difference. Thus use the one which is more convenient for you.
If you would like to add a custom code, here are few resources which I could look up on search:
https://www.techpulsetoday.com/wordpress-breadcrumbs-without-plugin/
https://www.thewebtaylor.com/articles/wordpress-creating-breadcrumbs-without-a-plugin
https://www.codexworld.com/wordpress-how-to-display-breadcrumb-without-plugin/
https://gist.github.com/tinotriste/5387124
You can look into them and modify them as you wish!
I hope it helps!
I can't understand how an answer with only pasted links can get to that many upvote. The regular WordPress breadcrumb approach is painfully unoptimized, most of the one out there do not suit custom themes. I decided to built a URL based breadcrumb which is, from my point of view, far more efficient and adaptable. I wanted something generic, SEO friendly, without any default styling. It needed also to properly handle posts and pages title.
Version
Requires at least WordPress:
5.0.0
Requires at least PHP:
7.0.0
Tested up to WordPress:
6.0.2
The latest version is available on my GitHub as an unofficial WordPress plugin.
<?php
/**
* Checks if a string ends with a given substring.
* Backward compatibility for PHP < 8.0.0.
*
* #since 1.2.0
* #param String $haystack The string to search in.
* #param String $needle The substring to search for in the haystack.
* #return Boolean
*/
if ( ! function_exists( 'backward_compatibility_str_ends_with' ) ) {
function backward_compatibility_str_ends_with( $haystack, $needle ) {
$length = strlen( $needle );
if ( ! $length ) {
return true;
};
return substr( $haystack, -$length ) === $needle;
};
};
/**
* Determine if a string contains a given substring.
* Backward compatibility for PHP < 8.0.0.
*
* #since 1.2.0
* #param String $haystack The string to search in.
* #param String $needle The substring to search for in the haystack.
* #return Boolean
*/
if ( ! function_exists( 'backward_compatibility_str_contains' ) ) {
function backward_compatibility_str_contains( $haystack, $needle ) {
if ( strpos( $haystack, $needle ) !== false ) {
return true;
};
};
};
/**
* Retrieve the crumbs.
*
* #since 1.0.0
* #return Array Crumbs array.
*/
if ( ! function_exists( 'get_the_crumbs' ) ) {
function get_the_crumbs() {
/**
* $_SERVER["REQUEST_SCHEME"] seems to be UNRELIABLE.
*
* Article "Is $_SERVER['REQUEST_SCHEME'] reliable?".
* #see https://stackoverflow.com/a/18008178/3645650
*
* $_SERVER['REQUEST_SCHEME'] is a native variable of Apache web server since its version 2.4.
* Naturally, if a variable is not set by the server, PHP will not include it in its global array $_SERVER.
*
* An alternative to $_SERVER['REQUEST_SCHEME'] is $_SERVER['HTTPS'] which set to a non-empty value if the script was queried through the HTTPS protocol.
*
* Article "How to find out if you're using HTTPS without $_SERVER['HTTPS']".
* #see https://stackoverflow.com/a/16076965/3645650
*/
if ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) {
$server_scheme = 'https';
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || ! empty( $_SERVER['HTTP_X_FORWARDED_SSL'] ) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ) {
$server_scheme = 'https';
} else {
$server_scheme = 'http';
};
/**
* $_SERVER["REQUEST_URI"] seems to be RELIABLE.
* $_SERVER['REQUEST_URI'] will not be empty in WordPress, because it is filled in wp_fix_server_vars() (file wp-includes/load.php).
*
* Article "Is it safe to use $_SERVER['REQUEST_URI']?".
* #see https://wordpress.stackexchange.com/a/110541/190376
*/
$server_uri = $_SERVER['REQUEST_URI'];
/**
* $_SERVER["HTTP_HOST"] seems to be RELIABLE.
*
* Article "How reliable is HTTP_HOST?".
* #see https://stackoverflow.com/a/4096246/3645650
*/
$server_host = $_SERVER["HTTP_HOST"];
if ( backward_compatibility_str_contains( $server_uri, '?' ) ) {
$server_uri = substr( $server_uri, 0, strpos( $server_uri, '?' ) );
};
if ( backward_compatibility_str_ends_with( $server_uri, '/' ) ) {
$server_uri = explode( '/', substr( $server_uri, 1, -1 ) );
} else {
$server_uri = explode( '/', substr( $server_uri, 1 ) );
};
$crumbs = array();
foreach ( $server_uri as $crumb ) {
$slug = esc_html( urldecode( $crumb ) );
$url = esc_url( $server_scheme . '://' . $server_host . '/' . substr( implode( '/', $server_uri ), 0, strpos( implode( '/', $server_uri ), $crumb ) ) . $crumb. '/' );
array_push( $crumbs,
array(
'slug' => $slug,
'url' => $url,
)
);
};
/**
* WordPress, by default, doesn't generate a taxonomy index, meaning https://.../taxonomy will redirect to a 404.
* Any request needs to be made against a term. eg: https://.../taxonomy/term will redirect to taxonomy.php.
* Therefore we need to remove the taxonomy slug from the crumbs array to avoid displaying a link to a 404.
*
* We round up all taxonomies through get_taxonomies().
* #see https://developer.wordpress.org/reference/functions/get_taxonomies/
*
* Through array_filter we filter-out any matching crumbs.
* #see https://www.php.net/manual/en/function.array-filter.php
*/
$banned_slugs = array();
$taxonomies = get_taxonomies(
array(
'public' => true,
),
'objects'
);
foreach ( $taxonomies as $taxonomy ) {
array_push( $banned_slugs, $taxonomy->name );
if ( isset( $taxonomy->rewrite['slug'] ) ) {
array_push( $banned_slugs, $taxonomy->rewrite['slug'] );
};
};
$banned_crumbs = array();
foreach ( $banned_slugs as $banned_slug ) {
$slug = esc_html( $banned_slug );
$url = esc_url( $server_scheme . '://' . $server_host . '/' . substr( implode( '/', $server_uri ), 0, strpos( implode( '/', $server_uri ), $banned_slug ) ) . $banned_slug. '/' );
array_push( $banned_crumbs,
array(
'slug' => $slug,
'url' => $url,
)
);
};
$crumbs = array_filter( $crumbs, function( $crumb ) use ( $banned_slugs ) {
if ( ! in_array( $crumb['slug'], $banned_slugs ) && ! in_array( $crumb['url'], $banned_slugs ) ) {
return ! in_array( $crumb['slug'], $banned_slugs );
};
} );
return $crumbs;
};
};
/**
* Display the bread, a formatted crumbs list.
*
* #since 1.0.0
* #param Array $ingredients The bread arguments.
* #param Array $ingredients['crumbs'] The crumbs array. Default to get_the_crumbs().
* #param Array $ingredients['root'] Root crumb. Default to null.
* #param String $ingredients['root']['slug'] Root crumb slug.
* #param String $ingredients['root']['url'] Root crumb url.
* #param String $ingredients['separator'] The crumb's separator.
* #param Integer $ingredients['offset'] Crumbs offset. Accept positive/negative Integer. Default to "0". Refer to array_slice, https://www.php.net/manual/en/function.array-slice.php.
* #param Integer $ingredients['length'] Crumbs length. Accept positive/negative Integer. Default to "null". Refer to array_slice, https://www.php.net/manual/en/function.array-slice.php.
* #return Array The formatted crumbs list.
*/
if ( ! function_exists( 'the_bread' ) ) {
function the_bread( $ingredients = array() ) {
if ( empty( $ingredients['crumbs'] ) ) {
$crumbs = get_the_crumbs();
} else {
$crumbs = $ingredients['crumbs'];
};
if ( empty( $ingredients['root'] ) ) {
$root = null;
} else {
$root = $ingredients['root'];
};
if ( empty( $ingredients['offset'] ) ) {
$offset = 0;
} else {
$offset = $ingredients['offset'];
};
if ( empty( $ingredients['length'] ) ) {
$length = null;
} else {
$length = $ingredients['length'];
};
/**
* Handling the root crumb case.
* Prepend one or more elements to the beginning of an array.
* #see https://www.php.net/manual/en/function.array-unshift.php
*/
if ( ! empty( $root ) ) {
array_unshift( $crumbs, $ingredients['root'] );
};
/**
* Handling the length case.
* Extract a slice of the array.
* #see https://www.php.net/manual/en/function.array-slice.php
*/
$crumbs = array_slice( $crumbs, $offset, $length );
if ( ! empty( $crumbs ) ) {
echo '<ol class="🍞 bread" itemscope itemtype="https://schema.org/BreadcrumbList">';
$i = 0;
foreach ( $crumbs as $crumb ) {
$i++;
/**
* Unparsing the slug.
*/
if ( url_to_postid( $crumb['url'] ) ) {
$title = get_the_title( url_to_postid( $crumb['url'] ) );
} elseif ( get_page_by_path( $crumb['slug'] ) ) {
$title = get_the_title( get_page_by_path( $crumb['slug'] ) );
} else {
$title = ucfirst( str_replace( '-', ' ', $crumb['slug'] ) );
};
echo '<li class="crumb" itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
<a itemprop="item" href="' . $crumb['url'] . '">
<span itemprop="name">' . $title . '</span>
</a>
<meta itemprop="position" content="' . $i . '">
</li>';
if ( $i !== sizeof( $crumbs ) && ! empty( $ingredients['separator'] ) ) {
echo $ingredients['separator'];
};
};
echo '</ol>';
};
};
};
Displaying the bread, a formatted crumbs list.
<?php
the_bread( $ingredients = array() );
Parameters
Parameter
Description
$ingredients
(Optional) Array The bread arguments.
$ingredients['crumbs']
Array The crumbs array. Default to get_the_crumbs().
$ingredients['root']
Array Root crumb. Default to null.
$ingredients['root']['slug']
(Required if $ingredients['root']). Root crumb slug.
$ingredients['root']['url']
(Required if $ingredients['root']). Root crumb url.
$ingredients['separator']
The crumb's separator.
$ingredients['offset']
Crumbs offset. Accept positive/negative Integer. Default to 0. Refer to array_slice.
$ingredients['length']
Crumbs length. Accept positive/negative Integer. Default to null. Refer to array_slice.
Example: The bread with a custom separator
<?php
$ingredients = array(
'separator' => '→',
);
the_bread( $ingredients );
Example: Displaying the last 3 crumbs
<?php
$ingredients = array(
'offset' => -3,
'length' => 3,
);
the_bread( $ingredients );
Example: The bread with a root crumb
<?php
$ingredients = array(
'root' => array(
'slug' => 'home',
'url' => get_home_url(),
),
);
the_bread( $ingredients );
Example: Intercepting the crumbs array
<?php
//Intercept the crumbs array...
$crumbs = get_the_crumbs();
//... Do something with it:
//In our case we're appending a new crumb to the crumbs array.
array_push( $crumbs, array(
'slug' => 'search',
'url' => 'https://.../search/',
) );
$ingredients = array(
'crumbs' => $crumbs,
);
the_bread( $ingredients );
HTML5 structure output
<ol class="🍞 bread" itemscope="" itemtype="https://schema.org/BreadcrumbList">
<li class="crumb" itemprop="itemListElement" itemscope="" itemtype="https://schema.org/ListItem">
<a itemprop="item" href="http://example.com/where/">
<span itemprop="name">Where</span>
</a>
<meta itemprop="position" content="1">
</li>
>
<li class="crumb" itemprop="itemListElement" itemscope="" itemtype="https://schema.org/ListItem">
<a itemprop="item" href="http://example.com/where/is/">
<span itemprop="name">Is</span>
</a>
<meta itemprop="position" content="2">
</li>
>
<li class="crumb" itemprop="itemListElement" itemscope="" itemtype="https://schema.org/ListItem">
<a itemprop="item" href="http://example.com/where/is/my/">
<span itemprop="name">My</span>
</a>
<meta itemprop="position" content="3">
</li>
>
<li class="crumb" itemprop="itemListElement" itemscope="" itemtype="https://schema.org/ListItem">
<a itemprop="item" href="http://example.com/where/is/my/bread/">
<span itemprop="name">Bread</span>
</a>
<meta itemprop="position" content="4">
</li>
</ol>
Minimal css boilerplate (Optional)
.🍞,
.bread {
list-style-type: none;
margin:0;
padding:0;
}
.🍞 li,
.bread li {
display:inline-block;
}
.🍞 li.crumb:last-child a,
.bread li.crumb:last-child a {
text-decoration: none;
pointer-events: none;
color: inherit;
}
Retrieving the crumbs
Even tho we recommend you to use the_bread() function to display and build your own breadcrumb, you can use get_the_crumbs() to retrieve the crumbs object.
Example: Outputting the crumbs object
<?php
var_dump( get_the_crumbs() );
A minimalistic breadcrumbs generator in a few lines as a filter:
add_filter( 'my_get_breadcrumbs', [ $this, 'the_breadcrumbs' ], 10, 1 );
/**
* Returns a list of all the breadcrumbs for the current page.
* usage: apply_filters( 'my_get_breadcrumbs', false )
*
* #param $max_depth int
*
* #return string
*/
function the_breadcrumbs() {
$crumbs = '';
$current_page_id = get_the_ID();
$parent = wp_get_post_parent_id( $current_page_id );
$index = 0;
while ( $parent ) {
$index ++;
$crumbs = '<li>' . get_the_title( $parent ) . '</li>' . $crumbs;
$parent = wp_get_post_parent_id( $parent );
if ( $index > 10 ) {
break;
}
}
return $crumbs . '<li><a>' . get_the_title( $current_page_id ) . '</a></li>';
}
We have the following arrangement for a housing website which has plots (aka houses) which are grouped into developments.
So, the actual structure might look like this
WINDY HILLS
1 Sunnydale Road
2 Sunnydale Road
10 Sunnydale Road
SUDDEN VALLEY
1 Sudden Valley
2 Sudden Valley
The slug I would like for these pages would be:
www.website.com/sudden-valley
www.website.com/sudden-valley/1-sudden-valley
I've tried multiple approaches to this. I think a custom post type of 'plots' with a taxonomy of 'developments' would work best. However I cannot figure out how to get the taxonomy term into the url. I always end up with something like www.website.com/developments/sudden-valley
Aside from slugs, I'm pretty savvy with custom post types / taxonomies, so happy to try anything suggested - consider this a blank slate. Any help much appreciated.
Generate a permalink for a taxonomy term
Parameters
$term
(object|int|string) (Required) The term object, ID, or slug whose link will be retrieved.
$taxonomy
(string) (Optional) Taxonomy.
Default value: ''
Source #
File: wp-includes/taxonomy.php
function get_term_link( $term, $taxonomy = '' ) {
global $wp_rewrite;
if ( !is_object($term) ) {
if ( is_int( $term ) ) {
$term = get_term( $term, $taxonomy );
} else {
$term = get_term_by( 'slug', $term, $taxonomy );
}
}
if ( !is_object($term) )
$term = new WP_Error('invalid_term', __('Empty Term'));
if ( is_wp_error( $term ) )
return $term;
$taxonomy = $term->taxonomy;
$termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
$slug = $term->slug;
$t = get_taxonomy($taxonomy);
if ( empty($termlink) ) {
if ( 'category' == $taxonomy )
$termlink = '?cat=' . $term->term_id;
elseif ( $t->query_var )
$termlink = "?$t->query_var=$slug";
else
$termlink = "?taxonomy=$taxonomy&term=$slug";
$termlink = home_url($termlink);
} else {
if ( $t->rewrite['hierarchical'] ) {
$hierarchical_slugs = array();
$ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
foreach ( (array)$ancestors as $ancestor ) {
$ancestor_term = get_term($ancestor, $taxonomy);
$hierarchical_slugs[] = $ancestor_term->slug;
}
$hierarchical_slugs = array_reverse($hierarchical_slugs);
$hierarchical_slugs[] = $slug;
$termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
} else {
$termlink = str_replace("%$taxonomy%", $slug, $termlink);
}
$termlink = home_url( user_trailingslashit($termlink, 'category') );
}
// Back Compat filters.
if ( 'post_tag' == $taxonomy ) {
/**
* Filters the tag link.
*
* #since 2.3.0
* #deprecated 2.5.0 Use 'term_link' instead.
*
* #param string $termlink Tag link URL.
* #param int $term_id Term ID.
*/
$termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
} elseif ( 'category' == $taxonomy ) {
/**
* Filters the category link.
*
* #since 1.5.0
* #deprecated 2.5.0 Use 'term_link' instead.
*
* #param string $termlink Category link URL.
* #param int $term_id Term ID.
*/
$termlink = apply_filters( 'category_link', $termlink, $term->term_id );
}
/**
* Filters the term link.
*
* #since 2.5.0
*
* #param string $termlink Term link URL.
* #param object $term Term object.
* #param string $taxonomy Taxonomy slug.
*/
return apply_filters( 'term_link', $termlink, $term, $taxonomy );
}
There are also plugins like Custom Post Type Permalinks that can do this for you.
When people are buying a product through the WooCommerce extension, I have enabled that they can create an account on checkout. I don't let them choose their own username and password.
Now I see that WP uses some part of the emailaddress to create a username, and the display name is based on the first name filled in on checkout.
Now I want to change that:
username must be the complete emailaddress [SOLVED];
display name must be the first name + last name [UNSOLVED].
I tried this: for display name with my 'no knowledge' of PHP:
add_filter('pre_user_display_name', 'wsis_pre_user_display_name');
function wsis_pre_user_display_name($display_name) {
$first = get_user_field("billing_first_name");
$last = get_user_field("billing_last_name");
$display_name = $first . $last;
return $display_name;
}
This filter is mentioned in their codex: http://codex.wordpress.org/Function_Reference/wp_update_user. But no examples and my code didn't work. Anybody can help?
In user.php wp-includes folder I found the filter, now get it working :-).
/**
* Filter a user's display name before the user is created or updated.
*
* #since 2.0.3
*
* #param string $display_name The user's display name.
*/
$display_name = apply_filters( 'pre_user_display_name', $display_name );
if ( empty($description) )
$description = '';
Second try did something! It left the display name completely empty:
add_filter('pre_user_display_name', 'pre_user_display_name');
function pre_user_display_name($display_name) {
$first = get_the_author_meta('first_name');
$last = get_the_author_meta('last_name');
$display_name = $first . $last;
return $display_name;
}
Am I on the right track?
To set the username as complete email address, you can add following code in functions.php file of your theme.
add_filter('woocommerce_new_customer_data','change_username');
function change_username($user_data)
{
return array(
'user_login' => $user_data['user_email'],
'user_pass' => $user_data['user_pass'],
'user_email' => $user_data['user_email'],
'role' => 'customer'
);
}
Here is how to set the display name to first name + last name.
// Sets the display name to first name and last name
add_filter( 'pre_user_display_name' , 'default_display_name' );
function default_display_name($name) {
if ( isset( $_POST['billing_first_name'] ) ) {
$firstname = sanitize_text_field( $_POST['billing_first_name'] );
}
if ( isset( $_POST['billing_last_name'] ) ) {
$lastname = sanitize_text_field( $_POST['billing_last_name'] );
}
$name = $firstname . ' ' . $lastname;
return $name;
}
Source : http://geektamin.com/blog/533/why-update_user_meta-display_name-doesnt-work-and-how-to-use-pre_user_display_name-instead/