Loading...

Follow Digging Into WordPress | Take your WordPress sk.. on Feedspot

Continue with Google
Continue with Facebook
or

Valid

One of the most annoying things in the WordPress universe are plugins and themes that don't conditionally load their scripts and styles (i.e., JavaScript and CSS files). For example, you install a dashboard plugin and it loads its scripts in the entire Admin Area and the frontend. Instead, the developer should have used conditional logic to NOT load the script on the frontend (e.g., via !is_admin()), or anywhere in the Admin Area EXCEPT the dashboard (e.g., via get_current_screen()). It's just basic human decency.

Unfortunately, a LOT of plugins FAIL when it comes to conditional loading of assets. They just spit them JavaScripts and CSS files all over the place, across every page on the site. And that my friends is frustrating. Especially when performance matters and you're trying to optimize loading of script and style.

Fortunately, WordPress makes it easy to disable any unwanted scripts or styles. So let's put an end to the nonsense and disable any unwanted CSS and JavaScript files. This tutorial explains how to do it in TWO steps.

Quick Nav Step 1: Get the ID

The first thing we need is the specific ID for the script or style that we want to disable. There are numerous ways of getting this information, from easiest to most time-consuming:

  • Check the <script> or <style> tag
  • Use a script/style-inspector function like the one below
  • Locate the source code responsible for adding the script
  • Educated guess then ask

In theory, you can just go through the list until you find the ID. In practice, however, finding script/style IDs is more an art form, trial and error until it works kind of thing. So basically just use that list as a guide and try each technique until you get the desired ID. This is a critical step for any script or style that you want to disable. Let's take a moment and go through each technique..

Check the script or style tag

The easiest way to get the ID is to just examine the <script> or <style> tag in the markup of your web page. For example, let's say we want to disable EDD plugin styles. Looking at the source code of one of our pages, we find the style tags output in the <head> section:

<link  id='media-styles-css'   href='https://example.com/wp/wp-content/themes/example/lib/css/media.css' type='text/css' media='all' />
<link  id='default_styles-css' href='https://example.com/wp/wp-content/themes/example/style.css' type='text/css' media='all' />
<link  id='edd-styles-css'     href='https://example.com/wp/wp-content/themes/example/lib/css/edd.css' type='text/css' media='all' />

Here we have three style tags, each loading a separate CSS file. The key thing to notice here are the id attributes. We have the following ID values:

  • media-styles-css
  • default_styles-css
  • edd-styles-css

Seems straightforward, right? Wrong. If you try to use these IDs to disable or dequeue the associated styles, it won't work. Why? Because those values are NOT the actual style IDs. Nope. WordPress appends -css ("dash css") to the actual ID values. Applying this esoteric bit of knowledge, our list of style IDs now looks like this:

  • media-styles
  • default_styles
  • edd-styles

So now we have the correct ID for the unwanted EDD stylesheet, edd-styles. Let's remember that value, as we'll be using it in Step 2.

Use a script/style-inspector function

The previous method of getting the ID is the easiest. But the problem is that WordPress does not include an id attribute on <script> tags. So to get the ID of any unwanted scripts, we can use a simple "script-inspector" function like such as this little number by yours truly:

/*
	Get Script and Style IDs
	Adds inline comment to your frontend pages
	View source code near the <head> section
	Lists only properly registered scripts
	@ https://digwp.com/2018/08/disable-script-style-added-plugins/
*/
function shapeSpace_inspect_script_style() {
	
	global $wp_scripts, $wp_styles;
	
	echo "\n" .'<!--'. "\n\n";
	
	echo 'SCRIPT IDs:'. "\n";
	
	foreach($wp_scripts->queue as $handle) echo $handle . "\n";
	
	echo "\n" .'STYLE IDs:'. "\n";
	
	foreach($wp_styles->queue as $handle) echo $handle . "\n";
	
	echo "\n" .'-->'. "\n\n";
	
}
add_action('wp_print_scripts', 'shapeSpace_inspect_script_style');

How it working? Just add to your theme's functions.php file, upload, and refresh the page. No modifications are required unless you want to spice it up. As-is, the function will display a list of all properly registered script and style IDs. So in your markup in the <head> section, look for something like this:

<!--

SCRIPT IDs:
jquery
jquery-migrate
edd-checkout-global
edd-ajax

STYLE IDs:
media-styles
default_styles
edd-styles

-->

And these are the actual IDs, nothing appended or anything weird. So hopefully the unwanted script or style is listed here, so you can get the ID using this method and then proceed to Step 2.

Locate the source code responsible for adding the script

If neither of the previous techniques works, an effective way to get the ID is to grep through the actual plugin source code. There are many strategies for searching through plugin files and code, so use your search skillz and get to work. Tip: search for the file name and path, and/or just the file name, should yield some results to go from.

Another good strategy is to search for the names of WordPress functions that may be used to add the unwanted script or style. For example, search for wp_enqueue_script(), wp_register_script(), and friends.

Educated guess then ask

If all else fails, take a guess. Look at the actual file name that you want to exclude. For example if you have this:

