How I added GeSHi to GPORG. Here I will demonstrate using GeSHi (for prettification purposes).

PHP
  1. <?php
  2.  
  3. function sexy_code ($a, $content) {
  4. $attr = shortcode_atts(array( // sets the defaults for each attribute so we don't run into errors if we're missing any
  5. 'lang' => 'html', // default language is HTML
  6. 'start' => '1' // which line num to start on
  7. ), $a);
  8.  
  9. $content = strip_tags($content); // remove wpautop() formatting from the snippet
  10.  
  11. $array = explode("\n", $content);
  12. $tab = null;
  13. $t = 0;
  14. $pos = null;
  15.  
  16. foreach ($array as $i => $line) {
  17. $code = $line;
  18. if (strpos($line, '//') !== false) {
  19. list($code, $comment) = explode('//', $line);
  20. }
  21. if (preg_match("#\{|\($#", $code)) {
  22. $pos = 'after';
  23. $t++;
  24. }
  25. elseif (preg_match("#\}|\)$#", $code)) {
  26. $pos = 'before';
  27. $t--;
  28. }
  29. $tab = ($t > 0 ? implode("", array_fill(0, $t, " ")) : null);
  30. $line = ($pos == 'before' ? $tab : null).$line.( $pos == 'after' ? $tab : null);
  31. $array[$i] = $line;
  32. }
  33. $content = implode("\n", $array);
  34. $content = preg_replace("#( +)(\n)#", "\\2\\1", $content);
  35. $content = str_replace(" }", "}", $content);
  36.  
  37. $content = preg_replace("#\&amp;([a-z0-9]+);#", "&\\1;", $content);
  38. $content = str_replace('&lt;', '<', $content);
  39. $content = str_replace('&gt;', '>', $content);
  40.  
  41. //echo secret_output ('test HTML',$content);
  42.  
  43. $lang = $attr['lang'];
  44. $geshi = new GeSHi($content, $lang);
  45. $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS); // type of line numbers
  46. $geshi->enable_classes(); // turns on classes so we can prettify thru CSS
  47. if ($attr['start'] != 1) // if you specifically mentioned which line number you want the snippet to start on
  48. $geshi->start_line_numbers_at($attr['start']); // ...set it here
  49.  
  50. $r = $geshi->parse_code();
  51.  
  52. $r = str_replace('<ol>', '<ol class="no-custom">', $r);
  53. $r = preg_replace("#^<pre>#", '<pre class="wp-block-code">', $r);
  54.  
  55. return $r;
  56. }
  57. add_shortcode( 'code', 'sexy_code' ); // shortcodify!
  58.  
  59. ?>

(See the doc on Wordpress’s shortcode API if you haven’t already.)

To use in a post…

  1. [code lang="php" start="2"]<?php echo $fun; ?>[/code]

…will get you…

PHP
  1. <?php echo $fun; ?>