How to set nofollow rel attribute to all outbound links in WordPress? Any Plugin? - wordpress

I want to know how to automatically set all links to nofollow in Wordpress. Is there a WP Plugin that will make all my outbound links nofollow?
Help is greatly appreciated!

If you are make this change for SEO optimization, you can't make the change only with JS because the google bots don't read the content generated by Javascript.
But, you can add a filter in your function.php like this:
function rel_nofollow( $content ) {
return preg_replace_callback( '/<a[^>]+/', 'rel_nofollow_callback', $content );
}
add_filter( 'the_content', 'rel_nofollow', 99999 );
function rel_nofollow_callback( $matches ) {
$link = $matches[0];
$exclude = '('. home_url() .'|http://([^.]+\.)?(wp.org|wp.com))';
if ( preg_match( '#href=\S('. $exclude .')#i', $link ) )
return $link;
if ( strpos( $link, 'rel=' ) === false ) {
$link = preg_replace( '/(?<=<a\s)/', 'rel="nofollow" ', $link );
} elseif ( preg_match( '#rel=\S(?!nofollow)#i', $link ) ) {
$link = preg_replace( '#(?<=rel=.)#', 'nofollow ', $link );
}
return $link;
}
This function set all links into the post to the attribute: rel="nofollow", but, if you want change all the site maybe you must try with this plugin

A number of years later, the details changed but the question remains.
For one thing, the number of relevant rel attributes has grown:
nofollow alternatives sponsored and ugc
noopener, strongly suggested for security
noreferrer, less relevant with modern browser versions
external, XHTML valid, link to an external (different) site; not nofollow nor target="_blank", so dubious utility
somewhat related noindex
Disregard numerous examples in older posts of code snippets to tune rel= attributes, as simply hacking WordPress PHP is quite undesirable these days. With frequent and (optionally) automated core software and plugin updates, and with security plugins checking all the code for non-standard mods, let's focus on the UI and plugin configuration methods instead.
While the Classic editor gives an option to Open link in a new tab, current version of the Gutenberg editor in combination with Yoast also provides UI to select nofollow or sponsored.
For more controls there are plugins. The one mentioned in earlier answers is still around, named External Links and with 80K installs and an exclusive focus on the link attributes, plus link icons and WPMU.
A much more popular plugin, with 2M+ installs is All in One SEO (AIOSEO), which among many other features provides access to noindex and nofollow.
Perhaps the most popular among SEO plugins, with 5M+ installs is Yoast SEO, but current version provides no additional help with bulk nofollow, though it adds noopener, as documented, but apparently also noreferrer to external links automatically.
Discussion so far related to external links, as nofollow or noopener are not used for internal links. Instead, concerns about duplicate content or low quality (thin content) pages raise questions about which parts of the site navigation and interlinking to index. Yoast shines here, with fine grain support for indexing author, tag or category links and pages.
Beyond search engine interpretation of individual links, rel=canonical tag allows merging together treatment of multiple internal links that actually lead to the same page or post. We are only guessing how Google interprets our 'hints' about links and hope that Yoast and WordPress produce a structure that is digestible.
Whether a particular subset of the rel and SEO plugins mentioned, in combination with a particular version of your favorite editor can work reliably alongside each other, and how to sequence their combined workflow is entirely TBD. A safe and consistent way of iteratively making specific adjustments to subsets of external and groupings of internal links, with a special treatment of affiliate and associate links is TBD. How to tackle a substantial site already in production, and retroactively apply select auto-magical adjustments is TBD. Any detailed suggestions, links to specific information and best of all, actual experiences would be rather welcome.
How browsers and spiders actually traverse a WordPress site is controlled at a different system level. The popular plugin for HTTP redirection is conveniently called Redirection. URL rewriting in Apache web server is configured via .htaccess file. cPanel and several system plugins, e.g. Really Simple SSL or WordFence, have automation in their UI for some of the settings, though conflicts may need to be resolved manually. These subjects are best covered in depth elsewhere.
For coding affectionados, two earlier attempts at different approaches:
Much tighter jQuery implementation, compared with the one below.
Really old direct hack of the entire page HTML, fetched from DOM.

Within WordPress you can select to open a link in a new window. When this is selected WordPress adds an attribute target="_blank". This is what I usually do with outbound links. If so you can use jQuery to add the attribute rel="nofollow" like this
<script type="text/javascript">
$(document).ready(function() {
$('a[target="_blank"]').attr('rel', 'nofollow');
});
</script>