<script type='text/javascript' src='https://example.com/wp/wp-content/plugins/amazing-plugin/assets/js/amazing-plugin.min.js?ver=1.2.3'></script>

There is a pretty good chance that the correct ID is going to be amazing-plugin or something similar. If not, and/or if all else fails:

Ask the developer

Surely the developer will be able to provide proper script and style IDs.

Step 2: Dequeue script or style

Once you have the correct ID, actually disabling the script or style is straightforward. Going with the EDD example, the ID of the unwanted stylesheet is edd-styles. So to disable, we can add the following to our theme's functions.php file:

// disable stylesheet (example)
function shapeSpace_disable_scripts_styles() {
	
	wp_dequeue_style('edd-styles');
	
}
add_action('wp_enqueue_scripts', 'shapeSpace_disable_scripts_styles', 100);

Done. With this code in place, the EDD stylesheet will not be loaded on any frontend page. We know that it's front-end only because of the particular action hook we are using, wp_enqueue_scripts. If we want to disable stylesheets in the Admin Area, we instead would use admin_enqueue_scripts.

The only other secret here is the WordPress function used to disable the stylesheet, wp_dequeue_style(). If we want to disable adding of a JavaScript file, we instead would use wp_dequeue_script(). Hit those links for more details on any of these excellent functions.

Examples

Now that we understand how everything works, here is my growing collecting of real-world examples of disabling CSS and JavaScript added by plugins.

Disable script and style on frontend

In my latest site redesign, I removed a bunch of plugins and scripts that no longer were needed. After cleaning up my plugins, I no longer needed to explicitly disable any CSS or JavaScript files. Thus, I was able to remove the following function:

function shapeSpace_disable_scripts_styles() {
	
	// easy digital downloads
	if (!is_page('checkout') && !is_page('purchase-confirmation') && !is_page('purchase-history') && !is_page('transaction-failed')) {
		
		wp_dequeue_script('edd-ajax');
		wp_dequeue_script('edd-password-meter-passfield-locales');
		wp_dequeue_script('edd-password-meter-passfield');
		wp_dequeue_script('edd-password-meter');
		
		wp_dequeue_style('edd-sl-styles');
		wp_dequeue_style('edd-password-meter-passfield');
		wp_dequeue_style('edd-password-meter');
		
	}
	
	// super stripe plugin
	if (!is_page('direct') && !is_page('custom') && !is_page('cancel') && !is_page('success')) {
		
		wp_dequeue_script('supstr-aweber-js');
		wp_dequeue_script('supstr-shortcode-js');
		wp_dequeue_script('supstr-validate-js');
		
	}
	
	// search everything
	wp_dequeue_style('se-link-styles');
	remove_action('wp_head', 'se_global_head');
	
	
	// yet another related posts plugin
	wp_dequeue_style('yarppWidgetCss');
	
}
add_action('wp_enqueue_scripts', 'shapeSpace_disable_scripts_styles', 100);

This function disables various scripts and styles otherwise added via EDD, Super Stripe, Search Everything, and YARPP. It felt really good cleaning up all of that mess. As a bonus, notice the use of remove_action() to remove the unnecessary Search Everything stuff from the <head> section.

Disable script and style in Admin Area

Next, here is a function that disables some plugin style in the Admin Area:

function shapeSpace_disable_scripts_styles_admin_area() {
	
	wp_dequeue_style('jquery-ui-css');
	
}
add_action('admin_enqueue_scripts', 'shapeSpace_disable_scripts_styles_admin_area', 100);

As explained previously, the key to targeting the Admin Area is using the admin_enqueue_scripts hook.

Disable script and style elsewhere

And last but not least, here are two examples that demonstrate an important point. Not all functions register and enqueue CSS and JavaScript files as recommended. And in those cases, the previously prescribed methods may not work. So sometimes we have to get creative with alternate methods and hooks to use. Here is a good example:

// via the wp_print_styles hook
function shapeSpace_disable_download_manager_styles() {
	
	wp_deregister_style('dlm-frontend');
	
}
add_action('wp_print_styles', 'shapeSpace_disable_download_manager_styles', 100);

For whatever reason, the only way I could disable this particular plugin's stylesheet was to use wp_deregister_style() hooked into wp_print_styles. Whatever it worked. To be fair, I didn't have a lot of time to fiddle around with unwanted plugin styles, so there may be some sort of rational explanation.

And the second example is even more unusual. Observe:

// had to use the get_footer hook!!!
function shapeSpace_disable_yarpp_styles() {
	
	wp_dequeue_style('yarppRelatedCss');
	
}
add_action('get_footer', 'shapeSpace_disable_yarpp_styles');

Notice the hook used here: get_footer!!! Whaaaa...? Truly bizarre but it was the ONLY thing that would work to disable the unwanted YARRP styles. Not sure if I would recommend this technique on any other live site, just because it feels kinda weird using wp_dequeue_style() via the get_footer hook.

That's all for now, Thank you for visiting :)


Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

