将属性添加到所有Wordpress页面的标签
问题描述:
如何使用PHP为我所有的WordPress网站页面的H1标签添加属性?将属性添加到所有Wordpress页面的标签
期望的结果:
<h1 itemprop="name">Title of Article</h1>
答
下面是代码
$html = new DOMDocument();
$html->loadHtml('filename');
$nodes = $html->getElementsByTagName('h1');
foreach ($nodes as $node) {
$node->setAttribute('itemprop','name');
}
$txt = $html->saveHTML();
让我知道,如果它的工作原理!
编辑:
<?php
$html = '<h1>Title of Article</h1>';
$dom = new DOMDocument();
$dom->loadHtml($html);
$nodes = $dom->getElementsByTagName('h1');
foreach ($nodes as $node) {
$node->setAttribute('itemprop','name');
}
$html = $dom->saveHTML();
echo $html;
使用此代码,你可以看到的结果。只需将上面的代码粘贴到空白的php文件中并在浏览器中运行即可看到结果
你可以用JS做到,如果它符合你的要求我可以建议你用JS的方式。 –
我用jQuery很容易做到这一点。但它没有出现在谷歌结构化数据测试工具上。所以我真的没有看到使用JS的重点。 – Kannan