下面的代码将允许您在所有小部件中,在其$实例数组中存在的所有字符串上进行替换。
// Hook into \'widget_display_callback\' filter
// It allows altering a Widget properties right before it outputs in sidebar
add_filter(\'widget_display_callback\', function($instance, $widget, $args){
// Recursive functions that applies replacements in all string elements of $instance
$fnFixArray = function($v) use (&$fnFixArray){
// Dig deeper if this is an array or object
if(is_array($v) or is_object($v)){
// Use pointer here for property to satisfy both array/object in one
// Otherwise for arrays we need $v[$k1] and $v->{$k1} for objects
foreach($v as $k1=>&$v1){
// Go recursive on elements / properties
$v1 = $fnFixArray(v1);
}
return $v;
}
// Don\'t alter non-strings or empty ones
if(!is_string($v) or empty($v)) return $v;
// We found a string, replace stuff in it and return the altered value
return str_replace(\'%REPLACEWHAT%\', \'%REPLACEWITH%\', $v);
};
return $fnFixArray($instance);
}, 11, 3); // We need 3 arguments and a below normal priority
It\'s a bit more advanced but it\'s WHAT you really need.
同样的事情
array_walk_recursive() 它还递归对象:
// Hook into the \'widget_display_callback\' filter
// It allows altering a Widget properties right before output in sidebar
add_filter(\'widget_display_callback\', function($instance, $widget, $args){
// This digs through arrays and objects all the way to non-iterative level
array_walk_recursive($instance, function(&$value, $key){
// Don\'t alter non-strings or empty ones
if(!is_string($value) or empty($value)) return;
// We found a string, replace stuff in it and return the altered value
$value = str_replace(\'%REPLACEWHAT%\', \'%REPLACEWITH%\', $value);
});
// Return the possible altered $instance array
return $instance;
}, 11, 3);
祝你玩得开心