How to add a custom column to the posts admin overview page.
In this article we will have a look at how we can add a custom culumn to the posts, or pages, overview in the WordPress admin. That page that lists all the posts or pages. There are many valid reasons why you would want to add a column here but in this article we are going to add a very silly column with a view post link. It’s silly because there already is a Preview link. So it’s up to you to come up with a meaningful function for this.
Registering the column
The first step is to actually register our new column with WordPress so that it gets added to the page. For this task we can copy the code below to the functions.php file inside of our theme.
Here we add a filter to the manage_posts_columns hook and register a callback function called add_view_post_overview_column that excepts an array with the already registered columns.
Inside our new function we first create a new array by the name of $cols. Then we loop over the passed in $columns array and add each item to our $cols array. Inside the loop we also check if the current column name is equal to ‘title’ and if so we add a new item to the $cols array by giving it a key of ‘viewpost’ and set that to a translatable string ‘View post’.
Finally we return our newly created $cols array.
With this code we know have our View post column listed to the right of the Post title column on the All posts page inside the WordPress admin.
Adding content to the new column
Now that we have our new custom column we need to fill it with some useful content. For this task we need add the following code to our function.php..
In the code above we add an action to the manage_posts_custom_column hook and register a callback function by the name of add_view_post_overview_column_content that excepts a string with the name of the current column.
Inside this function we check to see if the current column name is equal to the ‘viewpost’ column we registered earlier. If not we simply return out of the function. If it is equal we echo out a link (a) element and use the get_permalink and get_the_ID functions. to get the Url of he current post.
With all of this we should now have a new column called ‘View post’ that has a View post link on each row.
Custom columns for pages.
if we want to add a column to the Pages overview we can swap out the hooks with manage_pages_columns and manage_pages_custom_column.
That’s it. Simple but effective. 🙂
If you want to leave a comment, please do so under the copy of this article on Dev.to so i can get back to you.
Follow me on twitter @Vanaf1979 or Dev.to @Vanaf1979 or subscribe to my newsletter to be notified about new articles, and other WordPress development related resources.
Thanks for reading