TransWikia.com

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

WordPress Development Asked on October 30, 2021

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);

One Answer

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.

Answered by mozboz on October 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP