1

it would be smart to check if a custom column exists when creating the logic for it when building your custom post type. what would the code be to check if_exists or similar?

my CPT column code is below:

//set up new column to show custom meta value
function site_title_column($column) {
    $column['views'] = 'Title';
    return $column;
}

add_filter('manage_attorneys_posts_columns', 'site_title_column');

//show custom column data
function site_show_title_column($name) {
    global $post;
    switch ($name) {
        case 'views':
            $title = get_post_meta($post->ID, '_site_professional_title', true);
            echo $title;
    }
}

add_action('manage_attorneys_posts_custom_column',  'site_show_title_column');

would it be the following?

//set up new column to show custom meta value
function site_title_column($column) {
    $column['views'] = 'Title';

    //if this value is blank, then it does not currently exist, 
    //...so output our custom $column:
    if ($column != NULL) {
       return $column;
    } else {
       return;
    }

    add_filter('manage_attorneys_posts_columns', 'site_title_column');
1

You should first check, and then assign your custom column. $column should really be $columns to convey the real meaning, as it's an array.

So, you need to check if the array key exists before the assignment with something like isset() or array_key_exists().

Finally, since your site_title_column() function modifies the value of a filter, you should always return a value (usually the original, perhaps modified), as simply calling return; returns NULL (which is rarely what's needed).

I'd rewrite your function as such:

function site_title_column( $columns ) {
    if ( ! isset( $columns['views'] ) ) {
        $columns['views'] = 'Title';
    }
    return $columns;
}
  • ah ok - checking array key - makes perfect sense! thank you so much for the detailed response. positive energy! – Zach Smith Jun 21 '17 at 16:32

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.