将文本环绕自定义字段数组

时间:2011-06-18 作者:david arthur

我在这里使用这段代码从帖子中获取所有自定义字段,以便在库数组中使用。

http://www.kevinleary.net/get-all-custom-fields-attached-post-page-post-type/

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);
}
它可以工作,但在自定义帖子周围输出如下文本Array ( [photo1] => Array ( [0] =>

有没有办法定制您之前包装的内容&;在自定义字段输出后,是否删除数组文本?

我想要实现的是

{image : \'http://website.com/slides/photo1.jpg\'}, 
{image : \'http://website.com/slides/photo2.jpg\'},  
{image : \'http://website.com/slides/photo3.jpg\'}, 
所以我需要打包{image : \' 之前和\'}, 链接之后。

我可以用单个查询进行排序,但数组系统会更好

{image : \'<?php echo $custom_fields[\'photo1\'][0]; ?>\'},
{image : \'<?php echo $custom_fields[\'photo2\'][0]; ?>\'},
{image : \'<?php echo $custom_fields[\'photo3\'][0]; ?>\'},

2 个回复
SO网友:Milo
if( !empty($custom_fields) ) {
    $output = \'\';
    foreach( $custom_fields as $key => $value ){
        foreach( $value as $val ){
            $output .= "{".$key." : \'".$val."\'},";
        }
    }
    echo $output;
}
SO网友:kaiser

我不太确定你在问什么,但据我所知,你是在每个自定义字段值之前/之后获取一些“东西”?

EDIT: 必须放置在您的函数中。php文件

function wpse20348_custom_field_output( $echo = false )
{
    $custom_fields = base_get_all_custom_fields();

    if ( empty( $custom_fields ) ) 
        return;

    $output = \'\';

    $prefix = \'{image : \';
    $suffix = \'}\';

    foreach ( $custom_fields as $key => $field )
    {
        $output .= $prefix.$field.$suffix;
    }

    if ( $echo === false )
        return $output;

    return print $output;
}
// Call it like this in your theme:
wpse20348_custom_field_output( true );

// or save it for further processing:
$wpse_custom_fields = wpse20348_custom_field_output();
也许你需要改变$prefix 满足您的需求。可能还需要附加[0]$field 内部foreach

结束

相关推荐