WordPress.org

Support

Support » How-To and Troubleshooting » How to put custom field data dynamically into WP_query

How to put custom field data dynamically into WP_query

  • I have a basic query that displays latest news, but I added a custom field in the post editor so the user can define the Post ID’s of the specific latest news they want to display.

    $relatedpostnums = get_post_meta($post->ID, 'relatedpostnums', true);
    $query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 5, 'post__in' => array( 31,7,53,35 ) ) ); while($query->have_posts()) : $query->the_post();

    I have 31,7,53,35 as the posts I want to display. that is manually entered. If I want it to be dynamic, how do I replace those 4 numbers with the output from $relatedpostnums?

    I did this:

    $relatedpostnums = get_post_meta($post->ID, 'relatedpostnums', true);
    $query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 5, 'post__in' => array( $relatedpostnums ) ) ); while($query->have_posts()) : $query->the_post();

    But it only displays the first number, even if I set it to posts_per_page to 4

Viewing 1 replies (of 1 total)
  • If your post numbers are separated by commas, you can ‘explode’ them into an array:

    $relatedpostnums = get_post_meta($post->ID, 'relatedpostnums', true);
    $post_nums = explode(',', $relatedpostnums);
    $query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 5, 'post__in' => $post_nums ) ); while($query->have_posts()) : $query->the_post();
Viewing 1 replies (of 1 total)
  • The topic ‘How to put custom field data dynamically into WP_query’ is closed to new replies.