练习add_filter
和apply_filters
首先要知道的是apply_filters
返回它的第二个参数,试试这个functions.php
:
echo apply_filters('cat_story', 'A cat'); // echoes "A cat"
第二件要知道的是,在apply_filters
返回“A cat”之前,它会应用可以修改“A cat”的过滤器,添加过滤器add_filter
:
function add_chasing_mice($cat) {
return $cat . ' is chasing a mice';
}
add_filter('cat_story', 'add_chasing_mice');
echo apply_filters('cat_story', 'A cat'); // echoes "A cat is chasing a mice"
第三件事是我们可以添加多个过滤器:
// #1
function add_chasing_mice($cat) {
return $cat . ' is chasing a mice';
}
add_filter('cat_story', 'add_chasing_mice');
// #2
function add_something_else($cat) {
return $cat . ', but it\'s not gonna catch it';
}
add_filter('cat_story', 'add_something_else');
echo apply_filters('cat_story', 'A cat'); // echoes "A cat is chasing a mice but it\'s not gonna catch it"
要知道的第四件事是您可以按特定顺序应用过滤器:
// #1
function add_chasing_mice($cat) {
return $cat . ' is chasing a mice';
}
add_filter('cat_story', 'add_chasing_mice', 10); // 10 - is priority
// #2
function add_something_else($cat) {
return $cat . ', but it\'s not gonna catch it';
}
add_filter('cat_story', 'add_something_else'); // 10 as well, if omitted
// The filter will be applied before `add_chasing_mice` and `add_something_else`
function replace_the_cat($cat) {
return 'A dog';
}
add_filter('cat_story', 'replace_the_cat', 9); // 9 < 10, so the filter will be applied first
echo apply_filters('cat_story', 'A cat'); // echoes "A dog is chasing a mice but it's not gonna catch it";
要知道的第五件事是您可以将其他参数传递给过滤器:
function add_chasing_mice($cat) {
return $cat . ' is chasing mice';
}
add_filter('cat_story', 'add_chasing_mice', 10); // 10 - is priority
function add_something_else($cat, $exclam, $wft) {
return $cat . ', but it\'s not gonna catch it' . $exclam . $wft;
}
add_filter('cat_story', 'add_something_else', 10, 3); // 3 arguments
function replace_the_cat($cat) {
return 'A dog';
}
add_filter('cat_story', 'replace_the_cat', 9); // 9 < 10, so the filter will be applied first
echo apply_filters('cat_story', 'A cat', '!!!', '!1wTf!?');
// 3 arguments are: 'A cat', '!!!', '!1wTf!?'.
// echoes "A dog is chasing a mice but it's not gonna catch it!!!!1wTf!?";