G
G
Gloynus Aleos2018-08-31 12:24:26
CMS
Gloynus Aleos, 2018-08-31 12:24:26

WordPress. How to automatically wrap blocks before displaying on the page?

Site on WordPress.
Articles often build multi-level lists. Each sublevel must be folded into a spoiler.
There is a solution via JQ:

jQuery('li>ol').wrap('<div class="spoil"><div class="sp_text"></div></div>'); // обернуть
jQuery( '.spoil' ).prepend('<button class="sp_button">Подробности</button>'); // добавить кнопку

The main disadvantage of this solution is that it distorts the numbering, since it changes the code after it has been output.
Questions:
1) Will it be better to leave the solution through JQ and figure out how to restore the numbering, or is it better to find a solution through PHP?
2) How to restore numbering? Transferring the parent block to another class, which also describes the styles needed for numbering? Or is there a better solution?
3) How, after all, in WordPress, before displaying the finished HTML code on the page, find the necessary blocks in it and wrap them?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Gloynus Aleos, 2018-11-02
@Gloynus_Aleos

Solution found. If anyone is interested, then it's done like this.

add_filter('the_content', 'spoilers');
function spoilers( $text ){
  $text = preg_replace('/(<\/ol>)(((?!<li.*>|<\/li>|<ol.*>|<\/ol>).)*?)(<\/li>)/s', '$1$2</div></div>$2$4', $text);
  $text = preg_replace('/(<li>((?!<li.*>|<\/li>|<ol.*>|<\/ol>).)*?)(<ol>)/s', '$1<div class="spoil"><button class="sp_button>Подробности</button><div class="sp_text">$2$3', $text);
  return $text;

I
Igor Mavlikhanov, 2018-08-31
@Gori4ka

You can hook onto the filter the_contentand then wrap it using a regular expression

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question