Last active
August 29, 2015 14:08
-
-
Save mitchelldmiller/cc32ab547aa028294f2a to your computer and use it in GitHub Desktop.
Find out if your WordPress blog contains posts with more than one category
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated November 28, 2014