Support

Account

Home Forums Front-end Issues Query to display all posts with ACF relationship value

Solving

Query to display all posts with ACF relationship value

  • Hi ACF,

    Adore this plugin to bits.

    I’m having a little trouble trying to make a dynamic query for a relationship field.

    Currently, I have a custom post type called “Company”. In every post, you have the ACF custom field to choose which Company you want to associate this post with. I have successfully been able to use this query (the last section) to display, on the singular Company page, related posts that have been associated with this company.

    However, if I have like a hundred posts, is there a way I can display X no. of posts, and have a “View More” link to go to a page to show these hundred posts with the relationship field value of the ACF of the company?

    Thank you very much in advance.

  • Hi Nataliette (cool name)

    You can limit the number of posts by adding ‘posts_per_page’ => 5
    to the query. Change 5 to whatever number you want.

    As for setting a view more link that’s a bit more complicated since there’s no default archive for posts queried by meta value. I suppose you could do something like this:

    
    <?php 
    $company_ID = $post->ID; //get the id of the current company
    $archive = get_post_type_archive_link('post').'?company='.$company_ID;
    ?>
    <a href="<?php echo $archive; ?>">Read more</a>
    

    This would mean that when you click the read more you get sent to the regular post archive but with an GET parameter.. Then on archive.php you can do a check for this parameter and if it’s present query all posts with that meta value.

    
    if(isset($_GET['company'])){
    
    }
    
  • Hi Jonathan!

    Thanks so much for your fast reply!

    You’re right, that’s exactly what I was looking for – creating an archive for posts queried by meta value from the “relationship” ACF.

    Although I had no idea we could query an archive with a GET parameter (am more of self-taught “developer” myself), your solution makes sense.

    I made a conditional statement with your if(isset($_GET['company'])){, but it gives me an error.

    The URL I was directed to with your read more link was:

    http://example.com/companies/?company=225

    Which doesn’t seem quite right. Is that where the problem lies?

    Thank you in advance!

    P/S. Haha, glad you like the name πŸ™‚

  • In case I messed something up, here’s the code I used on my single-company.php to generate the Read More link:

    <?php 
    $company_ID = $post->ID; //get the id of the current company
    $archive = get_post_type_archive_link('post').'?company='.$company_ID;
    ?>

    and here’s the code on my archive.php page:

    <?php get_header(); ?>
    <?php // if is a link to Read More from company single related post
    if(isset($_GET['company'])){ ?>
    	Show all related posts from the company's singular page.
    <?php } else { ?>
    	<?php while ( have_posts() ) : the_post(); // The Loop ?>
                <?php get_template_part( 'content','excerpt' ); ?>
    	<?php endwhile; ?>
    <?php } ?>
    <?php get_footer(); ?>
  • I’m a self-taught developer myself πŸ™‚ I think it’s quite common in our line of work..

    Sorry I think this is more like it:

    
    if (!empty($_GET['company'])) {
        // we got company....
    }
    

    The URL you are directed to is probably not correct if you’re supposed to end up on the regular posts archive.. You can try switching the $archive variable out and replace it with a “hardcoded” url to the archive page.. Right not it seems like it’s trying to go to the archive of companies.

  • Another self-taught chiming in…

    Building on Jonathan’s example, I would create a separate template for company post archives. Then you would just change the get_template_part function call to get_template_part( ‘content’,’company-posts’ ); or similar, and skip the “if($_GET)” validation stuff.

    A bit strange you’re being directed to ../companies/ if your post-type slug is ‘company’ since archives aren’t automatically pluralized.

    Lastly, what error are you getting?

  • Hi Jonathan and Wells5609;

    I’m getting more and more lost! Lol. Basically the posts which has selected a certain Company custom post shows up beautifully as “related posts” in that Company’s single-company.php using this query on my single-company.php.

    However I’ll require a link to “View More” after showing only 3 posts as related posts which should point to an archive page of posts which has the Company selected.

    Like Jonathan said, “since there’s no default archive for posts queried by meta value”, I am stuck πŸ™ Unfortunately, his solution yielded an error saying that no posts exist at the URL: http://example.com/companies/?company=225

    Helppp D:

  • Hi, could anyone help me with this?

    I basically need a way to dynamically generate an archive of all normal posts that have a “relationship” with the Company-post-type.

    Thank you in advance.

  • Hello again Nataliette.

    With my previous solution, did you create a loop inside the if-statement for when you have company posts?

    
    <?php get_header(); ?>
    <?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's singular page.
    $doctors = get_posts(array(
    							'post_type' => 'doctor',
    							'meta_query' => array(
    								array(
    									'key' => 'location', // name of custom field
    									'value' => '"' . $company_id . '"', // matches exaclty "123", not just 123. This prevents a match for "1234"
    									'compare' => 'LIKE'
    								)
    							)
    						));
     
    						?>
    						<?php if( $doctors ): ?>
    
    //ETC. This is not a full loop
    ?>
    <?php } else { ?>
    	<?php while ( have_posts() ) : the_post(); // The Loop ?>
                <?php get_template_part( 'content','excerpt' ); ?>
    	<?php endwhile; ?>
    <?php } ?>
    <?php get_footer(); ?>
    
    
  • Hi Jonathan,

    I believe the code you provided above is the code to be put in archives.php right? I can’t get it to work unless the “View all” link from the company-single.php works, which doesnt:

    
    <?php 
    $company_ID = $post->ID; //get the id of the current company
    $archive = get_post_type_archive_link('post').'?company='.$company_ID;
    ?>
    
  • ahaaa okay.

    Well if you try to echo out the second row what do you get?

  • Hi @Jonathan,

    Ah, when I echo out $archive, I get ?company=862. Yet the Company’s Post ID is 240.

    I believe this is the same out-of-the-loop issue you also helped me with awhile back here!

    However, even when I manually changed the link to 240, the URL is still:

    http://website.dev/en/companies/COMPANY_NAME/?company=240

    Which still gives me the error. Is this URL format correct?

  • I think your theme is all wack.. getting loop issues and stuff all the time.

    I don’t think thats the actual link but rather the a-tag is linked with just /?company=240 and since there’s nothing before that the link appears to go to that URL (which is the same as the one your on right?).

    So that means get_post_type_archive_link isn’t working. What version of WP do you run? You’ll need to have it up to date (or atleast 3.1) for the function to work.

  • 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.

  • Hi!

    First off, move wp_reset_postdata(); right under the endforeach; in your related posts loop.. that should fix the error with the incorrect ID.

    Secondly.. there doesn’t seem to be a default archive link for posts if you don’t include a date or category tag (like http://www.demo.com/2012/). I honestly cant think of a smooth way to solve this the way it’s set up at the moment.. If I where you I’d either rethink it all or id create categories thats named the same as the companies but with a permalink of something like companyname-cat and assign the posts to them as well. That way you could just put this for the readmore link:

    
    <?php
    $cat = get_category_by_slug($post->slug.'-cat');
    $catlink = get_category_link($cat->term_id);
    ?>
    <a href="<?php echo $catlink; ?>">View all</a>
    

    then you can check in archive.php if it’s trying to display a category with

    
    if(is_cat()){
    //the archive is displaying posts from a category
    }
    

    If this solution doesn’t work you could create a custom taxonomy and assign it to the posts (besides categories and tags) and use them instead and change the functions accordingly..

    
    
    <?php
    $cat = get_term_by('slug, '$post->slug.'-cat', 'your-taxonomy-slugname');
    $catlink = get_category_link($cat->term_id);
    ?>
    <a href="<?php echo $catlink; ?>">View all</a>
    
    

    and:

    
    if(is_tax()){
    
    //the archive is displaying a term from a taxoonomy
    }
    
Viewing 15 posts - 1 through 15 (of 15 total)

The topic ‘Query to display all posts with ACF relationship value’ is closed to new replies.