WordPress.org

Ready to get started?Download WordPress

Forums

wrap text around custom fields array (3 posts)

  1. markoburns
    Member
    Posted 3 years ago #

    I'm using this code here to grab all my custom fields from a post for use in an gallery array.

    function:

    //  Get all custom fields attached to a page
    if ( !function_exists('base_get_all_custom_fields') ) {
    function base_get_all_custom_fields()
    {
        global $post;
        $custom_fields = get_post_custom($post->ID);
        $hidden_field = '_';
        foreach( $custom_fields as $key => $value ){
            if( !empty($value) ) {
                $pos = strpos($key, $hidden_field);
                if( $pos !== false && $pos == 0 ) {
                    unset($custom_fields[$key]);
                }
            }
        }
        return $custom_fields;
    }
    }

    single.php:

    // Get all custom fields attached to this post and store them in an array
    $custom_fields = base_get_all_custom_fields();
    if( !empty($custom_fields) ) {
    print_r($custom_fields);
    }

    It works, but outputs text like this around the custom post: Array ( [photo1] => Array ( [0] =>

    Is there a way to customise what you wrap before & after a custom field output, and remove the array text? I 'm not a php expert.

    What I'm trying to achieve is

    {image : 'http://website.com/slides/photo1.jpg'},
    {image : 'http://website.com/slides/photo2.jpg'},
    {image : 'http://website.com/slides/photo3.jpg'},

    so I need to wrap {image : ' before and '}, after the link.

    I can sort of do it with single queries but the array system would be better

    {image : '<?php echo $custom_fields['photo1'][0]; ?>'},
    {image : '<?php echo $custom_fields['photo2'][0]; ?>'},
    {image : '<?php echo $custom_fields['photo3'][0]; ?>'},
  2. vtxyzzy
    Member
    Posted 3 years ago #

    The print_r() function just dumps out the contents of a variable. To format as you showed in your sample, you will need to have a foreach loop to process each link:

    // Get all custom fields attached to this post and store them in an array
    $custom_fields = base_get_all_custom_fields();
    if( !empty($custom_fields) ) {
       $sep = '';
       foreach ($custom_fields as $key => $value) {
          echo "$sep{image : '$value'};
          $sep = ",\n";
       }
    }
  3. markoburns
    Member
    Posted 3 years ago #

    ok, thanks.

Topic Closed

This topic has been closed to new replies.

About this Topic