使用自定义帖子类型的标题列表作为 ACF 字段的值

问题描述 投票:0回答:1

我想在我的 WordPress 帖子中添加“帖子作者”选择选项。我不想在 WordPress 中创建 30 个左右的不同用户,而是想用自定义帖子类型(员工)的所有标题填充 ACF 下拉选择字段。

我发现这个代码用于输出自定义帖子类型标题列表......

 // query for your post type
$post_type_query  = new WP_Query(  
array (  
    'post_type'      => 'your-post-type',  
    'posts_per_page' => -1  
)  
);   
// we need the array of posts
$posts_array      = $post_type_query->posts;   
// create a list with needed information
// the key equals the ID, the value is the post_title
$post_title_array = wp_list_pluck( $posts_array, 'post_title', 'ID' );

...我从一篇关于动态填充选择框的 ACF 文章中找到了这段代码...

function acf_load_color_field_choices( $field ) {

// reset choices
$field['choices'] = array();


// get the textarea value from options page without any formatting
$choices = get_field('my_select_values', 'option', false);


// explode the value so that each line is a new array piece
$choices = explode("\n", $choices);


// remove any unwanted white space
$choices = array_map('trim', $choices);


// loop through array and add to field 'choices'
if( is_array($choices) ) {

    foreach( $choices as $choice ) {

        $field['choices'][ $choice ] = $choice;

    }

}


// return the field
return $field;

}

add_filter('acf/load_field/name=color', 'acf_load_color_field_choices');

...但是我真的不确定如何将两者拼接在一起,以便它获取我的自定义字段标题并将它们添加到该 ACF 字段选择器中。

我尝试过,但无法显示任何结果。

有什么想法吗?

php wordpress advanced-custom-fields custom-post-type
1个回答
0
投票

感谢 mmmm 的评论,我能够使用 ACF 中的“关系”字段类型来实现我想要的...这是我的代码,供任何感兴趣的人

'post-author'是ACF字段的名称,它被设置为relationship,并且从选项中选择了自定义帖子类型'staff',所以我可以选择任何工作人员。然后将它们连同缩略图和职位名称一起输出到帖子中......

<?php

$posts = get_field( 'post-author' );

if ( $posts ): ?>

<?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
<?php setup_postdata($post); ?>

<div class="author">
<?php the_post_thumbnail('small'); ?>
<div class="author-text">
    <a href="<?php the_permalink(); ?>">
        <?php the_title(); ?>
    </a>
    <p>
        <?php the_field('job_title') ?>
    </p>
</div>
<div class="clearfix"></div>
</div>

<?php endforeach; ?>

<?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif; ?>
© www.soinside.com 2019 - 2024. All rights reserved.