WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Custom field Query Posts (3 posts)

  1. Tom
    Member
    Posted 4 years ago #

    A client needs a "related" posts where you manually enter in the related posts via a custom field.

    I've decided to insert the related posts ID's into a custom field, like so: 13,267.

    Then, using a custom query in the sidebar, I'm trying to use post__in in the query to call the numbers in the custom field. Thus far, it either breaks or only shows the first number.

    Help! I've tried it about 45,000 different ways, all resulting in nothing. Any suggestions would be greatly appreciated!

    Heres my code:

    <h2>Related Posts</h2> 
    
    	<?php $related = get_post_meta($post->ID, "related", $single=true);
    		echo $related; //To check if it works
    		$args = array_merge( array('post__in'  => array($related), $wp_query->query ) );
    
    		query_posts($args);
    		if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    
    		<div id="<?php the_ID(); ?>">
    			<a href="<?php the_permalink();?>"><p class="caption"><?php the_title(); ?></p></a>
    		</div>
    
    	<?php endwhile; else: ?>
     	<p>no related</p>
    	<?php endif; wp_reset_query();?>
  2. alchymyth
    The Sweeper & Moderator
    Posted 4 years ago #

    your custom field contains a string, not an array:
    first step is to explode this string to get the array;
    then remove the word 'array' from the $args list:

    this following seems to work in my local test installation:

    <h2>Related Posts</h2> 
    
    	<?php $related = get_post_meta($post->ID, "related", $single=true);
    		echo $related; //To check if it works
    		$related=explode(',',$related);
    		$args = array_merge( array('post__in'  => $related, $wp_query->query ) );
    
    		query_posts($args);
    		if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    
    		<div id="<?php the_ID(); ?>">
    			<a href="<?php the_permalink();?>"><p class="caption"><?php the_title(); ?></p></a>
    		</div>
    
    	<?php endwhile; else: ?>
     	<p>no related</p>
    	<?php endif; wp_reset_query();?>
  3. Tom
    Member
    Posted 4 years ago #

    @alchymyth Thank you so much! Case solved!

Topic Closed

This topic has been closed to new replies.

About this Topic