Related

How to remove unused CSS/JS and Improve server response time for WordPress website?

I've optimized my WordPress site performance and also checked its performance using web.dev
But still, have the following issues that I couldn't solve:
Remove unused CSS
Remove unused JS
Initial server response time was short
How can I Solve this issues?
Performance optimisation is a huge theme and probably can't be covered simply in one answer, but I still can point you to the right direction.
Remove unused CSS & JS
First, you have to determine what CSS and JS files you really load on each page, find out where they come from and think about whether you really need them or not. It often happens that a lot of heavy CSS & JS files are being loaded only for the sake of a simple animation that is used once somewhere on website. You can see all the files loaded in browser console, or with the help of services like GT Metrix. If you find assets that you don't need but they're still being loaded, first try to find a source (for example: a theme or a plugin) that loads them. Popular themes and plugins have settings for disabling some parts of assets so it's an easy one. For those that don't have any settings you can try this piece of code, just replace file names with yours.
add_action( 'wp_print_styles', 'remove_styles' );
add_action( 'wp_print_scripts', 'remove_scripts' );
// Remove styles from plugins we don't need
function remove_styles() {
if ( $GLOBALS['pagenow'] != 'wp-login.php' && ! is_user_logged_in() ) {
wp_dequeue_style( 'coblocks-frontend' );
wp_dequeue_style( 'coblocks-frontend-css' );
wp_dequeue_style( 'wp-editor-font' );
wp_dequeue_style( 'duplicate-post' );
wp_dequeue_style( 'thickbox' );
}
}
// Remove scripts from plugins we don't use and don't need
function remove_scripts() {
// just in case we use those in wp-admin, exclude only from front-end loading
if ( ! is_user_logged_in() ) {
wp_dequeue_script( 'coblocks-animation' );
wp_deregister_script( 'coblocks-animation' );
wp_dequeue_script( 'thickbox' );
wp_deregister_script( 'thickbox' );
wp_deregister_script('jquery');
}
}
Ideally you need to keep your CSS and JS as small as possible but it can be tricky in modern WP themes that use a lot of it.
Initial server response time
Long response time mean that your server takes too long to return any data. 99% of the times it is either because of badly-optimised website or a weak server. Latter can be easily solved by moving to another hosting provider or changing hosting plan.
Website optimisations are trickier and may require profiling, especially if you already have proper full page caching installed . Generally, I can describe all the general cases like this:
Slow server response + no caching = try caching first. WP Super Cache, WP Rocket or similar plugins.
Slow server response + caching = try hosting providers with nginx-caching support (basically serving static content on each page load). I can recommend Kinsta or Pressjitsu.
Slow server response + a lot of dynamic content = You can't cache things the same way as regular websites. Here you need an experienced dev who should first profile you website with tools like xhprof or blackfire.io and then gradually work on optimising performance of the worst performing functions.

Can I remove the JSON-LD schema that Yoast adds to my WordPress site?

I would like to remove the JSON-LD schema that Yoast applies to my WordPress site so that I can add my own. I have already added my own, and Google Structured Data Testing says that it is OK, but basically I have 3 separate JSON-LD schemas instead of two because of Yoast.
You can see what I mean here: https://search.google.com/structured-data/testing-tool/u/0/#url=http%3A%2F%2Fwww.yogabearpc.com
Yoast has added the WebSite schema and it seems unnecessary or even damaging?
I wanted to disable this because of the sitelinks searchbox and the fact that I don't have a search function that works globally, just on the blog. Having the search box enabled for me would have undesirable effects.
The easier option may just be to prevent Google using the sitelinks searchbox without having to touch the functions files. You can prevent Google using sitelinks searchbox on your site by using the following meta:
<meta name="google" content="nositelinkssearchbox" />
If you want to disable Yoast's JSON-LD all together then here's a snippet from my blog and the code I use on my site:
SOURCE
How to disable Yoast SEO Schema JSON-LD completely
function bybe_remove_yoast_json($data){
$data = array();
return $data;
}
add_filter('wpseo_json_ld_output', 'bybe_remove_yoast_json', 10, 1);
Login to your WordPress dashboard and head over to the editor
within the tab menu appearance, find your functions file (normally
named functions.php) and add the code below just before the PHP tag is
closed at the bottom.
Simplest way to completely disable the Yoast SEO schema JSON-LD
Add this line to functions.php file:
add_filter( 'wpseo_json_ld_output', '__return_empty_array' );
Source
If you want to disable just Organization or just Website, add this to your theme's functions.php file:
function bybe_remove_yoast_json($data){
if ( (isset($data['#type'])) && ($data['#type'] == 'Organization') ) {
$data = array();
}
return $data;
}
add_filter('wpseo_json_ld_output', 'bybe_remove_yoast_json', 10, 1);
Unless the data Yoast produces is wrong, there is no harm in having it. Quite the contrary, having more structured data is better than having less.
If having it is "unnecessary" depends on your definition of what is necessary. Some consumers might be interested in it, others not.
My guess is that Yoast adds a WebSite entity because of Google’s sitelinks searchbox rich snippet result, which allows Google users to search your site directly from the Google search result.

