Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find out if your WordPress blog contains posts with more than one category
<?php
/**
* mdm_wp_multiple_categories.php
*
* Find out if your WordPress blog contains posts with more than one category.
*
* Use as a standalone page or a function with WordPress.
*
* Function uses param to return string message or count of posts with multiple categories.
*/
if (!defined('ABSPATH'))
{
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
header('Content-type: text/plain');
echo mdm_wp_multiple_categories(), "\r\n";
exit;
}
/**
* Counts posts with multiple categories
*
* @param bool $text
* @return string|int
* if ($text == true) return string: informative message
* else return integer: count of posts with multiple categories
*/
function mdm_wp_multiple_categories($text = true)
{
global $wpdb;
$result = $wpdb->get_results("select ID from wp_posts where post_type = 'post' and post_status = 'publish'", ARRAY_N);
if (!is_array($result) || empty($result))
{
return 'No posts were found';
}
$multiple = 0;
$total = count($result);
foreach ($result as $k => $v)
{
$cats = get_the_category($v[0]);
// $cats is an array or false if no categories were found.
// user cannot save a post without a category, but nothing is certain.
// check for array first. PHP expressions are evaluated left to right.
if ( is_array( $cats ) && count( $cats ) > 1 )
{
$multiple++;
}
} // end foreach
return $text ? "{$multiple} / {$total} posts have multiple categories" : $multiple;
} // end mdm_wp_multiple_categories
?>
@mitchelldmiller

This comment has been minimized.

Copy link
Owner Author

mitchelldmiller commented Nov 28, 2014

Updated November 28, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.