Support » How-To and Troubleshooting » Pull in post numbers from Custom Fields

Pull in post numbers from Custom Fields

  • Hi. I am trying to pull in the posts that I request in a custom field as related titles. I’m directly editing my templates.

    Example: Custom field “relatedposts” has input of “105, 107, 108, 112”

    These are the IDs of 4 posts that I want to display the titles of, underneath my post.

    So far (in index.php) I have this:

    $post_id = 105;
    $queried_post = get_post($post_id);
    <h3><?php echo $queried_post->post_title; ?></h3>

    This works but obviously doesn’t pull in the array set by the custom field. I’m not too hot on arrays, how can I achieve this?

    Thanks in advance.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Michael


    Forum Moderator

    pull in the array set by the custom field

    looks more like a string with comma separated numbers;

    try for example:

    $postlist = explode( ',', get_post_meta($post->ID, 'relatedposts', true) );
    if($postlist) foreach( $postlist as $post_id ) {
    $queried_post = get_post($post_id);
    <h3><?php echo $queried_post->post_title; ?></h3>
    <?php } ?>


    Thanks alchymyth, that works nicely.

    Do I need to set a condition, eg only process this if the ‘relatedposts’ custom field contains any content? I can write that code but can’t see if it’s necessary here. Just trying to think of ways it could break too, eg if a user puts a bad character in there.

    Moderator Michael


    Forum Moderator

    it might be good to check that the custom field is set, and that $post_id is not empty;

    for example:

    $post_ids = get_post_meta($post->ID, 'relatedposts', true);
    $postlist = explode( ',', $post_ids );
    if($post_ids && $postlist) foreach( $postlist as $post_id ) {
    if( !post_id ) continue;
    $queried_post = get_post($post_id);
    <h3><?php echo $queried_post->post_title; ?></h3>
    <?php } ?>

    Again, thanks for that. I have your code working but I’ve been trying to integrate the first image from the post as well as the title. I use the excellent code here:
    which is great for pulling that image in AND resizing it. The function I am trying to integrate is the pcrmbimagegrab()

    How would I get this to display the image using this function?

    Can anyone help to echo the resized image this function outputs as well as the title? Here’s the function.php code:

    function pcrmbimagegrab() {
    //Grabs the first image from the post
    global $post, $posts;
    $first_img = '';
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_img = $matches [1] [0];
    //Get default image instead
    $first_img = "/images/default.png";
    }return $first_img;}

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Pull in post numbers from Custom Fields’ is closed to new replies.