[wp-trac] [WordPress Trac] #40192: apply_filters() works only once, if doing multiple array merge
WordPress Trac
noreply at wordpress.org
Sat Mar 18 09:01:29 UTC 2017
#40192: apply_filters() works only once, if doing multiple array merge
--------------------------+-----------------------------
Reporter: esemlabel | Owner:
Type: defect (bug) | Status: new
Priority: normal | Milestone: Awaiting Review
Component: General | Version: trunk
Severity: normal | Keywords:
Focuses: |
--------------------------+-----------------------------
{{{#!php
<?php
$array = array( 'one', 'two' );
$array = array_merge( $array, (array) apply_filters( 'example_filter',
array() ) );
}}}
Such array_merge() need when we want only extend original array without
modifying it. If we hook in this filter multiple times, the last one
hooked functions will override all previously returned to filter values.
{{{#!php
<?php
add_filter( 'example_filter', 'three' );
function three() {
return 'three';
}
add_filter( 'example_filter', 'four_n_five' );
function four_n_five() {
return array( 'four', 'five' );
}
}}}
Result $array will be
{{{#!php
<?php
$array = array( 'one', 'two', 'four', 'five' );
}}}
------------------------------------------------------
The only way to return all values is to always use original $array in
apply_filters, and always perform array_merge() inside every hooked
function. Look like the logic is gone.
{{{#!php
<?php
$array = array( 'one', 'two' );
$array = apply_filters( 'example_filter', $array );
add_filter( 'example_filter', 'three' );
function three( $array ) {
return array_merge( $array, array( 'three' ) );
}
add_filter( 'example_filter', 'four_n_five' );
function four_n_five( $array ) {
return array_merge( $array, array( 'four', 'five' ) );
}
}}}
Result $array will be
{{{#!php
<?php
$array = array( 'one', 'two', 'three', 'four', 'five' );
}}}
--
Ticket URL: <https://core.trac.wordpress.org/ticket/40192>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list