wordpress - 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" />';
}
但这当然行不通。有什么建议么?
解决方案
你快到了。您只需要return $the_ID;
fromfooter_output()
并使用该函数而不是$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" />';
}
推荐阅读
- python-3.x - sqlite插入函数重复id错误
- dataset - 当我遇到类别问题时,我应该如何处理为建模准备数据?
- redis - 保存用户redis
- ngxs - 使用 NGXS 初始化组件状态的 Angular 测试库
- windows - Powershell 参数问题:'无法将值“”转换为类型“System.Boolean”'
- java - 如何将子域转换为路径 Spring boot
- python - 尝试使用 Python 导入 Googleads 时收到错误消息
- android - 为什么进入横向模式时应用程序崩溃?kotlin.UninitializedPropertyAccessException:lateinit 属性尚未初始化
- javascript - HTML5 进度条的样式
- gitlab - gitlab-ci.yml 中 curl 脚本 json 数据中的语法使用变量