【发布时间】:2019-05-26 21:25:16
【问题描述】:
我想通过用 PHP 修改 DOM 使产品和购物车页面上所有 qty 类的 input 标签具有 type="number" 和 readonly="readonly" 属性。
当我将其限制为购物车和产品页面时,它“仅”使延迟加载插件和 Autoptimize 插件对这两个页面停止工作,而其他页面则很好。我在管理页面上也没有发现任何控制台错误。
当我允许它为每个页面运行时,会发生以下情况:
- 产品和购物车页面上的控制台没有错误。
- Ajax 请求 Ajax 添加到购物车插件中断。
- 我收到多个控制台错误,这些错误会破坏许多管理页面的布局、移动和隐藏部分内容。
这些输出缓冲区修改感觉就像是黑客入侵导致错误/不兼容。可能是因为libxml_use_internal_errors(true); 隐藏了警告,实际上并没有解决任何问题?
Dom loadHTML doesn't work properly on a server
这就是我的functions.php中的内容:
add_action( 'template_redirect', 'acau_activate_buffer', 99999 );
function acau_activate_buffer() {
// cart and product page only, WooCommerce required for below line to work, remove to reproduce issues without WooCommerce
if ( ! is_cart() && ! is_product() ) return;
ob_start();
}
add_action('shutdown', function() {
// cart and product page only, WooCommerce required for below line to work, remove to reproduce issues without WooCommerce
if ( ! is_cart() && ! is_product() ) return;
$final = '';
// Collect output from all previous buffers.
$levels = ob_get_level();
for ($i = 0; $i < $levels; $i++) {
$final .= ob_get_clean();
}
echo apply_filters('acau_output', $final);
}, -99999);
// Filter final output.
add_filter('acau_output', function($output) {
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML(mb_convert_encoding($output, 'HTML-ENTITIES', 'UTF-8'));
foreach ($dom->getElementsByTagName('input') as $node) {
$classes = explode (' ', $node->getAttribute('class') );
if ( in_array ( 'qty', $classes ) ) {
$node->setAttribute('type', 'number');
$node->setAttribute('readonly', 'readonly');
}
}
$newHtml = $dom->saveHtml();
return $newHtml;
});
【问题讨论】:
-
你为什么不用javascript?
-
我更进一步,将代码限制在两个操作中的产品和购物车页面而不是一个操作中,并编辑了我的原始问题。如果我使用 JavaScript,在页面加载输入字段 type="hidden" 将从隐藏变为可见,导致闪烁,除非我在 CSS 之上加载脚本,否则如果网站使用某些插件/代码,谷歌不鼓励并且无法实现sn-ps 影响脚本定位。使用 PHP,只要页面可见,元素就会出现。