How to Add Custom Posts Column In users.php – WordPress

Here we learn about how to add custom posts column in users.php without editing the core files.

There are two hook filter to include custom posts column in users.php.

  • manage_users_columns
  • manage_users_custom_column

1. manage_users_columns

This function provides an array of column names for argument.

The column name is as simple as adding an associative array.

In this case, the column is called contributes.

Example:

<?php
function contributes( $columns ) {
  $columns['contributes'] = __( 'Contributes', 'contributes' );
  return $columns;
}
add_filter( 'manage_users_columns', 'contributes' );
?>

2. manage_users_custom_column

syntax:

<?php apply_filters( 'manage_users_custom_column', string $output, string $column_name, int $user_id ); ?>

This filters display custom columns in the Users list table.

Parameters:

  • $output – (string) column output.
  • $column_name – (string) Pass column name.
  • $user_id – (int) ID of currently-listed user.

Example:

<?php
function contributes_columns( $value, $column_name, $user_id ) {
  if ( 'contributes' != $column_name )//Replace 'contributes' with the column name from the filter you previously created
    return $value;
  global $wp_query;
  $posts 		 = query_posts('post_type=contribute&author='.$user_id.'&order=ASC&posts_per_page=30');//Replace post_type=contribute with the post_type=yourCustomPostName
  $posts_count = count($posts);
  $posts_count = "<a href='".site_url()."/wp-admin/edit.php?author={$user_id}&post_type=contribute'>{$posts_count}</a>";
    
  return $posts_count;
}
add_action( 'manage_users_custom_column', 'contributes_columns', 10, 3 );	
?>

Here is Complete Custom code copied and paste into your child theme’s functions.php file.

<?php
function contributes( $columns ) {
  $columns['contributes'] = __( 'Contributes', 'contributes' );
  return $columns;
}
add_filter( 'manage_users_columns', 'contributes' );

function contributes_columns( $value, $column_name, $user_id ) {
  if ( 'contributes' != $column_name )//Replace 'contributes' with the column name from the filter you previously created
    return $value;
  global $wp_query;
  $posts 		 = query_posts('post_type=contribute&author='.$user_id.'&order=ASC&posts_per_page=30');//Replace post_type=contribute with the post_type=yourCustomPostName
  $posts_count = count($posts);
  $posts_count = "<a href='".site_url()."/wp-admin/edit.php?author={$user_id}&post_type=contribute'>{$posts_count}</a>";
    
  return $posts_count;
}
add_action( 'manage_users_custom_column', 'contributes_columns', 10, 3 );
?>

OUTPUT:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories