Metabox选择数组在自定义列中显示post id而不是post name

时间:2014-04-14 19:33:02

标签: php mysql wordpress

我在wordpress的自定义页面的管理列中显示帖子名称时遇到了一些麻烦。我有一切正常工作,但是当我调用从自定义元数据下拉列表中选择的所选项目时,它会在管理列中显示帖子ID而不是帖子名称。

这是我正在使用的代码(显示列)

add_filter('manage_edit-projects_columns', 'edit_projects_columns');

function edit_projects_columns($columns) {

$columns = array(
    'cb'        => '<input type="checkbox" />',
    'title'     => __( 'Project Title' ),
    'client'    => __( 'Client' ),
    'protype'   => __( 'Project Type' ),
    'featureImage'  => __( 'Project Image' ),   
    );

return $columns;

}

显示所选字段

add_action('manage_projects_posts_custom_column', 'manage_projects_columns', 10, 2);

function manage_projects_columns($column, $post_id, $selected) {
    global $post;
    switch($column) {
        /* Display Column */
    case 'client' :
    /* Get the post meta. */
        $selected = get_post_meta($post->ID, 'a_clients', true);
        if (empty($selected))
            echo __('');
    else
            printf(__( '%s' ), $selected);
        break;

        /* End Display Column */
    /* If displaying the 'genre' column. */
        case 'protype' :
            $terms = get_the_terms($post_id, 'tagwork');
    if (!empty($terms)) {
        $out = array();
        foreach($terms as $term) {
            $out[] = sprintf('<a href="%s">%s</a>',
            esc_url(add_query_arg(array('post_type' => $post->post_type, 'tagwork' => $term->slug), 'edit.php')),
            esc_html(sanitize_term_field('tagwork', $term->name, $term->term_id, 'tagwork', 'tagwork'))
        );
        }
        echo join(', ', $out);
    } else {
        _e('');
    }
    break;

        case 'featureImage' :
        $column = get_the_post_thumbnail($post->ID, 'featureImage');

    if (empty($contact))
                echo __('');
    else
                printf(__('%s'), $contact);
    break;

    default :
    break;
    }
}

我遇到问题的所选字段是客户

/* Display Column */
case 'client' :
/* Get the post meta. */
$selected = get_post_meta($post->ID, 'a_clients', true);
if (empty($selected))
    echo __('');
else
    printf(__('%s'), $selected);
break;

它显示的是帖子ID而不是帖子名称。我该如何解决此问题?

额外注意:该列正在从项目页面的下拉菜单中提取客户端信息。菜单从我添加到客户端页面的任何新客户端中提取标题。这样我就可以将项目分配给特定的客户。

enter image description here

1 个答案:

答案 0 :(得分:1)

在您的示例$selected中分配了a_clients元值的值,该值似乎是post_id。您需要使用此post_id来获取客户端的WP_Post,然后使用post_title属性打印出正确的标题。您可以省略else,因为它只是一个空字符串。

/* Display Column */
case 'client' :
    /* Get the post meta. */
    $client_id = get_post_meta( $post->ID, 'a_clients', true );
    // Will be true if a_clients is not "" or 0 
    if ( !empty($client_id) ){
        // Get the post for the client_id
        $client = get_post($client_id);
        // If we have a title, print it out, else just use the ID
        printf( __( '%s' ), !empty($client->post_title)? $client->post_title : $client_id);
    }
    break;