• Resolved baga

    (@baga)


    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>
Viewing 6 replies - 1 through 6 (of 6 total)
  • vtxyzzy

    (@vtxyzzy)

    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>";
    }
    Thread Starter baga

    (@baga)

    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?

    vtxyzzy

    (@vtxyzzy)

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

    Thread Starter baga

    (@baga)

    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!

    vtxyzzy

    (@vtxyzzy)

    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.

    Thread Starter baga

    (@baga)

    Ok thanks again ??

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Display comma separated custom field values’ is closed to new replies.