After months of development, I am excited to announce my newest premium WordPress plugin: GA Pro! Quite simply it connects your WordPress site to your Google Analytics account just like the free version, but with awesome new features like visitor Opt Out, multiple trackers, code previews, and more.

Direct link to article | View post at DigWP.com

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Just to be crystal clear, this post is all about displaying basic statistics about your site, not about your visitors. So if you are thinking something like, "duh, just use Google Analytics or whatever," then imagine a giant buzzer sound telling you that you're incorrect. Sure, Google Analytics gives you information about your visitors, like how many, where from, how long, and so forth. But GA et al do NOT provide information about your site itself. Things like the number of registered users, number of posts and pages, number of comments, and all the other cool little details about your site. That is what we'll be covering in today's DigWP tutorial. So grab some popcorn and enjoy the show! ;)

Contents The easy way..

The easy way to display all of your site's statistics? Use a free plugin! There are so many great ones available, so feel free to use whatever works best for you. For DigWP.com and other sites, I use Basic Blog Stats, which I develop. It provides a set of customizable shortcodes that can be used to display a wide variety of site stats, including most everything presented in this article. Here is a partial list of basic stats that you can display just about anywhere on your site:

  • Total number of posts
  • Total number of pages
  • Total number of drafts
  • Total number of comments
  • Number of comments in moderation
  • Number of approved comments
  • Number of registered users
  • Number of categories
  • Number of tags
  • Number of words for any post
  • Number of words for all posts
  • Display all blog stats in a list

..and much more! Check it out and download Basic Blog Stats at the WordPress Plugin Directory. It's open source and 100% free always :)

Display stats manually

While using a plugin to display site statistics makes everything super easy, it may be overkill for some cases. In the past, displaying basic blog stats required all sorts of fancy database queries and complicated code. Since then WordPress has made it much easier. Now for most types of basic statistics, WordPress provides an assortment of functions that make it just stupid easy to show off all manner of juicy stats.

For example, if you just want to display the number of users or posts, probably don't need an entire plugin when just a code snippet will do the job nicely. To help with such scenarios, here are a bunch of simple code techniques to display all sorts of useful statistics about your WordPress-powered site.

Total number of users

To display the total number of users registered at your site, we can use count_users(). Here is a basic example showing how it works:

$count = count_users();

$total = isset($count['total_users']) ? $count['total_users'] : null;

if ($total) echo 'Total number of users: '. $total;

This will give us something like:

Total number of users: 120

The count_users() function also provides user counts per role:

$counts = isset($count['avail_roles']) ? $count['avail_roles'] : null;

if ($counts) {
	
	echo '<ul>';
	
	foreach ($counts as $role => $count) {
		
		echo '<li>'. $role .': '. $count .'</li>';
		
	}
	
	echo '<ul>';
	
}

This outputs a list of each role and its number of registered users, for example:

  • Administrator: 1
  • Editor: 11
  • Author: 8
  • Contributor: 20
  • Subscriber: 80
Total number of posts & pages

To display the number of posts, pages, or any post type, we can use wp_count_posts(). The wp_count_posts() function returns an object that gives us post counts for each post status (e.g., publish, draft, pending). Here are some simple examples:

$count = wp_count_posts();

$publish = $count->publish;

$draft = $count->draft;

echo 'There are '. $publish .' published posts and '. $draft .' draft posts.';

As before, we call the function then access its various properties to get the counts we want to display. Here we are grabbing the number of published and draft posts. In the browser, the output looks like this:

There are 750 published posts and 20 draft posts.

Likewise, we can display the number of any post type, for example:

$count = wp_count_posts('page');

By setting the $type parameter to page, the returned object contains all the count information for pages. Any post type may be specified here, so you can get current counts for any post type.

Total number of comments

WordPress also provides a function for displaying the total number of comments, wp_count_comments(). It works similarly to wp_count_posts(), returning an object with various properties. We can either get the count of ALL comments on the site:

// get comment count for entire site
$count = wp_count_comments();

..or we can specify a post ID as the (optional) first parameter to get the comment count for a specific post:

// get comment count for specific post
$count = wp_count_comments($post_id);

In either case, the function returns an object with counts for approved, moderated, spam, trash, and total_comments. So we can display the count information however is needed. Here is an example showing counts for each comment status:

$count = wp_count_comments();

echo '<ul>';

echo '<li>Comments in moderation: '. $count->moderated      .'</li>';
echo '<li>Comments approved: '.      $count->approved       .'</li>';
echo '<li>Comments in Spam: '.       $count->spam           .'</li>';
echo '<li>Comments in Trash: '.      $count->trash          .'</li>';
echo '<li>Total Comments: '.         $count->total_comments .'</li>';

echo '</ul>';

That will output a list like this:

  • Comments in moderation: 5
  • Comments approved: 10,000
  • Comments in Spam: 33
  • Comments in Trash: 0
  • Total Comments: 10,038
Site creation date

Something that's useful for things like copyright statements and footer credits, etc., is the date that your site was created. Awesomely, WordPress provides a function named mysql2date() that makes it super easy. Here is an example:

