Add Snippet To Project
Are you finding the ‘title’ attribute on your WordPress site unnecessary or simply not fitting the aesthetic you’re going for? While the title attribute can bring some benefits, in certain cases, it may become an unwanted feature. Whether you need to remove it for design purposes, or to enhance your website’s usability, this guide will show you how to effectively remove the title attribute in WordPress. Let’s dive in!
function wpturbo_remove_title_attribute($output) {
return preg_replace('/s*titles*=s*(["']).*?1/', '', $output);
}
add_filter('wp_nav_menu', 'wpturbo_remove_title_attribute');
add_filter('wp_page_menu', 'wpturbo_remove_title_attribute');
add_filter('wp_list_categories', 'wpturbo_remove_title_attribute');
In the provided PHP code snippet, a new function, wpturbo_remove_title_attribute()
, is defined. This function is created to remove the title
attribute which often appears in several WordPress core functions.
function wpturbo_remove_title_attribute($output) {
return preg_replace('/s*titles*=s*(["']).*?1/', '', $output);
}
The wpturbo_remove_title_attribute($output)
function accepts one parameter, $output
, which is the HTML output of a WordPress navigation menu, page menu, or list of categories.
Within this function, the PHP function preg_replace()
is used to perform a regular expression search and replace operation on the $output
parameter. The goal is to search for every instance of the title
attribute and replace it with blank space (”). The title
attribute in HTML is used to hold extra information about an element and usually displays as tooltip text.
The regular expression '/s*titles*=s*(["']).*?1/'
is used to accurately find any title
attribute within the $output
. This regular expression matches any instance of the title
attribute, regardless of the spaces around the equals sign, or whether single or double quotes are used.
Finally, the modified function is hooked into various WordPress actions via add_filter()
function. This function hooks a function wpturbo_remove_title_attribute()
onto a specific filter action, wp_nav_menu
, wp_page_menu
, and wp_list_categories
, changing the behavior of these core WordPress functions.
add_filter('wp_nav_menu', 'wpturbo_remove_title_attribute');
add_filter('wp_page_menu', 'wpturbo_remove_title_attribute');
add_filter('wp_list_categories', 'wpturbo_remove_title_attribute');
So, whenever WordPress generates a navigation menu, a page menu, or a list of categories, the title
attribute will be removed from the HTML output. As a result, the output of these actions would be free of title
attributes.