I'm using a function to display logged-in user name in wordpress navigation menu and I would like to also display logged-in user avatar in the menu but couldn't find a way to do this. So I'm asking for some help :)
Here is the function I'm using for the name:
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
if ( '#current-username#' == $menu_item->title ) {
global $shortcode_tags;
if ( isset( $shortcode_tags['current-username'] ) ) {
// Or do_shortcode(), if you must.
$menu_item->title = call_user_func( $shortcode_tags['current-username'] );
}
}
}
return $menu_items;
}
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
I have this code in my functions.php and I call it with #current-username# in a menu item, is there a way to customise this code to also output the avatar? Thanks for any help.
try this : echo get_avatar( $id_or_email, $size, $default, $alt );
you can display user name as like.
add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 10, 2 );
function your_custom_menu_item ( $items, $args ) {
$current_user = wp_get_current_user();
if(!empty($current_user->user_login))
$items .= '<li>'.$current_user->user_login.'</li>';
return $items;
}
Related
Wordpress - functions.php
I'm using this function to automatically add custom structure in url for posts in a specific categorie.
But now I would like to know how I could add multiple categories without having to copy this function over and over.
Other solution could be to have this function work for the parent post category and all child categories.
// url structure
add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
// Get the category for the post
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "b" ) {
$cat_name = strtolower($category[0]->cat_name);
$permalink = trailingslashit( home_url('/questions/' . $post->post_name .'/' ) );
}
return $permalink;
}
add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
'b/([^/]+)(?:/([0-9]+))?/?$',
'index.php?category_name=b&name=$matches[1]&page=$matches[2]',
'top' // The rule position; either 'top' or 'bottom' (default).
);
}
I am using WordPress and WooCommerce and I have followed this article https://rudrastyh.com/woocommerce/my-account-menu.html to add new menu items in WooCommerce my account menus.
This is my working code.
function getUserRolesByUserId( $id ) {
if ( !is_user_logged_in() ) { return false; }
$oUser = get_user_by( 'id', $id );
$aUser = get_object_vars( $oUser );
$sRoles = $aUser['roles'];
return $sRoles;
}
function createMenuBasedonUserRole($userId)
{
$userRoleIds = getUserRolesByUserId(get_current_user_id());
$urlMenuData = [];
if(!empty($userRoleIds) && in_array('mindesk_var_account',$userRoleIds)) {
$urlMenuData = [
'pageName' => "Clients",
"pageLink" => "clients"
];
} else if(!empty($userRoleIds) && in_array('mindesk_owner_account',$userRoleIds)) {
$urlMenuData = [
'pageName' => "Children",
"pageLink" => "children"
];
}
return $urlMenuData;
}
/*
* Step 1. Add Link (Tab) to My Account menu
*/
add_filter ( 'woocommerce_account_menu_items', 'mindesk_clients_children_link', 40 );
function mindesk_clients_children_link( $menu_links ){
$urlData = createMenuBasedonUserRole(get_current_user_id());
if(!empty($urlData)){
$menu_links = array_slice( $menu_links, 0, 5, true ) + array( $urlData['pageLink'] => $urlData['pageName'] ) + array_slice( $menu_links, 5, NULL, true );
}
return $menu_links;
}
/*
* Step 2. Register Permalink Endpoint
*/
add_action( 'init', 'mindesk_add_menu_endpoint' );
function mindesk_add_menu_endpoint() {
add_rewrite_endpoint( 'clients', EP_PAGES );
add_rewrite_endpoint( 'children', EP_PAGES );
}
/*
* Step 3. Content for the new page in My Account, woocommerce_account_{ENDPOINT NAME}_endpoint
*/
add_action( 'woocommerce_account_clients_endpoint', 'mindesk_clients_my_account_endpoint_content' );
function mindesk_clients_my_account_endpoint_content() {
require_once(get_template_directory() . '/myaccount/clients.php') ;
}
add_action( 'woocommerce_account_children_endpoint', 'mindesk_children_my_account_endpoint_content' );
function mindesk_children_my_account_endpoint_content() {
require_once(get_template_directory() . '/myaccount/children.php') ;
}
/* Step 4
*/
// Go to Settings > Permalinks and just push "Save Changes" button.
And this is my how my new menu called as "Clients" showing.
As you can see above, I have added new menu and executing the page and based on user role mindesk_var_account I need to show clients and mindesk_owner_account I need to show children.
I have created these 2 php pages at /wp-content/themes/twentytwentyone/myaccount and its working fine.
However, I want to use wp_die or something if user with another role try to access one of the page which they are not allowed to.
So for example if logged in user has mindesk_var_account role then if they try to go to http://localhost/wordpress/my-account/clients/ then i need to use wp_die() to not execute it.
I tried to use wp_die inside these new 2 pages but then menus and other things executed. I just want something like this.
I tried to use following code...
add_action( 'template_redirect', 'my_account_redirect' );
function my_account_redirect() {
if( is_page( 'my-account' ) ) {
wp_die('fg');
}
}
But then its checking for all my-account pages .. and I want it to be checked only for inner pages like client or children.
Can someone guide me how can I achieve this what should I do from here on.
Thanks
There are still some little mistakes in your code, some missing things and since WooCommerce 3 there are some related changes within step 2 for My account endpoints. Some things can be simplified too.
To avoid non allowed user roles to access to some prohibited section(s) or endpoint(s) you can use a custom function hooked in template_redirect hook that will redirect user to an allowed section.
Here is the complete code:
// Custom function that get My account menu item data based on user roles
function get_menu_item_by_user_role() {
$user_roles = wp_get_current_user()->roles;
if ( ! empty($user_roles) ) {
$menu_item = [];
// if ( in_array('mindesk_var_account', $user_roles) ) {
if ( in_array( 'mindesk_var_account', $user_roles ) ) {
$menu_item = [ 'clients' => __( "Clients", "woocommerce" ) ];
}
elseif( in_array( 'mindesk_owner_account', $user_roles ) ) {
$menu_item = [ 'children' => __( "Children", "woocommerce" ) ];
}
}
return $menu_item;
}
// Step 1 - Add Link (Tab) to My Account menu
add_filter ( 'woocommerce_account_menu_items', 'add_mindesk_custom_menu_items', 40 );
function add_mindesk_custom_menu_items( $menu_items ){
$new_item = get_menu_item_by_user_role();
if ( ! empty($new_item) ) {
$menu_items = array_slice( $menu_items, 0, 5, true ) + $new_item + array_slice( $menu_items, 5, null, true );
}
return $menu_items;
}
// Step 2 - Enable endpoint (and endpoint permalink) - Since WooCommerce 3
add_filter( 'woocommerce_get_query_vars', 'add_mindesk_menu_item_endpoint' );
function add_mindesk_menu_item_endpoint( $query_vars ) {
$query_vars['clients'] = 'clients';
$query_vars['children'] = 'children';
return $query_vars;
}
// Step 3. Content for the new page in My Account, woocommerce_account_{ENDPOINT NAME}_endpoint
add_action( 'woocommerce_account_clients_endpoint', 'add_mindesk_account_clients_endpoint_content' );
function add_mindesk_account_clients_endpoint_content() {
require_once(get_template_directory() . '/myaccount/clients.php') ;
}
add_action( 'woocommerce_account_children_endpoint', 'add_mindesk_account_children_endpoint_content' );
function add_mindesk_account_children_endpoint_content() {
require_once(get_template_directory() . '/myaccount/children.php') ;
}
// Step 4. Endpoint page title
add_filter( 'woocommerce_endpoint_clients_title', 'set_mindesk_account_clients_endpoint_title', 10, 2 );
function set_mindesk_account_clients_endpoint_title( $title, $endpoint ) {
$title = __("Clients", "woocommerce" );
return $title;
}
add_filter( 'woocommerce_endpoint_children_title', 'set_mindesk_account_children_endpoint_title', 10, 2 );
function set_mindesk_account_children_endpoint_title( $title, $endpoint ) {
$title = __( "Children", "woocommerce" );
return $title;
}
// Step 5. Redirect if not allowed user role
add_action( 'template_redirect', 'redirect_mindesk_account_dashboard' );
function redirect_mindesk_account_dashboard() {
if ( is_account_page() ) {
global $wp;
$item_key = array_keys(get_menu_item_by_user_role());
$page_url = get_permalink( get_option('woocommerce_myaccount_page_id') );
if ( empty($item_key) && ( isset($wp->query_vars['children']) || isset($wp->query_vars['clients']) ) ) {
wp_safe_redirect( get_permalink($page_id) );
exit();
}
elseif ( 'clients' == reset($item_key) && isset($wp->query_vars['children']) ) {
wp_safe_redirect( get_permalink($page_id) . 'clients/' );
exit();
}
elseif ( 'children' == reset($item_key) && isset($wp->query_vars['clients']) ) {
wp_safe_redirect( get_permalink($page_id) . 'children/' );
exit();
}
}
}
// Step 6. FLush rewrite rules:
// Go to Settings > Permalinks and click on "Save Changes".
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
related: WooCommerce My Account custom endpoint menu item
Based on Change WooCommerce products menu title in WordPress admin dashboard answer by 7uc13r, I am trying to understand how to change WooCommerce into Store.
I've tried with the following, without success:
#1: Debug, show the menu array on dashboard
function debug_admin_menus() {
global $menu, $submenu, $pagenow;
if ( current_user_can('manage_options') ) {
if( $pagenow == 'index.php' ) { // print on dashboard
echo '<pre>', print_r( $menu, 1 ), '</pre>'; // top level menus
echo '<pre>', print_r( $submenu, 1 ), '</pre>'; // submenus
}
}
}
add_action( 'admin_notices', 'debug_admin_menus' );
#2: change the name and submenu name (WooCommerce won't change, "All products" does)
function custom_change_admin_label() {
global $menu, $submenu;
$menu[70][0] = 'Store';
$submenu['edit.php?post_type=product'][5][0] = 'All Plugins';
}
add_action( 'admin_menu', 'custom_change_admin_label' );
This should suffice to change WooCommerce into Store
function custom_change_admin_label() {
global $menu, $submenu;
// Change WooCommerce to Store
$menu['55.5'][0] = 'Store';
}
add_action( 'admin_menu', 'custom_change_admin_label' );
In conjunction with your previous question you will get:
function custom_change_admin_label() {
global $menu, $submenu;
// Change 'WooCommerce' to 'Store'
$menu['55.5'][0] = 'Store';
// Change 'All Products' to 'All Plugins'
$submenu['edit.php?post_type=product'][5][0] = 'All Plugins';
// Contains the URI of the current page.
$current_url = $_SERVER['REQUEST_URI'];
// Make sure wc-admin / customers page will still work
if ( strpos( $current_url, 'customers' ) == false) {
// Remove 'Home' from WooCommerce menu
remove_submenu_page( 'woocommerce', 'wc-admin' );
}
}
add_action( 'admin_menu', 'custom_change_admin_label', 99, 0 );
I am trying to hide product attributes in woocommerce based on product title. currently I have code that removes the attributed based on category. It works fine for what it is, but I would prefer to use title and a strpos array instead.
Here is the code that allows me to remove attributes based on categories
add_action( 'wp', 'remove_product_content11' );
function remove_product_content11() {
if ( has_term( array('Flush Mount', 'Semi Flush'), 'product_cat' ) ) {
function mycode_hide_attributes_from_additional_info_tabs( $attributes, $product ) {
$hidden_attributes = [
'pa_item-length-or-depth',
'pa_item-minimum-height',
];
foreach ( $hidden_attributes as $hidden_attribute ) {
if ( ! isset( $attributes[ $hidden_attribute ] ) ) {
continue;
}
$attribute = $attributes[ $hidden_attribute ];
$attribute->set_visible( false );
}
return $attributes;
}
add_filter( 'woocommerce_product_get_attributes', 'mycode_hide_attributes_from_additional_info_tabs', 20, 2 );
}
}
I would just like to change this code so It uses strpos to search though the product title, instead of using category.
check this code, tell me if it helps.
add_action( 'wp', 'remove_product_content11' );
function remove_product_by_strpos_title() {
global $post;
// check if its a product page, so the code is not executed for every page
// and check if title contains 'my-title'
if ( is_product() && strpos('my-title', $post->post_title) ) {
function mycode_hide_attributes_from_additional_info_tabs( $attributes, $product ) {
$hidden_attributes = [
'pa_item-length-or-depth',
'pa_item-minimum-height',
];
foreach ( $hidden_attributes as $hidden_attribute ) {
if ( ! isset( $attributes[ $hidden_attribute ] ) ) {
continue;
}
$attribute = $attributes[ $hidden_attribute ];
$attribute->set_visible( false );
}
return $attributes;
}
add_filter( 'woocommerce_product_get_attributes', 'mycode_hide_attributes_from_additional_info_tabs', 20, 2 );
}
}
I'm using Wordpress with UserPro, and want my menu to display the logged-in user's first name, linked to the user profile page.
The problem is that in my menu structure, the "Profile" menu option is supposed to have a sub-menu containing "edit profile", "submit", and "logout".
This is my current code:
/*earlier code, currently commented out, for function to
display username in menu using #profile_name# placeholder
function give_profile_name($atts){
echo userpro_profile_data('first_name', get_current_user_id());
}
add_shortcode('profile_name', 'give_profile_name');
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
if ( '#profile_name#' == $menu_item->title ) {
global $shortcode_tags;
if ( isset( $shortcode_tags['profile_name'] ) ) {
// Or do_shortcode(), if you must.
$menu_item->title = call_user_func( $shortcode_tags['profile_name'] );
}
}
}
return $menu_items;
}
end of earlier code */
//currently in use, unlinked code
add_filter( 'wp_nav_menu_items', 'my_custom_menu_item');
function my_custom_menu_item($items)
{
if(is_user_logged_in())
{
$user=wp_get_current_user();
$name=$user->user_firstname;
$items .= '<li>'.$name.'';
}
return $items;
}
?>
I can fiddle around and try to add the sub-menu under the menu by fiddling with the code from Firebug, but that would mean manual edits to all the links in the functions.php, which would be tedious.
I want to be able to add, edit, remove, and redirect the sub-menu items easily via the Wordpress menu.
Please advise.
Okay, I found a solution (and it can be used for any theme, with any plugin as it only uses core WordPress functions).
In the menu, name the menu item where you want the user's name to appear with a place-holder (such as: #profile_name#, #user#, #random#, etc.)
Now, add the following code to the your child-theme's functions.php:
function give_profile_name($atts){
$user=wp_get_current_user();
$name=$user->user_firstname;
return $name;
}
add_shortcode('profile_name', 'give_profile_name');
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
if ( '#profile_name#' == $menu_item->title ) {
global $shortcode_tags;
if ( isset( $shortcode_tags['profile_name'] ) ) {
// Or do_shortcode(), if you must.
$menu_item->title = call_user_func( $shortcode_tags['profile_name'] );
}
}
}
return $menu_items;
}
In case you're using your own place-holder, remember to replace #profile_name# with the name of your custom place-holder in the code above.
Apologies in case I've misused the term 'place-holder'.