Blog creation date: <?php echo mysql2date('l, F j, Y', get_user_option('user_registered', 1)); ?>

This will give us something like this:

Blog creation date: Wednesday, March 9th, 2005

How does it work? Easy. The first parameter specifies the date format, and the second parameter is a variable that contains the date we want to convert. In this example, we are simply using the user_registered option for the date parameter. It will contain the date/time that the original admin user (ID = 1) was created, which technically happens when the database is created and WordPress installed. Very straightforward. Check the docs for more details.

Display theme information

Another useful bit of information to display is your theme name, version, and other theme-related details. As one might expect, WordPress provides a function named wp_get_theme() that gives us access to a wealth of theme information. Here is an example:

$theme = wp_get_theme();

if ($theme->exists()) {
	
	echo $theme->get('TextDomain') .' @ ';
	echo $theme->get('ThemeURI');
	
}

Here we use wp_get_theme() and store the object results in the $theme variable. Then before echoing any theme information, we check to make sure the theme exists using the $theme object's exists() method. From there, we use the object's get() method to output whatever theme info is desired. Here is a dump of an example WP_Theme object, which is returned by wp_get_theme():

object(WP_Theme) {
	
	public  'update'     => boolean false
	private 'theme_root' => string 'home/path/wp-content/themes'
	private 'headers'    => array {
		
		'Name'        => string 'shapeSpace'
		'ThemeURI'    => string 'https://shapespace.io/'
		'Description' => string 'WordPress Starter Theme'
		'Author'      => string 'Jeff Starr'
		'AuthorURI'   => string 'https://perishablepress.com/'
		'Version'     => string '2.3'
		'Template'    => string ''
		'Status'      => string ''
		'Tags'        => string ''
		'TextDomain'  => string 'shapeSpace'
		'DomainPath'  => string ''
		
		}
	private 'headers_sanitized' => null
	private 'name_translated'   => null
	private 'errors'            => null
	private 'stylesheet'        => string 'shapeSpace'
	private 'template'          => string 'shapeSpace'
	private 'parent'            => null
	private 'theme_root_uri'    => null
	private 'textdomain_loaded' => null
	private 'cache_hash'        => string '1234567890...'
	
}

Lots of possibilities here, just a matter of calling the property you want to display. And here is a pro tip for you: you can display the current theme name, by simply writing: <?php echo wp_get_theme(); ?>

Display plugin information

WordPress also provides a cool function for displaying information about your plugins. Indeed, the function get_plugins() returns an array of data for each installed WordPress plugin. Here is an example showing how it works:

// load the required file if needed
if (!function_exists('get_plugins')) {
	
	require_once ABSPATH . 'wp-admin/includes/plugin.php';
	
}

$plugins = get_plugins();

$hello_dolly = isset($plugins['hello-dolly/hello.php']) ? $plugins['hello-dolly/hello.php'] : null;

if ($hello_dolly) var_dump($hello_dolly);

That is how you would get an array of information about the default "Hello Dolly" plugin. The only real trick to using this technique is manipulating the $plugins array, which may contain a LOT of data, depending on the number of installed plugins. To get a better idea of the data available to us, we can use the following function:

error_log(print_r($plugins, true));

This will "dump" or "print" the complete contents of the $plugins array to the site's server-writable error log. For example, if our site only has the default "Hello Dolly" plugin, then the get_plugins() function should return something like this:

Array (
	[hello-dolly/hello.php] => Array (
		
		[Name]        => Hello Dolly
		[PluginURI]   => http://wordpress.org/extend/plugins/hello-dolly/
		[Version]     => 1.6
		[Description] => This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words...
		[Author]      => Matt Mullenweg
		[AuthorURI]   => http://ma.tt/
		[TextDomain]  => 
		[DomainPath]  => 
		[Network]     => 
		[Title]       => Hello Dolly
		[AuthorName]  => Matt Mullenweg
	)
)

So any of this information may be displayed anywhere in your WordPress theme template. And for sites with more than one plugin, the array will contain information for each of them. For each array item, the key is the plugin file path and the value is an array of the plugin data. If you just want to display ALL plugin data, here is a function that iterates through each plugin in the $plugins array, and displays all the information as a nice, bulleted list:

// display all plugin infos!
$plugins = get_plugins();

if ($plugins) {
	echo '<ul>';
	foreach ($plugins as $key => $value) {
		echo '<li>';
		echo '<strong>'. esc_html($key) .'</strong> ';
		if (is_array($value)) {
			echo '<ul>';
			foreach ($value as $k => $v) {
				echo '<li>'. esc_html($k) .': '. esc_html($v) .'</li>';
			}
			echo '</ul>';
		}
		echo '</li>';
	}
	echo '</ul>';
}

Just want to emphasize that the get_plugins() function returns information about ALL plugins on your site, not just the ones that are activated.

Bonus: Display only active plugins

While writing this article, I found this little code snippet lurking at the bottom of my notes. It provides a way to display names of only ACTIVE plugins:

