How to Pass External Variables to Filters/Actions

You have at least two options:

  1. Globalize the desired variable, and then reference it inside the callback
  2. Wrap the score calculation logic with a function, then reference it inside the callback

Globalize the Variable

<?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 . "https://wordpress.stackexchange.com/") - ' . $title;
}

add_filter( 'aioseop_title_single', 'add_score_to_title');
?>

Wrap the Score Calculation

If you only ever need the score calculation inside the filter, pull the logic into the callback itself:

<?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 . "https://wordpress.stackexchange.com/") - ' . $title;
}

add_filter( 'aioseop_title_single', 'add_score_to_title');
?>

Better yet, you could wrap your score calculation in a function of its own, and then call that function inside your callback:

<?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 . "https://wordpress.stackexchange.com/") - ' . $title;
}

add_filter( 'aioseop_title_single', 'add_score_to_title');
?>

If you find you have problems referencing the $_POST object, you can also register your query variable and then use get_query_var() internally to get data:

function add_score_query_vars( $query_vars ) {
    $query_vars[] = 'Q';

    return $query_vars;
}
add_filter( 'query_vars', 'add_score_query_vars' );

With this in place, $_POST['Q'] can be replaced with get_query_var('Q').

Leave a Comment

tech