我有一个函数,它返回一个我想通过另一个函数检查的值。据我所知,我无法在第一个函数中回显它,因为它在body_class的wordpress过滤器中使用,并在那里输出。
那么,如何检查在另一个函数中返回的值?
返回$class的第一个函数的示例,这是我想要检查的:
function layout_class( $class ) {
// There is lots of more functionality here for the $layout variable
$layout = 'col-3cm';
$class[] = $layout;
return $class;
}
add_filter( 'body_class', 'layout_class' );现在,这个类决定是否加载辅助侧栏模板。所以我想做:
function sidebar_dual() {
$layout = layout_class();
if (
( $layout == 'col-3cm' ) ||
( $layout == 'col-3cl' ) ||
( $layout == 'col-3cr' )
)
{ get_template_part('sidebar-2'); }
}因为我不能回显第一个函数,并且不想编写另一个函数,因为它很大--我如何处理它?是否有一种检查返回值的简单方法,类似于echo?
发布于 2013-12-07 13:21:52
看起来你需要重构你的代码。
只需将确定布局的代码移动到单独的函数中,就可以在过滤器内部和sidebar_dual()函数中调用该函数:
function get_layout_mode(){
// There is lots of more functionality here for the $layout variable
$layout = 'col-3cm';
return $layout;
}过滤器功能变成:
function layout_class( $class ) {
$class[] = get_layout_mode();
return $class;
}
add_filter( 'body_class', 'layout_class' );在sidebar_dual()函数中调用get_layout_mode()而不是layout_class()
也可以使用当前代码,将WP的get_body_class()函数返回的字符串拆分为数组,然后检查数组中是否存在这3个类中的任何一个。不过,我会选择第一种选择,因为它更清晰。
发布于 2013-12-07 13:16:26
如果$class在layout_class($class)中是空的,那么函数无论如何都是无效的。您需要为变量layout_class($class = null)声明一些东西,或者如果您称它为layout_class(null),但是如果不声明它,它就不会像设置它的方式那样工作。
剩下的代码没问题。
另外,您已经在函数中声明了$class,并且将它作为函数中的变量使用,我将重命名您的输出
function layout_class( $class ) {
// There is lots of more functionality here for the $layout variable
$layout = 'col-3cm';
return $layout;
}https://stackoverflow.com/questions/20441751
复制相似问题