You can use a simple JavaScript code snippet to add the target=»_blank» attribute to your links in WordPress. This opens links in a new tab or window, enhancing user experience. Here’s how to do it:
- Access Your Theme’s Functions File:
- Go to your WordPress dashboard.
- Navigate to Appearance » Theme Editor.
- Find and open the functions.php file of your active theme.
- Add the JavaScript Code:
Insert the following code snippet into the functions.php file:
function add_blank_to_links() {
$jcode = <<<‘EOT’
<script type=«text/javascript»>
jQuery(document).ready(function($) {
$(‘a’).attr(‘target’, ‘_blank’);
});
</script>
EOT;
echo $jcode;
}
add_action(‘wp_footer’, ‘add_blank_to_links’);
- This code uses jQuery to select all <a> tags on your site and add the target=»_blank» attribute, making all links open in a new tab.
- After adding the code, click Update File to save your changes.
Important Notes
- Performance Consideration: The script is added to the footer, ensuring it runs after the page content loads, which helps maintain performance.
- Specific Links: If you want to apply this only to specific links (e.g., links within a certain <div>), modify the jQuery selector accordingly, such as $(‘#some_id a’) to target links within a specific element.
- Testing: After implementing the changes, visit your site to ensure links open in new tabs as expected.