function shapeSpace_active_site_plugins() {
	$plugins = get_option('active_plugins'); 
	if ($plugins) {
		echo '<ul>';
		foreach ($plugins as $key => $value) {	
			$string = explode('/', $value);
			echo '<li>'. esc_html($string[0]) .'</li>';
		}
		echo '</ul>';
	}
}
shapeSpace_active_site_plugins();

This function takes a different route to getting the active plugin information. Basically grabbing the active_plugins option and then parsing out the plugin name. Your mileage may vary, customize as needed!

Wrap up

This article provides many awesome techniques for display blog stats like post count, comment count, theme info, plugin info, and much more. You can either use the individual techniques and modify/use them as desired in your WordPress project.

Or if you just want a complete way to display all of your blog's basic stats, you can do it easily with a plugin like my own Basic Blog Stats. Either way, the point is you can be so cool and join the cool kids by displaying some awesome statistics about your WordPress-powered site.


Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Just a quick post to share some recommended useful resources for anyone working with the new Gutenberg Block Editor. Our book Digging Into WordPress now links to this post, so readers can learn more and dive deep into Gutenberg. Or just bookmark for future reference. What does that mean? It means that this page will be updated with any new useful and official resources. And by "official" just means the information is sourced/hosted at WordPress.org.

Learn more about Gutenberg

There are many official posts that are useful in specific contexts. This list focuses on just the main resources for learning more about Gutenberg Block Editor. Starting points for digging in and branching out.

Any one of these resources will open many doors for further learning and exploration of the Gutenberg Block Editor and related WordPress features.

Gutenberg Alternatives

The Gutenberg Block Editor has come a long way since it first began as a plugin. But not everyone is ready for the changes. Some folks like myself prefer the original "classic" editor. So for anyone looking for alternatives to Gutenberg, here are some resources that may be useful.

  • Classic Editor — official plugin by the WP team to restore the Classic Editor, already over 1 million active installations.
  • Disable Gutenberg — free WP plugin that completely disables all traces of Gutenberg and restores the Classic Editor. Includes robust options for custom configuration and selective enabling of the Block Editor.
  • ClassicPress — the new "Gutenberg-free" version of WordPress (forked at WP 4.9) that's focused on providing a reliable, consistent CMS.

Or if you are a developer and would like to know how to disable Gutenberg or selectively enable the Block Editor, check out these DigWP tutorials:

Plus there are lots of other plugins now available to help you configure, customize, and disable Gutenberg. Also lots of plugins to help you customize and extend the Block Editor, visit the WordPress.org Plugin Directory to explore the possibilities.

Bonus tip

Also useful if you want to look at the "Welcome" screen for WordPress 5.0 (or whichever version you are using), just enter the following URL while logged into your WordPress site:

https://example.com/wp-admin/about.php?updated

Or if you have WordPress installed in a subdirectory, say, /wordpress/, you would enter this URL instead:

https://example.com/wordpress/wp-admin/about.php?updated

Then you would replace "example.com" with your actual domain. That should get you to the "Welcome" screen for your current version of WordPress. So for awhile you can get a broad look at Gutenberg, how it works, features, etc.

Send any suggestions for useful/official Gutenberg resources that should be added to this post, please comment or contact direct, thank you! :)


Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Save 20% on Digging Into WordPress, The Tao of WordPress, .htaccess made easy, and WP Themes In Depth. Visit the Perishable Press Bookstore and enter coupon code HOHOHO during checkout for instant savings. Happy Holidays! :)

Direct link to article | View post at DigWP.com

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Previously, we covered numerous techniques to disable Gutenberg. For example, you can disable Gutenberg on specific post types, user roles, post IDs, and so forth. But what about doing the opposite and conditionally enabling Gutenberg? For example, if Gutenberg is disabled by default, you could then selectively enable it on whichever post types, user roles, or whatever criteria that's required. So this tutorial explains how to enable Gutenberg using simple WordPress filter hooks. You'll learn how to enable Gutenberg for any single posts, new posts, post meta, categories, tags, and post types. Plus some juicy tips and tricks along the way!

Update! To selectively enable Gutenberg only on certain posts, you can do it without touching any code. My free plugin Disable Gutenberg now provides whitelist options to always use Block Editor on any post IDs, slugs, or titles :)
First: Disable Gutenberg by default

In WordPress 5.0 and beyond, Gutenberg is enabled by default. So if you want to enable Gutenberg everywhere, you don't need to do anything: it just works.

Otherwise, if you want to enable Gutenberg only on specific post IDs, post types, and so forth, you will need to first disable Gutenberg everywhere. To do this, we can use either of the following filter hooks (depending on WP version):

// WP < 5.0 beta
add_filter('gutenberg_can_edit_post', '__return_false', 5);

// WP >= 5.0
add_filter('use_block_editor_for_post', '__return_false', 5);

So choose either or both of these hooks (to support all versions of WP), and add to your theme's functions.php. Or, if you would rather disable Gutenberg and restore the Classic Editor using a plugin, check out Disable Gutenberg, which is super lightweight, flexible, and easy to customize exactly where Gutenberg should be disabled on your site. However you choose to disable Gutenberg, you will need to do so in order for the following techniques to work properly.

