WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Put tagged-snippet in <pre></pre> tag (3 posts)

  1. kcyeu
    Member
    Posted 4 years ago #

    Hi,

    I am trying to put my WPF code snippet in a HTML "pre" tag pair
    with a syntax-highlighter, but there are two problems (see the screenshot):

    1. All the tags are turned into lower case.
    For example, "Window" in <Window></Window> shoud keep its capitalized form; but obviously it was lowered.

    2. Error-prone tag closing.
    As you can see in the screenshot, the "Grid.RowDefinitions" tag was closed in line 6; so the marked tag in line 24 is redundant, as well as some tags in the same line.

    I'm quite sure that the formatting option "WordPress should correct invalidly nested XHTML automatically" in the "Settings->Writing" was unchecked.
    And I reviewed my saved post, the content wasn't changed, so I guess the snippet was reformed after read from the DB.

    Any idea?

  2. vtxyzzy
    Member
    Posted 4 years ago #

    Don't remember where I got this, but it will format code nearly the same as in this forum. Just add it to the end of your functions.php, and use [raw] ... [/raw] shortcodes to wrap your code.

    <?php
    function raw_formatter($content) {
      // Shortcode [raw] ... {/raw] to preserve code formatting
    	$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)) {
            $newstr = htmlspecialchars($matches[1], ENT_NOQUOTES);
            $new_content .= '<pre>' . preg_replace('/\n/is','<br />',$newstr) . '</pre>';
    		} else {
    			$new_content .= wptexturize(wpautop($piece));
    		}
    	}
    
    	return $new_content;
    }
    remove_filter('the_content', 'wpautop');
    remove_filter('the_content', 'wptexturize');
    
    add_filter('the_content', 'raw_formatter', 99);
    ?>
  3. kcyeu
    Member
    Posted 4 years ago #

    @vtxyzzy:

    Thanks for you reply, it brought me a new thought.

    I found the plug-in "SyntaxHighlighter Plus" use similar technique to solve this problem; plus, a decent decoration. :-)

    Thank you!

Topic Closed

This topic has been closed to new replies.

About this Topic