如何从子主题覆盖 WordPress 父主题中的功能

How to override function in WordPress Parent theme from Child theme

父主题有以下内容:


public function mega_menu_attributes( $atts, $item, $args, $depth ) {

        // Get Mega Menu Type.
        $menu_type = $this->is_mega_menu( $item, $args );

        // Mega Menu attrs for terms.
        if ( in_array( $menu_type, array( 'term', 'child-term' ), true ) ) {
            $atts['data-term'] = $item->object_id;

            if ( 'term' === $menu_type ) {
                $atts['data-numberposts'] = 5;
            } elseif ( 'child-term' === $menu_type ) {
                $atts['data-numberposts'] = 6;
            }
        }

        // Mega Menu attrs for posts.
        if ( isset( $item->mega_menu_children ) && 'mixed' === $menu_type ) {
            $layout = $this->identify_mega_menu_layout( $item->mega_menu_children );

            if ( 'posts' === $layout ) {

                $posts = array();

                foreach ( $item->mega_menu_children as $_post ) {
                    $posts[] = $_post->object_id;
                }

                $atts['data-posts'] = implode( '|', $posts );

                $atts['data-numberposts'] = 5;
            }
        }

        return $atts;
    }

我想用 $atts['data-numberposts'] = 12;

覆盖 $atts['data-numberposts'] = 6;

这就是我在 Child 主题中想要做的一切 functions.php

我在这里检查了几个涵盖类似案例的线程,但是我从中尝试过的解决方案中 none 已经奏效。这包括:

function remove_parent_theme_mega_menu_atts()
{
    remove_filter( 'nav_menu_link_attributes', array( $this, 'mega_menu_attributes' ), 10, 4 );
}

add_action('init', 'remove_parent_theme_mega_menu_atts');

我是 PHP/WordPress 的中级水平,我认为我可以弄清楚这个问题,但我现在无法理解这些解决方案中的任何一个。

感谢任何帮助!

看来这应该行得通。会发生什么?

function test_run_before($atts, $item, $args) {
  $atts['data-numberposts'] = 12;
  return $atts;
}
function test_run_after($atts, $item, $args) {
  $atts['data-numberposts'] = 12;
  return $atts;
}

add_filter('nav_menu_link_attributes', 'test_run_before', 9, 3);
add_filter('nav_menu_link_attributes', 'test_run_after', 11, 3);