Tip: Notice the third parameter (5) in the two filters above? Setting that value makes it possible to override and enable Gutenberg using techniques such as the ones provided below.
Enable Gutenberg for any Post IDs

Once Gutenberg is disabled everywhere, here is an example showing how to enable it only for specific post IDs:

function shapeSpace_enable_gutenberg_post_ids($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	if (1 === $post->ID) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post', 'shapeSpace_enable_gutenberg_post_ids', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post', 'shapeSpace_enable_gutenberg_post_ids', 10, 2);

As written, this function will enable Gutenberg on post ID = 1. You can change that as needed in the third line of the function.

Tip: To selectively disable Gutenberg on any post, role, type, and so forth, check out my previous tutorial, How to Disable Gutenberg: Complete Guide.
Enable Gutenberg for new posts

To enable Gutenberg for all new posts, you can do something like this:

function shapeSpace_enable_gutenberg_new_posts($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	$current = get_current_screen();
	
	if ('post' === $current->base && 'add' === $current->action) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post', 'shapeSpace_enable_gutenberg_new_posts', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post', 'shapeSpace_enable_gutenberg_new_posts', 10, 2);

As written, this function checks if the user is viewing the post-new.php screen, and if so returns true (to enable Gutenberg).

Tip: Notice the 10 value that these techniques are passing via the add_filter hooks. Why? Remember we set that parameter to 5 when we disable Gutenberg, so by setting it to 10 or any value greater than 5, we easily override the disabling function and thereby enable Gutenberg. It's all about hook priority!
Enable Gutenberg for specific Post Meta

What about enabling Gutenberg Block Editor only on posts that have some specific meta data attached? Easy, here is an example showing how to do it:

function shapeSpace_enable_gutenberg_post_meta($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	if ('Happy' === get_post_meta($post->ID, 'current_mood', true)) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post', 'shapeSpace_enable_gutenberg_post_meta', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post', 'shapeSpace_enable_gutenberg_post_meta', 10, 2);

As written, this function checks the current post for a custom field named current_mood with a value of Happy. If it exists, the function then returns true to enable Gutenberg for that post. Note that these examples are kept as simple as possible to help understanding. Much more is possible!

Tip: Notice that we hook the function name into both Gutenberg filter hooks: gutenberg_can_edit_post and use_block_editor_for_post. This means that the function will run in all applicable versions of WordPress. So if you are not worried about supporting older or newer versions of WordPress, you can simply remove one or the other add_filter() functions and done.
Enable Gutenberg for specific categories

Here is an example showing how to enable Gutenberg only for specific categories:

function shapeSpace_enable_gutenberg_post_cats($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	if (has_category(12)) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post', 'shapeSpace_enable_gutenberg_post_cats', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post', 'shapeSpace_enable_gutenberg_post_cats', 10, 2);

As written, this function uses WP's has_category() to check if the current post belongs to category 12; if so, true is returned thereby enabling Gutenberg. Of course, you can specify your own category or array of categories, or whatever.

Tip: To check if the current post contains any Gutenberg blocks, we can add this logic to any of our enabling functions: if (has_blocks($post)) return true;
Enable Gutenberg for specific tags

Here is an example showing how to enable Gutenberg only for specific tags:

function shapeSpace_enable_gutenberg_post_tags($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	if (has_tag(50)) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post', 'shapeSpace_enable_gutenberg_post_tags', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post', 'shapeSpace_enable_gutenberg_post_tags', 10, 2);

As written, this function uses WP's has_tag() to check if the current post is tagged with tag ID = 50; if so, true is returned thereby enabling Gutenberg. Of course, you can specify your own tag or array of tags.

Tip: Notice the 3rd parameter, 2, passed to either of the add_filter() functions. That specifies the number of parameters passed to the hooked function, which in this case is shapeSpace_enable_gutenberg_post_tags. So if you look at that function, you will see that it accepts two parameters, $can_edit and $post.
Enable Gutenberg for any Post Type

One more for the road! Here is an example showing how to enable Gutenbeg only for specific post types:

function shapeSpace_enable_gutenberg_post_type($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	if ('books' === $post_type) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post_type', 'shapeSpace_enable_gutenberg_post_type', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post_type', 'shapeSpace_enable_gutenberg_post_type', 10, 2);

This function is similar to the others, but hook-wise it does something a bit differently. When working with post types, WordPress/Gutenberg provide the following filter hooks for working with Post Types:

// WP < 5.0 beta
gutenberg_can_edit_post_type

// WP >= 5.0
use_block_editor_for_post_type

So we use these recommended hooks to enable Gutenberg for specific post types. Note also that our function currently checks the current post type. As written, it checks for a post type named books; feel free to modify as needed to suit your needs. The possibilities are endless!


Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Previously, we covered numerous techniques to disable Gutenberg. For example, you can disable Gutenberg on specific post types, user roles, post IDs, and so forth. But what about doing the opposite and conditionally enabling Gutenberg? For example, if Gutenberg is disabled by default, you could then selectively enable it on whichever post types, user roles, or whatever criteria that's required. So this tutorial explains how to enable Gutenberg using simple WordPress filter hooks. You'll learn how to enable Gutenberg for any single posts, new posts, post meta, categories, tags, and post types. Plus some juicy tips and tricks along the way!

