Add a profile picture column in the post list admin page – Learn WordPress from a to z

Tutorials 0 lượt xem

Do you want to display the profile picture outside the post list page?

Today I will show you how to do that. But first, let’s take a look at the results you will achieve.

Add new column for profile picture

Please copy the code below into the file functions.php of the theme you are using.

add_filter('manage_post_posts_columns', 'hk_featured_image_column');
function hk_featured_image_column( $column_array ) {

	$column_array = array_slice( $column_array, 0, 1, true )
	+ array('featured_image' => 'Ảnh đại diện')
	+ array_slice( $column_array, 1, NULL, true );
 
	return $column_array;
}

add_action('manage_posts_custom_column', 'hk_render_the_column', 10, 2);
function hk_render_the_column( $column_name, $post_id ) {

	if( $column_name == 'featured_image' ) {

		if( has_post_thumbnail( $post_id ) ) {
			
			$thumb_id = get_post_thumbnail_id( $post_id );
			echo '<img data-id="' . $thumb_id . '" src="'%20.%20wp_get_attachment_url(%20%24thumb_id%20)%20.%20'">';
			
		} else {
			
			echo '<img data-id="-1" src="'%20.%20get_stylesheet_directory_uri()%20.%20'/placeholder.png">';
			
		}
		
	}

}
<div>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span><span>11</span><span>12</span><span>13</span><span>14</span><span>15</span><span>16</span><span>17</span><span>18</span><span>19</span><span>20</span><span>21</span><span>22</span><span>23</span><span>24</span><span>25</span><span>26</span><span>27</span><span>28</span><span>29</span>
</div>

In the above code, I use 2 hooks. The first is the manage_post_posts_columns hook, which will allow you to add a new column to the Posts table . The second hook is manage_posts_custom_column , which will dump data into your column.

After you complete the above step, you will get a result like this.

Show avatar step 1

Because for each post, the avatar image is different in size, causing the admin interface to break. Let’s go to the next step to handle this.

Add CSS code to admin page

Continue adding the code below to the functions.php file .

add_action( 'admin_head', 'hk_custom_css' );
function hk_custom_css(){

	echo '';

}
<div>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span><span>11</span><span>12</span><span>13</span><span>14</span>
</div>

So it’s done. You will get results like the image at the top of this article.

Epilogue

I hope the above article will help you manage your posts better.

If this article was helpful and saved your time, please help me share it. Also if you are interested in similar topics, read other WordPress Tips articles and follow Fanpage so you don’t miss new posts from me.

Bài viết liên quan