0

I've created a Custom Post Type for "Books" ... I've also added several meta fields (custom fields) to each book, and I'd like to be able to display some of those fields in the table of results.

Is there a way to hook into the data table and add the custom fields?

enter image description here

1

There are a couple filters for that. I wrote a tutorial about adding custom columns, which is where the code below is from. The example is adding a column to the 'page' post type that displays the page's template.

You can hook into load-edit.php and use get_current_screen to grab the correct screen ID's/filters. From there you hook into manage_{$screen->id}_columns and manage_{$screen->post_type}_posts_custom_column

<?php
add_action('load-edit.php', 'pmg_ltt_load');
function pmg_ltt_load()
{
    $screen = get_current_screen();

    if(!isset($screen->post_type) || 'page' != $screen->post_type)
        return;

    add_filter(
        "manage_{$screen->id}_columns",
        'pmg_ltt_add_columns'
    );

    add_action(
        "manage_{$screen->post_type}_posts_custom_column",
        'pmg_ltt_column_cb',
        10,
        2
    );
}

manage_{$screen->id}_columns is what actually adds the column and manage_{$screen->post_type}_posts_custom_column is your callback.

Add the column:

<?php
function pmg_ltt_add_columns($cols)
{
    // pay attention to the key, you'll use it later.
    $cols['template'] = __('Page Template', 'pmg-list-table');
    return $cols;
}

And the callback function will get two argument: the column key (what you used above!) and the post ID. Check to make sure it's the column you want, then use get_post_meta (or whatever else appropriate to the situation) to fetch the stuff you want to display.

<?php
function pmg_ltt_column_cb($col, $post_id)
{
    static $templates;

    if('template' == $col)
    {
        if(empty($templates))
            $templates = array_flip(get_page_templates());

        $tmp = get_post_meta($post_id, '_wp_page_template', true);
        if($tmp && isset($templates[$tmp]))
        {
            echo esc_html($templates[$tmp]);
        }
        else
        {
            esc_html_e('Default Template', 'pmg-list-table');
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.