First: Disable Gutenberg by default

In WordPress 5.0 and beyond, Gutenberg is enabled by default. So if you want to enable Gutenberg everywhere, you don't need to do anything: it just works.

Otherwise, if you want to enable Gutenberg only on specific post IDs, post types, and so forth, you will need to first disable Gutenberg everywhere. To do this, we can use either of the following filter hooks (depending on WP version):

// WP < 5.0 beta
add_filter('use_block_editor_for_post', '__return_false', 5);

// WP >= 5.0
add_filter('use_block_editor_for_post', '__return_false', 5);

So choose either or both of these hooks (to support all versions of WP), and add to your theme's functions.php. Or, if you would rather disable Gutenberg and restore the Classic Editor using a plugin, check out Disable Gutenberg, which is super lightweight, flexible, and easy to customize exactly where Gutenberg should be disabled on your site. However you choose to disable Gutenberg, you will need to do so in order for the following techniques to work properly.

Tip: Notice the third parameter (5) in the two filters above? Setting that value makes it possible to override and enable Gutenberg using techniques such as the ones provided below.
Enable Gutenberg for any Post IDs

Once Gutenberg is disabled everywhere, here is an example showing how to enable it only for specific post IDs:

function shapeSpace_enable_gutenberg_post_ids($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	if (1 === $post->ID) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post', 'shapeSpace_enable_gutenberg_post_ids', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post', 'shapeSpace_enable_gutenberg_post_ids', 10, 2);

As written, this function will enable Gutenberg on post ID = 1. You can change that as needed in the third line of the function.

Tip: To selectively disable Gutenberg on any post, role, type, and so forth, check out my previous tutorial, How to Disable Gutenberg: Complete Guide.
Enable Gutenberg for new posts

To enable Gutenberg for all new posts, you can do something like this:

function shapeSpace_enable_gutenberg_new_posts($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	$current = get_current_screen();
	
	if ('post' === $current->base && 'add' === $current->action) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post', 'shapeSpace_enable_gutenberg_new_posts', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post', 'shapeSpace_enable_gutenberg_new_posts', 10, 2);

As written, this function checks if the user is viewing the post-new.php screen, and if so returns true (to enable Gutenberg).

Tip: Notice the 10 value that these techniques are passing via the add_filter hooks. Why? Remember we set that parameter to 5 when we disable Gutenberg, so by setting it to 10 or any value greater than 5, we easily override the disabling function and thereby enable Gutenberg. It's all about hook priority!
Enable Gutenberg for specific Post Meta

What about enabling Gutenberg Block Editor only on posts that have some specific meta data attached? Easy, here is an example showing how to do it:

function shapeSpace_enable_gutenberg_post_meta($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	if ('Happy' === get_post_meta($post->ID, 'current_mood', true)) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post', 'shapeSpace_enable_gutenberg_post_meta', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post', 'shapeSpace_enable_gutenberg_post_meta', 10, 2);

As written, this function checks the current post for a custom field named current_mood with a value of Happy. If it exists, the function then returns true to enable Gutenberg for that post. Note that these examples are kept as simple as possible to help understanding. Much more is possible!

Tip: Notice that we hook the function name into both Gutenberg filter hooks: gutenberg_can_edit_post and use_block_editor_for_post. This means that the function will run in all applicable versions of WordPress. So if you are not worried about supporting older or newer versions of WordPress, you can simply remove one or the other add_filter() functions and done.
Enable Gutenberg for specific categories

Here is an example showing how to enable Gutenberg only for specific categories:

function shapeSpace_enable_gutenberg_post_cats($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	if (has_category(12)) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post', 'shapeSpace_enable_gutenberg_post_cats', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post', 'shapeSpace_enable_gutenberg_post_cats', 10, 2);

As written, this function uses WP's has_category() to check if the current post belongs to category 12; if so, true is returned thereby enabling Gutenberg. Of course, you can specify your own category or array of categories, or whatever.

Tip: To check if the current post contains any Gutenberg blocks, we can add this logic to any of our enabling functions: if (has_blocks($post)) return true;
Enable Gutenberg for specific tags

Here is an example showing how to enable Gutenberg only for specific tags:

function shapeSpace_enable_gutenberg_post_tags($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	if (has_tag(50)) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post', 'shapeSpace_enable_gutenberg_post_tags', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post', 'shapeSpace_enable_gutenberg_post_tags', 10, 2);

As written, this function uses WP's has_tag() to check if the current post is tagged with tag ID = 50; if so, true is returned thereby enabling Gutenberg. Of course, you can specify your own tag or array of tags.

Tip: Notice the 3rd parameter, 2, passed to either of the add_filter() functions. That specifies the number of parameters passed to the hooked function, which in this case is shapeSpace_enable_gutenberg_post_tags. So if you look at that function, you will see that it accepts two parameters, $can_edit and $post.
Enable Gutenberg for any Post Type

