Home › Forums › Front-end Issues › Relationship field in BBpress forum post › Reply To: Relationship field in BBpress forum post
Okay… if anyone else has this issue… I have it working. Here is the code for adding a relationship field to a bbPress topic, saving/updating the value, and spitting it out on the front end. This allows the user to choose a related piece of content (such as a blog post) to show along with their topic post.
Note: I set the relationship field to just return the post ID. If you want to return the post object, you’d need to modify this.
// Inserts the field group into the bbPress form
add_action ( 'bbp_theme_after_topic_form_content', 'bbp_extra_fields');
function bbp_extra_fields() {
$options = array(
'field_groups' => array(123456), // replace with your ID
'form' => false
);
acf_form($options);
}
// This saves/updates the value when the topic is saved
add_action ( 'bbp_new_topic', 'bbp_save_extra_fields', 10, 1 );
add_action ( 'bbp_edit_topic', 'bbp_save_extra_fields', 10, 1 );
function bbp_save_extra_fields($topic_id=0) {
if (isset($_POST) && is_array($_POST['acf']['field_123456789'])) {
$value = $_POST['acf']['field_123456789'];
update_field( 'field_123456789', $value, $topic_id );
}
}
// This spits the related content out as a link on the front end, after the topic content
add_action('bbp_theme_after_reply_content', 'bbp_show_extra_fields');
function bbp_show_extra_fields() {
$topic_id = bbp_get_topic_id();
if ( function_exists('get_field') && get_field('related_field_name', $topic_id) ) {
$related_posts = get_field('related_field_name', $topic_id);
foreach ($related_posts as $related_post) {
if (get_post_status( $related_post) == 'publish') {
echo '<a href="' . get_permalink( $related_post) . '" class="btn">' . get_the_title( $related_post) . '</a>';
}
}
}
}
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.