【问题标题】:How to override function in WordPress Parent theme from Child theme如何从子主题覆盖 WordPress 父主题中的功能
【发布时间】:2021-10-19 16:34:04
【问题描述】:

父主题有以下内容:


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 中尝试做的所有事情

我在这里查看了几个涵盖类似情况的线程,但我尝试过的解决方案都没有奏效。这包括:

  • 删除父主题功能/过滤器并替换它的变体,但似乎什么也没发生,所以我显然没有做对。
  • 只是再次添加函数voer,但父主题不使用函数(存在)
  • include_once get_theme_file_path('/inc/mega-menu.php');get_stylesheet_directory_uri 尝试从子主题而不是父主题包含/加载 php 文件,但总是遇到“无法重新声明 [function_name](之前在...中声明)
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 的中级,并认为我可以解决这个问题,但我现在只是想不通,因为我无法让这些解决方案中的任何一个起作用。

任何帮助表示赞赏!

【问题讨论】:

  • 你能把父级的东西留在原地,在父主题的过滤器之后添加你自己的 nav_menu_link_attributes 过滤器,然后覆盖它设置的任何内容吗?
  • @Aaron 我确实遇到了这个解决方案,并试了一下,但没有任何效果。我只是没有排骨。我可以这样做,但无法弄清楚如何正确编写它并使其工作,并且在如何覆盖现有过滤器方面有点过头了。谢谢你的建议,我很感激。
  • 这里没有足够的信息来帮助您。

标签: wordpress wordpress-theming


【解决方案1】:

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

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);

【讨论】:

  • 做到了!使用了 test_run_after。非常感谢!!
猜你喜欢
  • 2015-07-27
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-10
  • 2019-02-28
  • 2014-08-17
相关资源
最近更新 更多