将自定义字段从一个帖子嵌入到另一个帖子

问题描述:

我有一个自定义字段(文本区域)的WordPress帖子。将自定义字段从一个帖子嵌入到另一个帖子

有没有办法从该自定义字段中获取数据,以通过嵌入代码或一些简码在同一博客上的另一篇新文章中显示?

例如: 邮政A有一个自定义字段,其中包含3张图片的画廊。我希望这个图片库可嵌入到另一个新帖子B中。

这是一个简单的实现。

添加到functions.php中:

// add hook for new shortcode 
add_shortcode('custom_field', 'shortcode_field'); 

function shortcode_field($atts) { 
    // get attributes that were passed in the shortcode 
    extract(shortcode_atts(array(
     'post_id' => null, 
    ), $atts)); 

    // if we don't at least have a field name, then exit 
    if (! isset($atts[0])) { 
     return; 
    } 

    // field is the first attribute 
    $field = esc_attr($atts[0]); 

    // get the current post 
    global $post; 

    // if no post id was passed as a parameter to the shortcode, use the current post 
    $post_id = (null === $post_id) ? $post->ID : $post_id; 

    // do the custom field lookup for the appropriate post and retur the text 
    return get_post_meta($post_id, $field, true); 
} 

你会使用简码在WordPress编辑器中的任何一种通过以下两种方式:

[custom_field "field_name"] - looks up field_name for the current post 
[custom_field "field_name" post_id=999] - looks up field_name for post with id 999 

你可以看中,并使用相同的概念用一些gui shortcode生成器插件,如Shortcodes Pro,这会在wordpress编辑器中给你一个不错的简码按钮。

+0

辉煌的先生!谢谢你! – user3886632 2014-09-11 07:21:42