VERSION 1 will query all the images and give you a count by checking the size of the returned array. VERSION 2 is a much faster method introduced by birgire.
// VERSION 1
$images = get_posts(array(
'post_type' => 'attachment',
'post_status' => 'any',
'numberposts' => -1,
'fields' => 'ids',
'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',
));
echo count($images) . ' images total';
// VERSION 2
$count = array_sum( (array) wp_count_attachments( 'image' ) );
echo "{$count} images total";
ORIGINAL – For a full XML-RPC solution, create a custom method.
function xml_add_method( $methods ) {
$methods['myNamespace.attachmentCount'] = 'get_attachment_count';
return $methods;
}
add_filter( 'xmlrpc_methods', 'xml_add_method' );
function get_attachment_count( $args ) {
// good to know it's here
// global $wpdb;
// params passed in the call - not needed in this example
$params = $args[3];
// count the posts then return the total value
$images = get_posts(array(
'post_type' => 'attachment',
'post_status' => 'any',
'numberposts' => -1,
'fields' => 'ids',
'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',
));
// images total
return count($images);
}
Then do the RPC
global $current_user;
$user = $current_user->user_login;
$password = $user->data->user_pass;
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );
$xmlrpc_url = home_url('xmlrpc.php');
$client = new WP_HTTP_IXR_CLIENT( $xmlrpc_url );
// set this to true if you need help
// $client->debug = true;
$response = $client->query( 'myNamespace.attachmentCount', array(
0,
$user,
$password,
array(
'post_type' => 'attachment',
'post_status' => 'any',
)
) );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
$count = $client->message->params[0]; // our return value is here
print_r( $count . ' images total' );
echo '</pre>';
}
UPDATE
Merging @birgire’s solution into this one.
add_filter('xmlrpc_methods', function ($methods) {
$methods['myNamespace.getTotalImageCount'] = 'rpc_myNamespace_getTotalImageCount';
return $methods;
});
function rpc_myNamespace_getTotalImageCount($args)
{
return array_sum((array)wp_count_attachments('image'));
}
add_action('parse_request', function () {
// PULL USER CREDS FROM CURRENT USER
global $current_user;
$user = $current_user->user_login;
$password = $user->data->user_pass;
include_once(ABSPATH . WPINC . '/class-IXR.php');
include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
$xmlrpc_url = home_url('xmlrpc.php');
$client = new WP_HTTP_IXR_CLIENT($xmlrpc_url);
// CALL OUR CUSTOM METHOD
$response = $client->query('myNamespace.getTotalImageCount', array(0, $user, $password));
echo 'Response:<pre>';
$count = $client->message->params[0];
print_r("{$count} total images");
echo '</pre>';
wp_die('FIN');
});