Forums

[resolved] Display comma separated custom field values (7 posts)

  1. baga
    Member
    Posted 1 year ago #

    I'm using this code to get custom field values from subpages:

    <?php
    $args = array(
    'post_type' => 'page',
    'post_status' => 'publish',
    'post_parent' => $post->ID
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
    <p><?php echo get_post_meta($post->ID, 'Email', true); ?></p>
    <?php endwhile;
    }
    wp_reset_query();
    ?>

    This way I got this output:

    <p>email 1</p>
    <p>email 2</p>
    <p>email 3</p>
    <p>email 4</p>

    I would like to know how to get a comma separated output like this one:

    <p>email 1,email 2,email 3,email 4</p>
  2. vtxyzzy
    Member
    Posted 1 year ago #

    This is untested, but should be close:

    if( $my_query->have_posts() ) {
       $sep = '';
       $list = '';
       while ($my_query->have_posts()) : $my_query->the_post();
          $item = get_post_meta($post->ID, 'Email', true);
          if ($item) {
             $list .= "$sep$item";
             $sep = ', ';
          }
       endwhile;
       echo "<p>$list</p>";
    }

    You could also use this:

    if( $my_query->have_posts() ) {
       $list = array();
       while ($my_query->have_posts()) : $my_query->the_post();
          $item = get_post_meta($post->ID, 'Email', true);
          if ($item) $list[] = "$item";
       endwhile;
       echo "<p>" . implode(',',$list) . "</p>";
    }
  3. baga
    Member
    Posted 1 year ago #

    Thanks a lot!
    It works perfectly :-)

    One more question: if I wanted to do the same stuff but getting custom field values from sub-subpages what should I change?

  4. vtxyzzy
    Member
    Posted 1 year ago #

    The code should work the same if you use the sub-page ID as the post_parent.

  5. baga
    Member
    Posted 1 year ago #

    I finally had time to try it and that's the code:

    $parent = $post->ID;
    $args = array(
        'post_type' => 'page',
        'post_status' => 'publish',
        'child_of' => $parent
    );
    $pages = get_pages($args);
    if ($pages) {
      foreach($pages as $post) {
        setup_postdata($post);
        if ($post->post_parent != $parent ) {
          $item = get_post_meta($post->ID, 'Email', true);
          if ($item) $list[] = "$item";
    }
    }
       echo "<p>" . implode(',',$list) . "</p>";
    }

    Thanks a lot for your help!

  6. vtxyzzy
    Member
    Posted 1 year ago #

    You are welcome!

    Please use the dropdown at right to mark this topic 'Resolved' so that
    others researching a similar topic can see that there is a solution.

  7. baga
    Member
    Posted 1 year ago #

    Ok thanks again :)

Topic Closed

This topic has been closed to new replies.

About this Topic