How to append to an array and return the results in a filter?

i am trying to get array in filters in wordpress i dont khnow how to do it.

add_filter('ft_tabs', function ($tabs) {
    return array_push($tabs, array(
        '111' => 'aaa',
        '222' => 'bbb'
    ));
}, 10);

add_filter('ft_tabs', function ($tabs) {
    return array_push($tabs, array(
        '333' => 'ccc',
        '444' => 'ddd'
    ));
}, 15);

$array = array();
$asdasd = apply_filters('ft_tabs', $array);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Note this is mostly a PHP programming question about arrays and is better asked on e.g. Stack Overflow.

As shown in the docs array_push() acts on the array and takes multiple parameters which get added as array values. It doesn’t add key => value pairs to associative arrays, and it doesn’t return the array itself, so you’re probably looking for array_merge or just the + operator, then returning the new value e.g.

add_filter('ft_tabs', function ($tabs) {
    $tabs = $tabs + arrary(
        '111' => 'aaa',
        '222' => 'bbb'
    );
    return $tabs;
}, 10);

Also it’s poor style to use reserved words like ‘array’ for variables names as you risk confusing the interpreter and getting a very unexpected result such as calling the array function when you meant to get the value of a variable.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x