【问题标题】:Return value within function in Wordpress to display a custom field在 Wordpress 中的函数内返回值以显示自定义字段
【发布时间】:2018-10-23 21:27:54
【问题描述】:

我不确定我做的是否正确。这是我的问题:

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');

所以我可以这样在我的主题中调用它:

或在循环中仅使用短代码 [自定义]。

当然不行,我的错在哪里?

最后一件事,在远程情况下,如果我在最后返回我的值,它将起作用,如下所示:

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

【问题讨论】:

    标签: php wordpress return shortcode custom-fields


    【解决方案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' );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      相关资源
      最近更新 更多