sinanisler logo

Adding Custom Column to the Admin Posts List View

Read custom field if there is any show it on the posts list view as new column

on this example the code creates a day column and shows the day as a date calculating publish date between the custom field date.

This code adds a new column called “Ads Unpublish Day” to the posts list in WordPress. The column displays a custom field value, which represents the number of days after the post’s publish date that the ad should be unpublished. If the custom field is not set, the column displays “N/A”. The code also includes optional features to make the new column sortable and set the sorting query for the column. The function add_filter is used to add filters to specific WordPress actions, while the function add_action is used to add a new action to the WordPress action queue. The code demonstrates how WordPress allows for the customization of the user interface and the query for data in a flexible and extensible manner.



// Add a new column to the posts list
function add_day_column($columns) {
    $columns['day'] = __('Ads Unpublish Day', 'text_domain');
    return $columns;
add_filter('manage_posts_columns', 'add_day_column');

// Display the custom field value in the new column
function display_day_column_data($column, $post_id) {
    if ($column === 'day') {
        $day = get_post_meta($post_id, 'day', true);

        if (!empty($day)) {
            // Get the post publish date
            $post_date = get_the_date('Y-m-d', $post_id);
            $date_obj = DateTime::createFromFormat('Y-m-d', $post_date);

            // Add the day number as days to the date
            $date_obj->modify("+$day days");

            // Display the calculated date
            echo $date_obj->format('Y-m-d');
        } else {
            echo __('N/A', 'text_domain');
add_action('manage_posts_custom_column', 'display_day_column_data', 10, 2);

// Optional: Make the 'Day' column sortable
function day_column_register_sortable($columns) {
    $columns['day'] = 'day';
    return $columns;
add_filter('manage_edit-post_sortable_columns', 'day_column_register_sortable');

// Optional: Set the sorting query for the 'Day' column
function day_column_orderby($query) {
    if (!is_admin() || !$query->is_main_query()) {

    $orderby = $query->get('orderby');

    if ('day' === $orderby) {
        $query->set('meta_key', 'day');
        $query->set('orderby', 'meta_value_num');
add_action('pre_get_posts', 'day_column_orderby');


Leave the first comment