【问题标题】:Echo variable ID out of function in WordPressEcho 变量 ID 在 WordPress 中不起作用
【发布时间】:2020-03-13 13:41:12
【问题描述】:

我试图在footer_output() 函数之外回显$the_ID,但我不确定如何让它工作。这是我的代码:

add_action('wp_footer', 'footer_output', 10);
function footer_output() {

    global $post;

    $args = array(
        'post_type'         => 'shoes',
        'posts_per_page'    => -1,
        'meta_query'   => array(
            'relation' => '==',
            array(
                'key'     => 'women',
                'compare' => 'EXISTS',
                'value'   => '1'
            ),
        ),
    );
    $query = new WP_Query($args);
    while ($query->have_posts()) : $query->the_post();

        $the_ID = $post->ID;

        $size = get_post_meta($the_ID, 'size', true);
        $color = get_post_meta($the_ID, 'color', true);
        // Do more stuff here...

    endwhile;
    wp_reset_postdata();

}

add_action('wp_head', 'header_output', 10);
function header_output() {

    echo '<link rel="stylesheet" id="shoes-' . $the_ID . '"  href="" media="all" />';

}

但这当然行不通。有什么建议吗?

【问题讨论】:

    标签: wordpress function variables scope


    【解决方案1】:

    你快到了。您只需要从 footer_output() 到 return $the_ID; 并使用函数而不是 $the_ID var,如下所示:

    add_action('wp_footer', 'footer_output', 10);
    function footer_output() {
    
        global $post;
    
    $args = array(
        'post_type'         => 'shoes',
        'posts_per_page'    => -1,
        'meta_query'   => array(
            'relation' => '==',
            array(
                'key'     => 'women',
                'compare' => 'EXISTS',
                'value'   => '1'
            ),
        ),
    );
    $query = new WP_Query($args);
    while ($query->have_posts()) : $query->the_post();
    
        $the_ID = $post->ID;
    
        $size = get_post_meta($the_ID, 'size', true);
        $color = get_post_meta($the_ID, 'color', true);
        // Do more stuff here...
    
        endwhile;
        return $the_ID;
        wp_reset_postdata();
    
    }
    
    add_action('wp_head', 'header_output', 10);
    function header_output() {
    
        echo '<link rel="stylesheet" id="shoes-' . footer_output() . '"  href="" media="all" />';
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-09
      • 2015-11-29
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      相关资源
      最近更新 更多