• Resolved greencode

    (@greencode)


    I have the following:

    <ul>
     <?php
     $key = get_post_meta($post->ID, 'custom-field-name', true);
     global $post;
     $myposts = get_posts(array('post__in' => array("$key"), 'posts_per_page' => -1));
     foreach($myposts as $post) :
       setup_postdata($post);
     ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
     <?php endforeach; ?>
     </ul>

    so that whatever value is in the specified custom field is then passed through to the get_posts query. This works well if there’s only one number but if I add more than one it still only shows the first post e.g. array(1) – will show post with ID of 1. array(1,2,3) – will still only show post with ID of 1 and not all three as specified.

    If I type these in directly to the code then everything works and shows perfectly but it’s when I pass it through the custom field.

    Any ideas?

Viewing 4 replies - 1 through 4 (of 4 total)
  • $key, as you get it from the custom field, is a string (which contains commata), but not an array.

    you could try:

    $key = get_post_meta($post->ID, 'custom-field-name', true);
    
    $key = explode(',', $key);
    function trim_value(&$value)
    {
        $value = (int)trim($value);
    }
    array_walk($key, 'trim_value');

    to convert it into a integer array.

    http://php.net/manual/en/function.explode.php
    http://php.net/manual/en/function.trim.php

    if this does not work, you could try without the ” around $key in this line:

    $myposts = get_posts(array('post__in' => array("$key"), 'posts_per_page' => -1));

    Thread Starter greencode

    (@greencode)

    Thanks for helping here – much appreciated. I now have the following code but nothing is being displayed:

    <ul>
     <?php
    $key = get_post_meta($post->ID, 'custom-field-name', true);
    $key = explode(',', $key);
    function trim_value(&$value)
    {
        $value = (int)trim($value);
    }
    array_walk($key, 'trim_value');
     $myposts = get_posts(array('post__in' => array($key), 'posts_per_page' => -1));
     foreach($myposts as $post) :
       setup_postdata($post);
     ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
     <?php endforeach; ?>
     </ul>

    my bad – i did not think to the end:

    $key is the array; so using array($key) does not make sense.

    this should work:

    $myposts = get_posts(array('post__in' => $key, 'posts_per_page' => -1));
    Thread Starter greencode

    (@greencode)

    YAY, Thank you so much for your help with this – just tried again and it works perfectly. A great end to a frustrating weekend 😉

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Pass custom field value to get_posts query’ is closed to new replies.