Categories
Web Development

WordPress: Additional Admin Columns with ACF

In functions.php, add the following and change [post_type] for the post type of the table you want to alter.

If you have used ACF,  you can find the post type in the ur e.g.

  • /wp-admin/edit.php?post_type=jobs
// Add the custom columns to the [post_type] post type:
add_filter( 'manage_[post_type]_posts_columns', 'set_custom_edit_[post_type]_columns' );
function set_custom_edit_[post_type]_columns($columns) {
    unset( $columns['author'] );
    $columns['yourFieldKey'] = __( 'yourFieldName', 'your_text_domain' );

    return $columns;
}

// Add the data to the custom columns for the [post_type] post type:
add_action( 'manage_[post_type]_posts_custom_column' , 'custom_[post_type]_column', 10, 2 );
function custom_[post_type]_column( $column, $post_id ) {
    switch ( $column ) {

        case 'yourFieldKey' :
            // Job Store
            if ( 'yourFieldKey' === $column ) {
                $data = get_field('yourFieldKey', $post_id);

                if ( ! $data ) {
                    _e( 'N/A' );
                } else {
                    echo $data->post_title;
                }
            }

        break;
    }
}

// Make Title Clickable
add_filter( 'manage_edit-[post_type]_sortable_columns', '[post_type]_sortable_columns');
function [post_type]_sortable_columns( $columns ) {
    $columns['yourFieldKey'] = 'yourFieldKey';
    return $columns;
}

// Make data sortable
add_action( 'pre_get_posts', 'posts_orderby' );
function posts_orderby( $query ) {
    if( ! is_admin() || ! $query->is_main_query() ) {
        return;
    }

    if ( 'yourFieldKey' === $query->get( 'orderby') ) {
        $query->set( 'orderby', 'meta_value' );
        $query->set( 'meta_key', 'yourFieldKey' );
    }
}

 

Leave a Reply