Home › Forums › ACF PRO › If relationship field has only draft posts then hide this section › Reply To: If relationship field has only draft posts then hide this section
Hi John, thank you for your advice.
For some reason filter is not working when it’s added to the page. Definitely works when add_action is being added to the functions.php, but it’s preventing me from seeing any drafts on the site.
<?php
if (get_field('alternative_method')):
// add filter to only get published posts
add_action('pre_get_posts', 'acf_field_only_published_posts', 10, 1);
// get field
$alt_posts = get_field('alternative_method');
// remove the filter so it does not affect other queries
remove_filter('pre_get_posts', 'acf_field_only_published_posts');
if (!empty($alt_posts)): ?>
<section id="alt-method">
<div class="text full">
<h2>Alternative methods</h2>
</div>
<div class="recipes-list item-listing">
<?php foreach( $alt_posts as $post ):
setup_postdata($post); ?>
<?php if ( get_post_status() == 'publish' ) :?>
<?php get_template_part( 'template-parts/content-recipe-card', get_post_format() ); ?>
<?php endif;?>
<?php endforeach; ?>
<?php
wp_reset_postdata(); ?>
</div>
</section>
<?php endif; ?>
<?php endif; ?>
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.