这个remove_filter()
是避免递归调用回调所必需的,这将由于无休止的函数执行而导致内存问题。
这种递归可能会发生,因为回调连接到get_post_metadata
通过调用get_metadata()
回调调用的函数。
因此,您需要首先“unhook”/从挂钩中注销回调,然后才能调用get_metadata()
.
否则,您最终会遇到以下情况:
WP applies the filter (calls apply_filters( \'get_post_metadata\', ... ))
- your callback is called
- the callback calls get_metadata()
- WP applies the filter
- your callback is called
- the callback calls get_metadata()
- WP applies the filter
- your callback is called
- the callback calls get_metadata()
- WP applies the filter.....
或:
your_callback() {
your_callback() {
your_callback() {
your_callback() {
..... it never ends ...
因此,您的代码很好,因为它避免了不必要的递归。
但是,我注意到您没有正确卸下过滤器:
// You added the filter like so:
add_filter(\'get_post_metadata\', array(WPKWP::CLASS_NAME, \'get_post_metadata\'), -1, 4);
// Then in the callback, you\'re removing it like this:
remove_filter(\'get_post_metadata\', array(WPKWP::CLASS_NAME, \'get_post_metadata\'), 0);
// And later in that callback, the filter is added back:
add_filter(\'get_post_metadata\', array(WPKWP::CLASS_NAME, \'get_post_metadata\'), 0, 4);
问题是,删除筛选器/操作时,接受的参数的优先级和数量必须与添加筛选器时使用的相同值相匹配:
// If you added the filter like so:
add_filter(\'get_post_metadata\', array(WPKWP::CLASS_NAME, \'get_post_metadata\'), -1, 4);
// Then use the same parameters when removing the filter:
remove_filter(\'get_post_metadata\', array(WPKWP::CLASS_NAME, \'get_post_metadata\'), -1, 4);
// And not like this — priority should be -1 and this is missing the fourth parameter:
remove_filter(\'get_post_metadata\', array(WPKWP::CLASS_NAME, \'get_post_metadata\'), 0);
如果您最初是这样添加过滤器的,那么也应该以同样的方式将其添加回回调中;使用相同的参数:
// Like this:
add_filter(\'get_post_metadata\', array(WPKWP::CLASS_NAME, \'get_post_metadata\'), -1, 4);
// Not this: (priority doesn\'t match)
add_filter(\'get_post_metadata\', array(WPKWP::CLASS_NAME, \'get_post_metadata\'), 0, 4);