Метабокс, заполненный пользовательским типом записи - Как вывести CPT на основе Select?


У меня есть выпадающий метабокс, заполненный пользовательским типом записи, теперь в моем шаблоне я могу получить значение вывода метабокса, но что мне действительно нужно, так это вся информация, хранящаяся в выбранном CPT, которая будет отображаться в определенных областях сообщения.

Мой метабокс

$meta_boxes[] = array(
'id' => 'actordetails',
'title' => 'Select an Actor',
'pages' => array( 'films' ),
'context' => 'normal',
'priority' => 'high',

// List of meta fields
'fields' => array(

    array(
'name' => '',
'id' => $prefix . 'getactors',
'type' => 'select',
'clone' => false,
'options' => get_actors_options(),
    ),


)
 );

Моя функция

function get_actors_options( $query_args ) {

$args = wp_parse_args( $query_args, array(
    'post_type' => 'actors',
) );

$posts = get_posts( $args );

$post_options = array();
if ( $posts ) {
    foreach ( $posts as $post ) {
        $post_options [ $post->post_title ] = $post->post_title;
    }
}

return $post_options;
}

Вот что я получаю:

    <?php echo get_post_meta($post->ID, 'nt_getactors', true); ?>

enter image description here

Это то, что мне нужно:

enter image description here

Ну и что код, который я бы использовал для получения остальной части выбранного мной пользовательского типа записи.

Author: Marco, 2014-03-11

1 answers

Если вы установите значение метабокса для идентификатора публикации авторов cpt, вы сможете получить публикацию с помощью

//get the id for the actors cpt
$actors_id   = get_post_meta( $post->ID, 'nt_getactors', true );

//get the post obejct for the author
$actors_post = get_post( $actors_id, OBJECT ); //or ARRAY_A if you want an array and not an object

//to output e.g. the title use
$actors_post->post_title;

Смотрите get_post для получения дополнительных опций.

Обновление

Изменение

$post_options [ $post->post_title ] = $post->post_title;

До

$post_options [ $post->ID ] = $post->post_title;

Обновление 2

Используйте свой $actors_post объект post точно так же, как обычный объект post. Проверьте кодекс для хорошей ссылки на доступные переменные-члены.

Например,

$actors_post->post_content;

Имейте в виду, что данные $actors_post являются "необработанными", и вы можете применить к ним некоторые фильтры, в зависимости от того, как вы их используете; например,

apply_filters( 'the_content', $actors_post->post_content );

Обновление 3

Чтобы получить мета-значения из сообщения актера, либо сделайте это для одного значения

get_post_meta( $actor_post->ID, 'ecpt_bio', true );

Или (если у вас несколько значений, вы можете получить их все в одном массиве) следующим образом:

$actor_meta = get_post_meta( $actor_post->ID );
//and then access the array element
echo $actor_meta['ecpt_bio'];

Завершите

Измените функцию обратного вызова, чтобы ссылаться на идентификатор сообщения вместо заголовка (см. Обновление #1)

//get the id for the actors cpt
$actors_id   = get_post_meta( $post->ID, 'nt_getactors', true );

//get the post obejct for the author
$actors_post = get_post( $actors_id, OBJECT );

//to output e.g. the title use
echo apply_filters( 'the_title', $actors_post->post_title );

//output the content
echo apply_filters( 'the_content', $actors_post->post_content );

//get the meta values from the actor post
$actor_meta = get_post_meta( $actor_post->ID );

//and output it like this
echo $actor_meta[ 'ecpt_bio' ];
 4
Author: alpipego, 2014-03-14 08:52:27