0

Never creates self filters before. In my plugin I have variable as array. I want another users can change this array without plugin modification. I'm trying this code in my plugin.php:

<?php
/*
Plugin Name: Test plugin
*/

$arr = [
    'val',
    'val2',
    'val3'
];

$arr = apply_filters( 'my_hook', $arr );
print_r( $arr );

In my functions.php I puts this code:

add_filter( 'my_hook', 'modify', 10, 1 );

function modify( $arr ) {
    unset($arr[0]);
    return $arr;
}

I expecting output without first element, but it outputs original array with 3 values;

What's wrong with it?

  • Are you sure you’re adding your filter before applying it? – Krzysiek Dróżdż Dec 24 '19 at 8:38
  • you write about function.php but the file in the theme is functions.php with a "s". – Kaperto Dec 24 '19 at 8:50
  • Are these definitely loaded in the right order? It might be worth moving your plugin.php code into an init hook so you can be sure that your my_hook implementation has loaded when you try to call it. – Rup Dec 24 '19 at 9:50
  • thanks for your answers. I posted and edition below. Is it right? I don't like globals, in this case it's the only way to solve my problem? – user3013494 Dec 24 '19 at 13:23
0

Thanks for your answers. According to comments above, I modified my code. Now it works. Is it correct way?

<?php
/*
Plugin Name: Test plugin
*/

$arr = [];

add_action( 'init', 'set_var_data' );

function set_var_data() {
    global $arr;

    $arr = [
        'val',
        'val2',
        'val3'
    ];

    $arr = apply_filters( 'my_hook', $arr );
}

print_r( $arr );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.