PHP function to edit HTML using php DOM Parser
Question
In a page I need to find a text or a HTML element by class. If I find this text (or element), in the page I show or hide specific div.classes.
HTML:
<!-- If found -->
<div class="x">content</div> <!-- hide -->
<div class="y">content</div> <!-- hide -->
<div class="z">content</div> <!-- show -->
<div class="w">content</div> <!-- show -->
<!-- If NOT found -->
<div class="x">content</div> <!-- show -->
<div class="y">content</div> <!-- show -->
<div class="z">content</div> <!-- hide -->
<div class="w">content</div> <!-- hide -->
I would use a php function in functions.php to do this, because I already use js but it works badly.
You can see a method to filter data like this (ref. here):
<?php
require_once('simple_html_dom.php');
function page_filter($content){
// Only proceed if we're using the right template
$template = get_post_meta(get_the_ID(), '_wp_page_template', true);
if ($template != 'main-template.php'){
return $content;
}
// Re-generate DOM after stripping p tags off images
$html = str_get_html(strip_p_from_img($content));
// p tags and anything that can interrupt them
$replace = "p,h1,h2,h3,h4,h5,h6,img,hr,table";
// For looping purposes.
// Are we currently in a div?
$mid_div = false;
// Get all instances of tags in $replace
$instances = $html->find($replace);
// loop through
foreach ($instances as $key=>$element){
$tag = $element->tag; // get current tag
// If we aren't mid-div and encounter a paragraph, start our div!
if (!$mid_div){
if ($tag === 'p'){
$instances[$key]->outertext =
"<div class="long-description">" . $element->outertext;
$mid_div = true;
}
// This is a limiting case; the only tag is a single paragraph
if (!array_key_exists($key+1, $instances)){
$element->outertext .= "</div>";
}
else{
$mid_div = true; // we're mid-div now!
}
}
// If we're mid-div and hit an "interrupting" tag,
// or we're out of paragraphs, end the div!
else{
if ($tag !== 'p'){
$element->outertext = "</div>" . $element->outertext;
$mid_div = false;
}
if ($tag === 'p' && !array_key_exists($key+1, $instances)){
$element->outertext .= "</div>";
$mid_div = false;
}
}
}
return $html;
}
add_filter('the_content', 'page_filter');
Can I edit the above function for my needs? Thank you.
0
3 months
0 Answers
13 views
0
Leave an answer
You must login or register to add a new answer .