Home > Back-end >  How to pass custom field value into array in wordpress loop argument?
How to pass custom field value into array in wordpress loop argument?

Time:02-06

There is a custom text field, where the user is prompt to enter page IDs to be displayed in the side bar. I am looking for a way to pass those numbers entered in the custom field into "post__in" argument as array.

Code so far:

<?php $pageid = get_post_meta(get_the_ID(),'key', true);

    $args = array(
    'post_type'      => 'page', 
    'post__in'    => array($pageid)
 );
 
 
$childrens = new WP_Query($args);
 
if ($childrens->have_posts()) : ?>
 <div >
    <?php while ($childrens->have_posts()) : $childrens->the_post();?>
 
        <div  id="staff-<?php the_ID(); ?>">
            <figure id="attachement_<?php the_ID();?>">
  <?php the_post_thumbnail(array(200,200,true),array('loading' => 'lazy', "alt"=> '', 'aria-hidden'=> 'true', 'tabindex' =>"-1"));?></figure>
 
            <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
 
        </div>
 
    <?php endwhile; ?>
</div>
<?php endif; wp_reset_query(); ?>

This only returns one page with first number (ID) entered. How can we pass these values so it returns pages by their IDs?

CodePudding user response:

Your $pageid from the post_meta is returning a string and array($pageid) is only creating an array with a single element. You need to convert the string to an array using explode(...). I recommend instructing users to separate the ids by comma, such as 1,2,3,4,5. Then using the following should work:

'post__in' => explode(',', $pageid)

I also recommend a couple more tweaks:

  • Change the key of your meta key to something more relevant, I usually add 2/3 characters at the start of any custom meta related to a project I'm working on, such as ss_.
  • Make $pageid plural to $pageIds.
  • Combine the explode with trim to ensure the user enters no spaces.

Note that chaning the meta key name to ss_child_page_ids would require you to also update the rest of your code where this field is being stored, and and will also unlink any existing values as you are no longer referencing key.

<?php
$pageIds = get_post_meta(get_the_ID(),'ss_child_page_ids', true);
$pageIds = array_map('trim', explode(',', $pageIds ));

$args = array(
    'post_type' => 'page', 
    'post__in'  => $pageIds
);

And $childrens can also be changed to $children, it is already in plural form.

Now $pageIds should be an array with each id item, such as '1,2,3,4,5' will be ['1','2','3','4','5'].

  • Related