I would like to add a 'Post Author' select option in my Wordpress posts. Instead of creating 30 or so different users in Wordpress I would like to populate an ACF dropdown select field with all the titles of a custom post type (staff).
I found this code for outputting a list of custom post type titles...
// 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' );
...and I found this code from an ACF article about dynamically populating a select box...
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');
...however I'm really not sure how to splice the two together so that it grabs my custom field titles and adds them to that ACF field selector.
I tried but couldn't get any results to display.
Any ideas?
Thanks to the comment from mmmm I was able to use the 'Relationship' field type in ACF to achieve what I wanted... here is my code for anyone interested
'post-author' is the name of the ACF field, which was set to relationship, and the custom post type 'staff' was selected from the options, so I can choose any member of staff. They are then outputted in the post with thumbnail and job title...
<?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; ?>