php - jQuery 到 PHP : Add a selector class to children elements if more than one

标签 php jquery wordpress templates woocommerce

是否可以在 PHP 中实现与下面的 jQuery 代码相同的东西?
我用它来隐藏从批发商进口产品时出现的错误。
这是我使用的jQuery代码:

jQuery(document).ready(function( $ ){
    $('.woocommerce-product-details__short-description:has(p:nth-of-type(2)) p').addClass('ukryj-klase-krotki');
});
它是如何工作的:
jQuery 检查产品简短描述中是否有多个 <p>元素。如果还有更多 - 它将类“ukryj-klase-krotki”添加到所有 <p>元素。然后我先添加 CSS 类来隐藏 <p>产品简短描述中生成的元素,所以我想要的唯一一个是可见的:
CSS代码:
.woocommerce-product-details__short-description .ukryj-klase-krotki{
    display: none;
}

.woocommerce-product-details__short-description .ukryj-klase-krotki ~ .ukryj-klase-krotki{
    display: block;
}
有什么帮助吗?

最佳答案

初读Template structure & Overriding templates via a theme了解如何通过事件子主题覆盖 WooCommerce 模板文件。
要覆盖的模板是 single-product/short-description.php
一旦复制到“woocommerce”文件夹>“单一产品”子文件夹中的chid主题,打开/编辑short-description.php文件,并替换为:

<?php
/**
 * Single product short description
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/single-product/short-description.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce\Templates
 * @version 3.3.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

global $post;

$short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt );

if ( ! $short_description ) {
    return;
} 

if ( $short_description && substr_count($short_description, '</p>') > 1 ) {
    $short_description = str_replace( ['<p class="', '<p>'], ['<p class="ukryj-klase-krotki ', '<p class="ukryj-klase-krotki">'], $short_description );
}

?>
<div class="woocommerce-product-details__short-description<?php echo $class; ?>">
    <?php echo $short_description; // WPCS: XSS ok. ?>
</div>

在这里,使用 substr_count() php函数,我们统计</p>的数量(结束标签)从产品简短描述中,添加 ukryj-klase-krotki作为所有 <p> 的类选择器 child 标签使用 str_replace() 功能。测试和工作。

关于php - jQuery 到 PHP : Add a selector class to children elements if more than one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66195123/

相关文章:

php - 建立实时数据库(方法)

php - 我是使用 fopen 还是 curl 加载给定 PHP 中的 URL 的 XML 文件

javascript - 每 20 秒显示 5 秒后如何关闭该元素

javascript - 使用 react-create-wptheme 创建应用程序后路由的 React-router-dom 问题

php - php mysql_fetch_array 是否适用于 html 输入框?

php - 背景更换器刷新

javascript - 为 Angular JS 折叠 Bootstrap DIV 设置默认打开状态?

jquery - Maple 浏览器中的 css3 属性

javascript 下拉停止在 Wordpress Woocommerce https 页面上工作

wordpress - 同一站点上的 Drupal 和 wordpress