未定义的属性:DOMDocument::$tagName

Lan*_*kea 5 php wordpress

我在 WP 的 debug.log 文件中收到以下错误。

PHP 注意:未定义属性:DOMDocument::$tagName 在 .../wp-content/themes/theme-name/libs/oi/functions.php 第 441 行

PHP 注意:尝试在第 441 行的 .../wp-content/themes/theme-name/libs/oi/functions.php 中获取非对象的属性

function oi_display_hierarchy( $nav_menu, $args )
{
    if( ! is_single() )
    {
        return $nav_menu;
    }

    $menuXML = new SimpleXMLElement( $nav_menu );
    list($current) = $menuXML->xpath( "//li[contains(@class,'current-menu-parent')]" );
    if( !empty( $current ) )
    {
        $node = dom_import_simplexml($current);
        while($node)
        {
            $node = $node->parentNode;
            if( $node->tagName == 'li' ) // 441 - The problem line
            {
                $classes = $node->getAttribute('class');
                $node->setAttribute('class', $classes . ' current-menu-ancestor current-menu-parent current_page_parent current_page_ancestor');
            }
        }
    }

    return str_replace('<?xml version="1.0"?>', '', $menuXML->asXML());
}
add_filter('wp_nav_menu', 'oi_display_hierarchy', 11, 2);
Run Code Online (Sandbox Code Playgroud)

有什么想法这里可能有什么问题吗?

var*_*ard 0

您正在尝试获取DOMElement上面一行中的当前对象父节点:

$node = $node->parentNode;
Run Code Online (Sandbox Code Playgroud)

所以之后$node会改为a DOMNode( DOMElementinherit of DOMNode)。tagNameproperty 不是 定义的一部分DOMNode,它特定于DOMElement- 这就是它抛出错误的原因。

xml 中的所有内容都是节点 - 文本、行、注释...因此 aDOMNode 可以是标签,但也可以是其他内容。因此,我们需要使用以下命令检查节点的类型:

if($node->nodeType == XML_ELEMENT_NODE) { // Node is a DOMElement
Run Code Online (Sandbox Code Playgroud)

这样我们就可以确定 $node 是一个DOMElement, 然后可以安全地使用tagName属性。