One more for the road! Here is an example showing how to enable Gutenbeg only for specific post types:

function shapeSpace_enable_gutenberg_post_type($can_edit, $post) {
	
	if (empty($post->ID)) return $can_edit;
	
	if ('books' === $post_type) return true;
	
	return $can_edit;
	
}

// Enable Gutenberg for WP < 5.0 beta
add_filter('gutenberg_can_edit_post_type', 'shapeSpace_enable_gutenberg_post_type', 10, 2);

// Enable Gutenberg for WordPress >= 5.0
add_filter('use_block_editor_for_post_type', 'shapeSpace_enable_gutenberg_post_type', 10, 2);

This function is similar to the others, but hook-wise it does something a bit differently. When working with post types, WordPress/Gutenberg provide the following filter hooks for working with Post Types:

// WP < 5.0 beta
gutenberg_can_edit_post_type

// WP >= 5.0
use_block_editor_for_post_type

So we use these recommended hooks to enable Gutenberg for specific post types. Note also that our function currently checks the current post type. As written, it checks for a post type named books; feel free to modify as needed to suit your needs. The possibilities are endless!


Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

What up! Just to help spread the word about the DigWP newsletter. Get WordPress news, tips, and special offers delivered fresh to your inbox. 3-4 times per year max. Always good stuff, never spam, and we never share your info with anyone. Just a quality newsletter letting you know about awesome stuff happening in our corner of the WordPress universe.

Direct link to article | View post at DigWP.com

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Weak passwords leave your site vulnerable. WordPress sites with more than one user should enforce a "strong password" policy for better security. To help with this, check out Password Policy Manager. It is a CHOICE WordPress plugin that makes it easy to define a strong set of password requirements for your site's users. Easy to use and provides a robust set of features. Check it out.

Direct link to article | View post at DigWP.com

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

During the latest site redesign, I removed the Subscribe to Comments plugin. Wisely, the plugin does not delete any subscriber information from the database. So as a part of the site's redesign slash clean-up, I wanted to export/save and then delete all subscriber information to decrease overall database size. After searching and not finding any specific solution or preferred technique for this process, I rolled my own. Actually it's just a simple SQL query to get it done! :)

Step 1: Backup Database

Before making any changes to your database, it always is a good idea to make a good working backup copy. This way you can restore your previous content should something unexpected happen.

Also, if you want to keep a copy of all your subscriber infos (i.e., names and emails), then take a moment to export those data as well. You never know when/where the information may be useful.

Step 2: Select Data

Using your favorite database UI (e.g., phpMyAdmin), enter the following query:

SELECT * FROM wp_postmeta WHERE meta_key = "_sg_subscribe-to-comments";

Remember to double-check the database prefix (e.g., wp_) and edit to match your own. This query will return all subscriber data added via the Subscribe to Comments plugin. Just so you are aware of what you will be deleting. Take a moment to observe the total number of entries and so forth. Also as another reminder, now would be a good time to grab a copy of the subscriber data you are about to delete.

Step 3: Delete Data

At this point, there is no going back. Enter the following SQL query to delete ALL data collected via the Subscribe to Comments plugin. Again, remember to check and change the database prefix if necessary.

DELETE FROM wp_postmeta WHERE meta_key = "_sg_subscribe-to-comments";

And DONE. All subscriber data should be removed from your database.

Step 4 (Optional): Replace "Subscribe" Link

After deleting all subscriber data and deleting the plugin itself, there may be one more detail to consider. Namely, a way for your readers to subscribe to comments on your awesome posts. There probably a bunch of different approaches or solutions for this.

For example, if your readers are savvy like ours, you can simply replace the "Subscribe to Comments" button with a link to the RSS feed for each post. Here is a screenshot showing how this was done here at DigWP.com:

Simple link for users to subscribe to RSS feed for post comments

And the underlying code to make it happen:

<div ><a href="<?php echo get_post_comments_feed_link(); ?>" title="Post Comments RSS Feed">Comments feed for this post</a></div>

That is added directly in the theme's comments.php template. Of course, some CSS also is used to dial in everything visually. So while comments are open, each post will display an RSS icon and feed link, for example:

https://digwp.com/2018/08/secure-wp-rest-api/feed/

Using some other plugin?

If you are not using the same plugin, Subscribe to Comments, the previous SQL queries will return zero results. But the concept is the same regardless of plugin. The only thing you need to find out is the name of the database column (and/or table if necessary), and then modify the previous queries accordingly.

Why Remove Subscribe to Comments?

The main reason is that we don't get a lot of comments these days, so it's not really necessary. But more importantly, I removed the plugin to eliminate all the errors. Well, not errors they were just PHP Notices or warnings. But there were a LOT of them. Like many megabytes worth of log entries every month. So basically endless log spam. It was just time to move on.

The Subscribe to Comments plugin was an essential and awesome plugin that served us well for many years. So total respect and props for the amazing run :)


Read Full Article

Read for later

Articles marked as Favorite are saved for later viewing.
close
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview