在Wordpress中的函数内返回值以显示自定义字段

时间:2018-10-23 21:27:54

标签: php wordpress return shortcode custom-fields

我不确定我在做正确的事情。这是我的问题:

function getCustomField() {
    global $wp_query;
    $postid = $wp_query->post->ID;
    echo '<p>'.get_post_meta($postid, 'blog_header', true).'</p>';
    wp_reset_query();

}

使用此功能,当我像这样调用函数getCustomField时,可以用wordpress在模板中的几乎任何地方显示自定义字段:

<?php getCustomField(); ?>

但这并不是我想要实现的目标。理想情况下,我想从此函数返回一个值,以便基本上用一个短代码执行相同的操作,所以相同的事情但不是回显该值,而是要返回该值并在最后添加:

add_shortcode('custom', 'getCustomField');

因此我可以通过以下方式在主题中调用它:

,或者在循环内仅输入简码[custom]。

这当然不起作用,我的错误在哪里?

最后,在远程情况下,如果我最终返回我的值,它将可以正常工作,

global $wp_query;
$postid = $wp_query->post->ID;
wp_reset_query();
return '<p>'.get_post_meta($postid, 'blog_header', true).'</p>';

1 个答案:

答案 0 :(得分:1)

您想使用简码检索帖子ID,如下所示:

function getCustomField() {

    $post_id = get_the_ID();
    return '<p>'.get_post_meta( $post_id, 'blog_header', true ).'</p>';
}
add_shortcode( 'custom', 'getCustomField' );

从get_post_meta()函数中检查一个值也可能很聪明。否则,您将获得空的段落标签。您可以这样做:

function getCustomField() {

    $post_id = get_the_ID();
    $blog_header = get_post_meta( $post_id, 'blog_header', true );

    if( $blog_header ) {

        return '<p>'.$blog_header.'</p>';

    }else{

        return false;
    }
}
add_shortcode( 'custom', 'getCustomField' );