首页 > 解决方案 > Echo 变量 ID 在 WordPress 中不起作用

问题描述

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

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" />';

}

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

标签: wordpressfunctionvariablesscope

解决方案


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

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" />';

}

推荐阅读