How to Check if Post has Taxonomy Term

Something I did not know about when working with Custom Post Types and Custom Taxonomies. Normally when checking if a regular WP Post belongs to a specific category, we can use the WordPress function in_category(). But that does not work with Custom Post Types. To check if a CPT belongs to a specific term in a Custom Taxonomy, use has_term() instead.

Check if WP Post belongs to specific category

To check if the current post belongs to a specific category, use in_category(). For example in your theme's single.php template, you can do this:

if (in_category(1)) {
	
	// post is in category with ID = 1
	
}

Here we are checking if the post belongs to category with ID = 1. You can change that to any category ID, name or slug, or an array containing multiple values.

Here is an example where mutliple categories are checked:

if (in_category('donuts')) {
	
	// post belongs to "donuts" category
	
} elseif (in_category(array('coffee', 'beer'))) {
	
	// post belongs to either "coffee" or "beer"
	
} else {
	
	// post does not belong to any of the above categories
	
}

Notice the use of an array in the elseif condition. You can specify as many categories as needed using an array of category IDs, names, or slugs.

Check if CPT belongs to specific taxonomy term

Now for the main point of this tutorial. To check if the current post belongs to a specific term in a custom taxonomy. For example, if we have a taxonomy named download_category and want to check if the current post belongs to the term combo, we can do this:

if (has_term('combo', 'download_category')) {
	
	// post belongs to "combo" in "download_category" taxonomy
	
}

When calling has_term(), the first parameter is the name of the term, and the second parameter is the name of the taxonomy.

To check multiple terms, use an array of term IDs, names, or slugs. For example:

if (has_term(array('combo', 'book', 'deal'), 'download_category')) {
	
	// post belongs to "combo", "book", or "deal" in "download_category" taxonomy
	
}

So this example will check if the current post belongs to "combo", "book", or "deal" in the "download_category" taxonomy.

Bonus Tip: Check for *any* taxonomy term

To check if the current post belongs to any term in a given taxonomy, simply leave the first parameter empty/blank. Example:

if (has_term('', 'download_category')) {
	
	// post belongs to a term in the "download_category" taxonomy
	
}

Here we are checking if the current post belongs to any term in the "download_category" taxonomy.

That's the thick and thin of it.

Bottom line is just remember:

  • Check post for category — use in_category()
  • Check post for tax term — use has_term()

Shortcode to Display Recent Posts on Any Post or Page

WordPress provides a widget that can be used to display recent posts in any sidebar or widgetized location. Likewise many WordPress themes provide some sort of "recent post" functionality, so users can display their latest posts in specific locations around the theme. Such functionality is great and useful for displaying recent posts just about anywhere in your theme. Problem is, those methods don't work for displaying recent posts inside of posts, pages, and custom post types. Like inside of post content itself. For that, we can use a shortcode.

Shortcode to the rescue

In order to display a list of related posts from within the WordPress post editor (e.g., RTE/Visal/TinyMCE or Plain-Text Editor), you can use the built-in WordPress widget or a plugin, but that may be overkill depending on your site strategy, goals, and so forth. By adding the following pretty simple slice of code your theme's functions.php file:

// recent posts shortcode
// @ https://digwp.com/2018/08/shortcode-display-recent-posts/
function shapeSpace_recent_posts_shortcode($atts, $content = null) {
	
	global $post;
	
	extract(shortcode_atts(array(
		'cat'     => '',
		'num'     => '5',
		'order'   => 'DESC',
		'orderby' => 'post_date',
	), $atts));
	
	$args = array(
		'cat'            => $cat,
		'posts_per_page' => $num,
		'order'          => $order,
		'orderby'        => $orderby,
	);
	
	$output = '';
	
	$posts = get_posts($args);
	
	foreach($posts as $post) {
		
		setup_postdata($post);
		
		$output .= '<li><a href="'. get_the_permalink() .'">'. get_the_title() .'</a></li>';
		
	}
	
	wp_reset_postdata();
	
	return '<ul>'. $output .'</ul>';
	
}
add_shortcode('recent_posts', 'shapeSpace_recent_posts_shortcode');

As is, this code creates a shortcode that gets a customizable set of posts from the WordPress database, and displays them on your post or page. As simple as "one, two three", as they say. No modifications are required, this universal "recent posts" shortcode can be added to any WordPress theme, or alternately the code can be added to your site via simple plugin.

Usage

To use the recent-posts shortcode, add the following to any WP post or page:

[recent_posts num="5" cat="7"]

That will display a list of five posts from category with ID = 7. You can customize the attributes however is desired. The shortcode also accepts a couple of other attributes, order and orderby:

[recent_posts num="10" cat="" order="asc" orderby="rand"]

So now the list will include 10 posts from any category, ordered randomly and displayed in ascending order.

Code explanation

This recent-posts technique combines the WP add_shortcode() function with the get_posts() template tag. Essentially define all the arguments, tap the database via get_posts(), and then output the results in HTML list format. And of course hook everything into WordPress via the Shortcode API. So it's actually very standard stuff, and because get_posts() uses the same parameters as WP_Query, you can do much more in terms of customizing and querying highly specific sets of posts. Check out the WP_Query docs for more ideas.


How to Change the Number of Posts Displayed On Your WordPress Blog Page

Do you want to change the number of posts displayed on your WordPress blog page? By default, all WordPress archive pages show a maximum of 10 posts per page.

However, you can change them easily from your dashboard settings and show as many articles as you like.

In this article, we will show you how to easily change the number of posts displayed on your WordPress blog page with just 2 simple steps.

Change the Number of Posts Displayed on Your WordPress Blog Page

The first thing you need to do is login to your WordPress dashboard and go to Settings » Reading page. Next, you need to change the value of ‘Blog pages show at most’ option to any number of posts you want to display.

Change Number of Posts on Your Blog Page in WordPress

Don’t forget to click on the ‘Save Changes’ button to store your settings.

Now your WordPress blog and archive pages will show the number of posts that you want to display.

How Many Posts Should I Display on My Blog Page?

Usually, bloggers display 10 posts per page as set by default. It seems an appropriate number to show from the user-experience and SEO (Search Engine Optimization) perspective.

You can display as many posts as you like, but we do not recommend choosing a number higher than 10 especially when you are not showing excerpts.

Mainly because the more posts you display on a page, the bigger the page size will be, which makes it slower to load.

On WPBeginner’s Blog and Archive pages, we show 10 posts with an excerpt and the featured image. This makes it easier for our users to browse the archives quickly, and it offers a better user experience.

We hope this article helped you change the number of posts displayed on your blog page. You may also want to see our guide on how to schedule your posts in WordPress to be published at a future time.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Change the Number of Posts Displayed On Your WordPress Blog Page appeared first on WPBeginner.

Display Your WordPress Site Statistics: Complete Guide

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.