admin管理员组

文章数量:1125596

I have defined a apply_filters hook inside plugins_loaded hook in my custom plugin.

$post_singular_name = apply_filters( 'post_singular_name', 'Event' );
new Prefix\Post_Types($post_slug, $post_singular_name, $post_plural_name );

Now want to override the value of post_singular_name hook from themes functions.php. which is like following,

function singular_name_change( $v ) {
    return 'Portfolio';
}
add_filter('post_singular_name', 'singular_name_change');

But it is not affecting the hook. Expected value is Portfolio but still it is showing Event

Can you help someone how can i solve this issue?

Thanks in advance.

I have defined a apply_filters hook inside plugins_loaded hook in my custom plugin.

$post_singular_name = apply_filters( 'post_singular_name', 'Event' );
new Prefix\Post_Types($post_slug, $post_singular_name, $post_plural_name );

Now want to override the value of post_singular_name hook from themes functions.php. which is like following,

function singular_name_change( $v ) {
    return 'Portfolio';
}
add_filter('post_singular_name', 'singular_name_change');

But it is not affecting the hook. Expected value is Portfolio but still it is showing Event

Can you help someone how can i solve this issue?

Thanks in advance.

Share Improve this question edited Feb 29, 2024 at 4:22 Joe asked Feb 29, 2024 at 4:21 JoeJoe 112 bronze badges 1
  • Just to debug, try to apply_filter on init hook instead of plugins_loaded. – Syed Muhammad Usman Commented Feb 29, 2024 at 4:27
Add a comment  | 

2 Answers 2

Reset to default 1

plugins_loaded runs before the theme is loaded, so it will never be able to filter something that happens on this hook from a theme.

If you want something to do with post type registration to be filterable you should perform the registration on the init hook. This is the usual hook for post type registration and it will allow themes to use the filter.

Due to issue coming when the filters are applied. If the filter post_singular_name is being applied before the themes functions.php file is loaded or before the singular_name_change function is defined, then your filter in the theme won't have any effect.

Hok into after_setup_theme, you ensure that your filter is applied early enough in the theme loading process to affect the value of post_singular_name before it is used in your plugin.

add_action('after_setup_theme', 'my_theme_setup');

function my_theme_setup() {
    // Define the filter within the theme's setup function
    add_filter('post_singular_name', 'Event');
}

function singular_name_change( $v ) {
    return 'Portfolio';
}

本文标签: filtersHow to override hook from themes functionsphp which is defined in plugin