Home › Forums › Front-end Issues › Query to display all posts with ACF relationship value › Reply To: Query to display all posts with ACF relationship value
Hi @Jonathan,
No it isn’t my theme, it’s just the placement of the “related posts” is on the sidebar which is out of the loop due to design issues 🙂
Hmmm, I manually typed in this URL (http://website.dev/?company=240) and it still gives me an error. Let me recap for you again, so perhaps you could point out to me what I’m doing wrong T_T
In my archives.php, here is the code:
<?php // if is a link to Read More from company single related post
if(isset($_GET['company'])){ ?>
<?php
$company_id = $_GET['company'];
// Show all related posts from the company singular page.
$items = get_posts(array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'company_relationship', // name of custom field
'value' => '"' . $company_id . '"', // matches exaclty "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE'
)
)
));
?>
<?php if( $items ): ?>
<?php endif; ?>
<?php } else { ?>
<?php while ( have_posts() ) : the_post(); // The Loop ?>
<?php get_template_part( 'content','excerpt' ); ?>
<?php endwhile; ?>
<?php } ?>
In my single-company.php, here is the code:
<?php
/*
* Query posts for a relationship value.
* This method uses the meta_query LIKE to match the string "123" to the database value a:1:{i:0;s:3:"123";} (serialized array)
*/
$posts = get_posts(array(
'post_type' => 'post',
'orderby' => 'ID',
'order' => 'DESC',
'posts_per_page'=> 1,
'meta_query' => array(
array(
'key' => 'company_relationship', // name of custom field
'value' => '"' . get_the_ID() . '"', // matches exactly "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE'
)
)
));
if( $posts ) { ?>
<div class="relatedposts">
<h5>Related Posts</h5>
<?php foreach( $posts as $post ): ?>
<?php setup_postdata($post); ?>
<?php get_template_part( 'content', 'excerpt' ); ?>
<?php endforeach; ?>
<?php
$company_ID = $post->ID; //get the id of the current company
$archive = get_post_type_archive_link('post').'?company='.$company_ID;
echo $archive;
?>
<a href="<?php echo $archive; ?>">View all</a>
</div><!-- div.relatedposts -->
<?php wp_reset_postdata(); ?>
<?php } ?>
I thank you in advance.
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.