Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Garconis/4eb6d001f1bb77d467e755e3554298e6 to your computer and use it in GitHub Desktop.
Save Garconis/4eb6d001f1bb77d467e755e3554298e6 to your computer and use it in GitHub Desktop.
ACF Relationship Field posts output with shortcode
<?php
// ACF Relationship Shortcode
function shortcode_acf_relationship_news( $atts ) {
// begin output buffering
ob_start();
// variable to check if it has any News posts chosen
$news_post_variable = get_field('news');
/*
// if it does have News posts chosen, then continue...
if( $news_post_variable ):
// echo the array of IDs of the posts
echo '<pre>';
print_r( $news_post_variable );
echo '</pre>';
// helps us know if it does have posts chosen or not
echo 'Yes it has News posts chosen';
endif;
*/
$args = array(
'post_type' => array( 'post' ),
'orderby' => 'ASC',
'posts_per_page' => -1,
'post__in' => get_field('news')
);
$query = new WP_Query( $args );
// if it the News posts exist, and the CPT actually has some chosen
if ( $query->have_posts() && $news_post_variable ) {
// we have posts, so lets wrap them
echo'<h4 class="styled-acf-label acf_label">Related News Posts</h4>';
echo '<ul class="documents-wrapper">';
// Start looping over the query results.
while ( $query->have_posts() ) {
// Set up post data.
$query->the_post();
/* Contents of the queried post results go here. */
echo '<li class="documents-list">
<a href="'. get_permalink() .'" class="documents-link">
<h5 class="documents-link-title">'. get_the_title() .'</h5>
</a>
<span class="documents-date">'. get_the_date( 'F j, Y' ) .'</span>
</li>';
// close the loop WHILE
}
wp_reset_postdata();
// close post wrapper
echo '</ul>';
// end output buffering, grab the buffer contents, and empty the buffer
return ob_get_clean();
// close the query IF
}
}
add_shortcode( 'acf_relationship_news', 'shortcode_acf_relationship_news' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment