Статьи

Удалить автоматические абзацы в шорткодах

Этот пост является расширением поста, который я написал некоторое время назад об отображении фрагментов кода на сайте WordPress . В этом посте было показано, как создать плагин WordPress, который создает шорткод для ряда различных языков, которые будут кодировать контент, чтобы вы могли отображать фрагменты кода на своем сайте WordPress.

Используя этот плагин, вы получите доступ к четырем шорткодам: HTML, CSS, JavaScript и PHP.

<div class="html">
     <h1>HTML</h1>
</div>
.css_class
{

}
var js = document.getElementById('element');
<?php
     echo 'This is PHP.';
?>

Но поскольку мы кодировали контент с использованием htmlentities, это вызвало некоторые проблемы с тем, как WordPress отображает контент. WordPress автоматически изменит двойные разрывы строк на теги абзаца. В этой статье мы увидим, что это за проблемы, и найдем решение для их решения.

WordPress Автоматические Параграфы

Когда WordPress отображает ваш контент на странице, он запускает его через два разных фильтра: wptexturize и wpautop .

wptexturize — это фильтр, который преобразует все цитаты в умные. Он также преобразует апострофы, тире, эллипсы, символ торговой марки и символ умножения. Поскольку код обычно использует прямые кавычки вместо фигурных кавычек, текст внутри тегов pre и code игнорируется.

wpautop — это фильтр, который преобразует двойные разрывы строк в теги paragragh. Когда вы добавляете новую строку при использовании редактора tinyMCE , он создает двойной разрыв строки, поэтому этот фильтр решает эту проблему.

Это проблема внутри шорткодов, которые запускают контент через функцию htmlentities (), потому что он преобразует HTML, чтобы он отображался в области контента шорткода.

Поэтому, если вы создаете шорткод для отображения HTML, как это:

[ html ]
<div id="code"></div>
[ /html ]

Поскольку в этом шорткоде есть разрывы строк при переходе на новую строку, wpautop () попытается преобразовать этот текст. Так как мы используем htmlentities для содержимого шорткода, выходные данные будут отображать эти теги абзаца и теги разрыва строки. Что на самом деле будет возвращено из шорткода, так это:

</p>
<div id="code"></div><br/>
<p>

Вы можете увидеть закрывающий тег абзаца и разрыв строки в конце строки с элементом div.

Если вы пытаетесь отобразить дополнительную информацию, такую ​​как класс CSS с разрывом строки для каждого свойства, она будет отображаться следующим образом:

<br />
.alert-danger,<;br />
.alert-error {<br />
color: #b94a48;<br />
background-color: #f2dede;<br />
border-color: #eed3d7;<br />
}<br />

Turning Off wpautop()

Removing these line breaks and paragraph tags from the content is very easily done in WordPress. All we have to do is make sure the content doesn’t go through the wpautop filter by removing it.

To remove a filter in WordPress, all you have to do is use the function remove_filter(), pass in the tag of the_content and remove the function wpautop.

remove_filter('the_content', 'wpautop');

But if we use this function to remove the wpautop() then it will be removed for all content, which will remove all paragraphs in your content, which makes your content unreadable.

In order to display code snippets correctly, we need to find a way of solving this problem without turning off wpautop() on all content. We will only want to turn this off on content inside shortcodes.

Removing wpautop() from Content Only in Shortcodes

To remove the wpautop() function only in shortcodes we need to create a brand-new filter through which to run all of our content.

First, we turn off wpautop filters and wptexturize filters on all content.

remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');

This new filter will need to check to see how the content is being displayed. If the content is inside a shortcode, then it won’t run through the wptexturize and wpautop functions. If the content is not inside the shortcodes, then it will apply the wptexturize and wpautop functions.

function remove_auto_p_in_shortcode_formatter($content) {
	$new_content = '';
	$pattern_full = '{(\[raw\].*?\[/raw\])}is';
	$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
	$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

	foreach ($pieces as $piece) {
		if (preg_match($pattern_contents, $piece, $matches)) {
			$new_content .= $matches[1];
		} else {
			$new_content .= wptexturize(wpautop($piece));
		}
	}
	return $new_content;
}

add_filter('the_content', 'remove_auto_p_in_shortcode_formatter', 99);

Now, all the code inside shortcodes will not have a trailing paragraph tag and you will no longer have line breaks at the end of your code snippets.

If you’d like a copy of the syntax highlighter used on Paulund, it is available on GitHub as a WordPress plugin.

Paulund Syntax Highlighter