Home › Forums › Front-end Issues › Relationships to un-published content
I have a content type called “partner”. Each partner has a list of “issues” that they support. “Issue” is a relationship field to a 2nd content type called “issue”. On the partners page I just loop through the relationship field and create links to all of the issues.
The issue (no pun intended) is that if the client un-publishes any of the issues then my partner pages may end up spitting out links to pages that are now in draft form which isn’t ideal.
I can get around it like this…
$issues = get_field('issues');
foreach ( $issues as $issue ) {
if ($issue->post_status == 'publish') { ?><a href="<?php echo get_permalink( $issue->ID ); ?>" class="btn"><?php echo get_the_title( $issue->ID ); ?></a>
<?php }
} ?>
… but I’m wondering if there’s a better, more global way to do that. I’ve used the ‘acf/fields/relationship/query’ filter to make sure that only published issues show up in the relationship field but this doesn’t help if the relationship already exists and the content is later unpublished. Is there any type of filter I could use to make this happen for ALL relationship fields anywhere on the site without having to go modify the code loops one by one?
Hi @jaybuys
I believe you can do it with this code:
function my_acf_load_value( $value, $post_id, $field )
{
// run the_content filter on all textarea values
$returned_value = array();
foreach($value as $key => $id){
if( get_post_status( $id ) == 'publish' ){
$returned_value[] = $id;
}
}
return $returned_value;
}
add_filter('acf/load_value/type=relationship', 'my_acf_load_value', 10, 3);
I hope this helps.
Terrific! Thank you!
For anyone who may stumble on this thread… if you don’t require at least one selection to be made in your relationship fields then you may end up with a bunch of PHP warnings as it tries to check what are essentially null values. Just wrap this code in a conditional to make sure a value exists before looping through the items, like so…
if ($value) {
foreach($value as $key => $id){
if( get_post_status( $id ) == 'publish' ){
$returned_value[] = $id;
}
}
}
The topic ‘Relationships to un-published content’ is closed to new replies.
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.