Is it possible to implement the same thing than the jQuery code below in PHP?
I use it to hide errors made during importing products from wholesaler.
Here is the jQuery code I use:
jQuery(document).ready(function( $ ){
$('.woocommerce-product-details__short-description:has(p:nth-of-type(2)) p').addClass('ukryj-klase-krotki');
});
How does it work:
jQuery checks if in product short description is more than one <p>
element. If there is more - it adds class 'ukryj-klase-krotki' to all <p>
elements. Then I add CSS class to hide first <p>
element generated in product short description so the only one I want is visible:
CSS code:
.woocommerce-product-details__short-description .ukryj-klase-krotki{
display: none;
}
.woocommerce-product-details__short-description .ukryj-klase-krotki ~ .ukryj-klase-krotki{
display: block;
}
Any help?
My Answer:
paragraph element (p:nth-of-type(2)). If it finds more than one paragraph element, it adds a class 'ukryj-klase-krotki' to the paragraph elements.
In PHP, you can achieve a similar functionality by using DOMDocument and DOMXPath to parse the HTML content and add the class to the elements. Here is an example code snippet:
php
$html = 'Paragraph 1
Paragraph 2
';
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$paragraphs = $xpath->query('//div[contains(@class, "woocommerce-product-details__short-description")]/p');
if ($paragraphs->length > 1) {
foreach ($paragraphs as $paragraph) {
$paragraph->setAttribute('class', 'ukryj-klase-krotki');
}
}
$newHtml = $dom->saveHTML();
echo $newHtml;
This code snippet loads the HTML content into a DOMDocument, uses DOMXPath to query for paragraph elements within the specified class, and adds the class 'ukryj-klase-krotki' to the paragraph elements if there are more than one. Finally, it outputs the modified HTML content.
Rate this post
5 of 5 based on 4208 votesComments