Completely custom page in WordPress generated by a plugin

I am writing a WordPress plugin that has an AJAX element to it - blocks of HTML are fetched by the front end from the plugin using AJAX.
I am having difficulty joining up the pieces here, and I suspect it is just a terminology issue. How would I implement a page completely provided by the plugin?
The content of the page will be HTML - the plugin can generate this in response to POST or GET parameters.
There needs to be a route to this page. The route does not have to be user-friendly or a REST style - just some kind of URI that gets to the plugin. Is there perhaps a way to register a custom page with an arbitrary name, without having to create it as a WP post?
I would like all this to be self-contained in the plugin, so should not involve the administrator having to create posts or pages, or have to add anything to the theme.
Ideally I would avoid any URLs that go into the wp-admin directory. End users don't belong in here.
I would strongly suggest referring to https://codex.wordpress.org/AJAX_in_Plugins#Ajax_on_the_Viewer-Facing_Side
You need to have a php script in your plugin directory that returns what you request, and you need to determine that url at run time for reference in your ajax. The above link gives an example for enqueuing and using wp_localize_script() to provide the url for your custom php script.
wp_enqueue_script( 'ajax-script',
plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as
// ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => plugins_url( '/php/myapi.php' ));
Your javascript file will be included on every page and will listen for events on the page which require a block of HTML, as you've described it.
Your file myapi.php then needs to take a request, probably using a query string, get the appropriate content from the wordpress api, and respond with said content, which your javascript will put into place.
To have access to the wordpress api as well though, you have two options:
Force wordpress to run starting with your file, by including wp-load.php. This is probably not the cleanest way.
Set up a custom page or slug to direct to your plugin.
I would advise the second option, and advise a slug, in which case you may find this post helpful: wp_rewrite in a WordPress Plugin
From Jason's comment, based on the link above:
The rewrite rules are mentioned a lot, but are really a distraction -
they just help to make URLs look more "friendly", which was not an
objective here. The key is: register a custom GET parameter; look for
that parameter early in the page rendering process; if you find the
parameter is set, then output/echo stuff and die(). There are a
number of hooks that can be used to look at the parameters, chosen
dependin on how much you want WP to set up and process first.

How can I successfully use browser-sync with wordpress locally?

I'm trying to get browser-sync to work with my multipress wordpress install, for simpler mobile / responsive development.
Currently I'm having problems in that, my normal development takes place at local.example.com, and browser-sync is proxying this (via 123.456.78.9:3202, as per browser sync).
So far browser-sync loads the site, but none of my scripts or CSS are loading (although images load fine). They jsut fail with no response in the network panel.
I'm using NGINX for hosting the site, as opposed to apache.
Does anyone have any wordpress browser-sync experience? Am I missing something with the browser-sync set up? And tips for this would be super welcome. I'd love to get this as a solid part of my work flow.
The problem is to do with how wordpress handles URLs, in that it normally uses full URLs for including content and links etc.
The proxy is trying to access these on another domain and that's why it's failing.
Update
A much simple, cleaner and maintainable strategy, that also helps with development environments is to use the Root Relative URLs plugin. Adds hooks and configs similar to below, but also updates your content and editors to apply the same structure, so it's a bit more robust
Original Answer
You can add a simple hook (source: wordpress relative urls) to filter wordpress generated urls and remove the base domain so you get relative links to styles and posts etc:
$relative_url_filters = array(
'script_loader_src', //js
'style_loader_src', //css
'post_link', // Normal post link
'post_type_link', // Custom post type link
'page_link', // Page link
'attachment_link', // Attachment link
'get_shortlink', // Shortlink
'post_type_archive_link', // Post type archive link
'get_pagenum_link', // Paginated link
'get_comments_pagenum_link', // Paginated comment link
'term_link', // Term link, including category, tag
'search_link', // Search link
'day_link', // Date archive link
'month_link',
'year_link'
);
foreach ( $relative_url_filters as $relative_url_filters ) {
add_filter( $relative_url_filters, 'wp_make_link_relative' );
}
Which should clean up most of your issues and get browser-sync working nicely.
I'm still having some issues where I have more complex inclusions for images, but more or less it's working and we're already seeing how cool it is!

How to customize Wordpress Theme before going live

Yesterday I installed a new theme on Wordpress on my self-hosted website. I am aware of the feature that allows you to preview a theme and have used it to select a new Theme that I want to install.
Problem
I do not want to interrupt normal operations of my website, but this new theme requires a lot of customization before it is ready to go. How do I do this?
My Crappy Solution
Is the only way to go about it to run a virtual server on my desktop? This seems tedious, not to mention all the errors I usually get when switching to the "real" server when doing this.
A better way?
I've been searching on SO as well as the WordPress Forum for an answer as to how to do this, but have come up short. I would have thought this is a common question. Maybe I'm using the wrong search terms [themes, customization, before installing]???
Any help is greatly appreciated! Thanks!
Ok, since your question is a pretty good one and probably not a few people are going through the same process when they decide to update their site, I decided to give a try to the get_stylesheet and get_template filter hooks. It turns out that with a very small plugin, you can easily enforce a specific theme(well in this case any logged-in visitor, but you can change this to use any logic you want) according to a specific rule/s.
Here's the code that you need to put in a file in your plugins directory:
<?php
/*
Plugin Name: Switch Theme
Description: Switches the theme for logged-in visitors, while keeping the current theme for everyone else. !!!NOTE!!! Please back-up your database prior using this plugin - I can't guarantee that it will work with any theme, nor that it won't break your site's set-up - USE AT YOUR OWN RISK(I did a quick test and it seemed to be fine, but haven't done extensive testing).
You don't need to switch to the desired theme before that - you want to keep active the theme that you will display to your visitors - the one that you will see will be used programatically.
Before activating the plugin, change the line that says `private $admin_theme = '';` to `private $admin_theme = 'theme-directory-name';` where "theme-directory-name" is obviously the name of the directory in which the desired theme resides in.
*/
class MyThemeSwitcher {
private $admin_theme = '';
function MyThemeSwitcher() {
add_filter( 'stylesheet', array( &$this, 'get_stylesheet' ) );
add_filter( 'template', array( &$this, 'get_template' ) );
}
function get_stylesheet($stylesheet = '') {
if ( is_user_logged_in() && $this->admin_theme ) {
return $this->admin_theme;
}
return $stylesheet;
}
function get_template( $template ) {
if ( is_user_logged_in() && $this->admin_theme ) {
return $this->admin_theme;
}
return $template;
}
}
$theme_switcher = new MyThemeSwitcher();
So - first of all BACKUP YOUR DATABASE! I tested locally with Twenty Eleven being the default theme and a basic framework theme as my custom theme - the theme options and navigation menus were saved properly.
Then all you need to do is to update the file(change the line that says private $admin_theme = ''; to private $admin_theme = 'theme-slug'; where theme-slug is the name of the directory in which the theme you want to use is).
Also - you won't be able to change the Front page and Posts page options, without this affecting the live site, nor will you be able to change the any shared components that both themes use(Site name, Front Page, Posts page, Posts Per Page, etc options, content and so on).
So if you have no clue whether this solution is for you - well, it depends.
If both themes are not relatively complex, then most-likely you should be able to use this hack. If they are though maybe you should do a second installation of your website as others suggested - I think that a second installation in either a sub-domain or a sub-directory would be the best option for you(simply because moving a multisite database is more complex than moving a normal WP database).
I'd setup local apache server with a wordpress installed to customize and test a new theme. When you finished customizing it then you can upload the theme to your live site and activate it. If there are settings that you need to set in the dashboard then you probably will have to adjust them again. That's one way to test/customize a theme before putting it live.
You could create a network (make WordPress multisite with define('WP_ALLOW_MULTISITE', true);, see : http://codex.wordpress.org/Create_A_Network) and then create one sub-site, then turn it "off" with a Maintenance plugin so it is not accessible to users not logged in as admin, export your posts & data from main blog, import them in sub-blog with WordPress default importer, then apply your new theme to this sub-blog and work on it. When everything satisfies you, apply the theme to the main site and deactivate subsite.

Resources