2017-09-17 65 views
0

下面是這種情況:如何將參數傳遞給apply_filters?

if(apply_filters('example_filter', false, $type)) { 
     // do something 
} 

我要讓$type提供// do something塊內或從callback_function通過。

$type = 'select'; 
function callback_function($bool, $type) { 
    return true; 
} 
add_filter('example_filter', 'callback_function', 10, 2); 

如何傳遞從內部apply_filters範圍callback_function的arguement?

回答

0

不幸的是,你不能在WordPress中引用apply_filters函數中的其他變量(不管是否參考),但是,有幾個解決方法。如果您的代碼旨在處理它,則可以將第二個參數(從apply_filters調用返回的過濾器名稱後面的那個參數)更改爲非布爾值或全局變量(不推薦):

$type = 'select'; 
if(false !== ($type = apply_filters('example_filter', false, $type)) ) { 
    // Returned $type available here (if it is not boolean false) 
} 

定義:

function callback_function($type) { 

    if(/* is valid conditional */) { 
     return $type; // Default value 
    } else if (/* another valid condition */) { 
     return 'radio'; 
    } 

    // else not valid 
    return false; 
} 
add_filter('example_filter', 'callback_function', 10); 


另一種方法是使用全局變量(不推薦):

$GLOBALS['type'] = 'select'; 
if(apply_filters('example_filter', false)) { 
    // $GLOBALS['type'] available here 
} 

定義:

function callback_function($bool) { 
    global $type; 
    $type = 'radio'; 
    return true; 
} 
add_filter('example_filter', 'callback_function', 10); 

參考:https://www.geeklab.info/2010/04/wordpress-pass-variables-by-reference-with-apply_filter/