NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Last modified : Jul 07 2021
Estimated reading time : 1 minute, 57 seconds - 197 words
Share the post "Get Post/Page quantity by user role"
With this tutorial, we will create new WordPress functions which will get the quantity of posts or post types by user role.
In the example below, the role will be chroniqueur. If we want to add a new user role, we need a new function such as the function below. Make sure to assign users to your roles if necessary.
/**************************************** Add a new role Member ***********************************/ function themespress_role_partenaire() { //add the new user role add_role( 'chroniqueur', 'Chroniqueur', array( 'read' => true, 'delete_posts' => false ) ); } add_action('admin_init', 'themespress_role_partenaire');
And then we need to query the database by checking how many posts or post types are associated with the user. Within the function, we need to set the role with the user; you can replace news_writer by author for example.
With this function, we will stock the variable used to query the database for the post or post type parameter.$post_type
function count_chahuts_by_author($post_type){ // Change here the user role $user_query = new WP_User_Query( array( 'role' => 'chroniqueur' ) ); // Get the total number of users for the current query. I use (int) only for sanitize. $users_count = (int) $user_query->get_total(); // Echo a string and the value return $users_count; }
Now we will create a shortcode that will return the value of the function above. For example our shortcode will be: [chroniqueurchahutcount]
For our example, the shortcode will return the quantity of chahuts post type which will match the chroniqueur user.
/////////////////////////////////////// Shortcode count chahut /////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// function shortcode_chroniqueurs_count_chahut(){ $user_ID = get_current_user_id(); return count_chahuts_by_author($user_ID, 'chahuts'); } add_shortcode('chroniqueurchahutcount', 'shortcode_chroniqueurs_count_chahut');
Add your [chroniqueurchahutcount] shortcode in your template or your formidable form.
Be careful as this tutorial will generate the result for a user connected with their user_id (current_user).