您至少有两种选择:
将所需变量全球化,然后在回调中引用该变量,用函数包装分数计算逻辑,然后在回调中引用该变量
<?php
global $score;
$score = 42; //Some crazy calculation I don\'t want to repeat.
function add_score_to_title($title) {
global $score;
return \'Quiz Results (\' . $score . \'/\') - \' . $title;
}
add_filter( \'aioseop_title_single\', \'add_score_to_title\');
?>
如果您只需要在过滤器内部进行分数计算,请将逻辑拉入回调本身:
<?php
function add_score_to_title($title) {
$score = 0;
$questions = get_quiz_result_questions();
$total_questions = 0;
foreach( $questions as $question ) {
$order = $question->order;
if( $order >= 100 ) {
break;
}
if( $question->correct == $_POST[\'Q\'][$order] ) {
$score++;
}
$total_questions++;
return \'Quiz Results (\' . $score . \'/\') - \' . $title;
}
add_filter( \'aioseop_title_single\', \'add_score_to_title\');
?>
更好的是,您可以将分数计算封装在自己的函数中,然后在回调函数中调用该函数:
<?php
function wpse48677_get_score() {
$score = 0;
$questions = get_quiz_result_questions();
$total_questions = 0;
foreach( $questions as $question ) {
$order = $question->order;
if( $order >= 100 ) {
break;
}
if( $question->correct == $_POST[\'Q\'][$order] ) {
$score++;
}
$total_questions++;
$output[\'score\'] = $score;
$output[\'total_questions\'] = $total_questions;
return $output;
}
function add_score_to_title($title) {
$score_results = wpse48677_get_score();
$score = $score_results[\'score\'];
return \'Quiz Results (\' . $score . \'/\') - \' . $title;
}
add_filter( \'aioseop_title_single\', \'add_score_to_title\');
?>
如果您发现在引用
$_POST
对象,您还可以注册查询变量,然后使用
get_query_var()
内部获取数据:
function add_score_query_vars( $query_vars ) {
$query_vars[] = \'Q\';
return $query_vars;
}
add_filter( \'query_vars\', \'add_score_query_vars\' );
有了这个,
$_POST[\'Q\']
可以替换为
get_query_var(\'Q\')
.