admin管理员组

文章数量:1405186

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?

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?

Share Improve this question edited Dec 24, 2019 at 12:18 user3013494 asked Dec 24, 2019 at 6:48 user3013494user3013494 451 silver badge7 bronze badges 5
  • Are you sure you’re adding your filter before applying it? – Krzysiek Dróżdż Commented Dec 24, 2019 at 8:38
  • you write about function.php but the file in the theme is functions.php with a "s". – Kaperto Commented Dec 24, 2019 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 Commented Dec 24, 2019 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 Commented Dec 24, 2019 at 13:23
  • wordpress.stackexchange/questions/265952/… – cjbj Commented Dec 24, 2019 at 13:41
Add a comment  | 

1 Answer 1

Reset to default 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 );

本文标签: filtersCan39t understand applyfilter logic