質問

I want to change heading tags from child theme but i can't figure out how to add filter to parent theme function.

Parent theme function that i want to change:

if(! class_exists('WpkPageHelper')) {
class WpkPageHelper
{
    public static function zn_get_subheader( $args = array(), $is_pb_element = false )
    {
        $config = zn_get_pb_template_config();
        self::render_sub_header( $args );
    }

    public static function render_sub_header( $args = array() )
    {
        $defaults = array(
            'title_tag' => 'h2'
        );
    }   
}
}

I want the default title_tag value to be 'span'.

役に立ちましたか?

解決

There is no filter. To filter a value the developer needs to create a filter by wrapping the filterable value in a call to apply_filters() with a name for that filter. They have not done that.

What they have done is make the WpkPageHelper class pluggable. This means that it's possible for a child theme to replace the entire class.

Before defining the WpkPageHelper class, the parent theme is checking if(! class_exists('WpkPageHelper')) {. This is checking if the class has been defined already and only defining the class if it hasn't been. Because child themes are loaded before parent themes this gives you an opportunity to define WpkPageHelper before the parent theme does. The parent theme will then use your version.

So all you need to do is copy the code for the WpkPageHelper class into your child theme's functions.php file (or another file included in your child theme's functions file) and make the change you want. Just leave out the class_exists() check:

class WpkPageHelper
{
    public static function zn_get_subheader( $args = array(), $is_pb_element = false )
    {
        $config = zn_get_pb_template_config();
        self::render_sub_header( $args );
    }

    public static function render_sub_header( $args = array() )
    {
        $defaults = array(
            'title_tag' => 'span'
        );
    }   
}

This is what WordPress and some themes and plugins are doing when they wrap class and function definitions in conditional statements. You'll occasionally see conditions like if ( ! function_exists( 'function_name' ) ) {. This is WordPress or the theme/plugin giving developers an opportunity to define their own versions of these functions or classes for WordPress or the theme/plugin to use instead of their own.

他のヒント

I do not see you actually calling child_remove_parent_function() in your code.

Another issue to be aware of is timing. It is counter–intuitive, but functions.php files are loaded in order of child first, parent second.

Overall you need to ensure two things:

  1. code works at all

  2. it is called at the appropriate moment, after parent theme is done with its set up

ライセンス: CC-BY-SA帰属
所属していません wordpress.stackexchange
scroll top