WordPress.org

Ready to get started?Download WordPress

Forums

How to put custom field data dynamically into WP_query (2 posts)

  1. michaellawrence
    Member
    Posted 1 year ago #

    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

  2. vtxyzzy
    Member
    Posted 1 year ago #

    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();

Topic Closed

This topic has been closed to new replies.

About this Topic