Skip to content

Instantly share code, notes, and snippets.

@greg-randall
Last active July 23, 2021 15:33
Show Gist options
  • Select an option

  • Save greg-randall/1e20fb76f61f6061e1d3e1c7ded4444f to your computer and use it in GitHub Desktop.

Select an option

Save greg-randall/1e20fb76f61f6061e1d3e1c7ded4444f to your computer and use it in GitHub Desktop.
Title Case converter for WordPress post exports.
<?php
/*
Takes a Wordpress Post export and changes the case of the words in the <title> tag to title-case.
This will print out a list of titles at the top with the title case and then the original case, so
you can check over and make sure that you don't need to add any special cases:
Add acronyms or words with non-standard capitalization to the array $caps_words. (note, add spaces
around the word/phrase i.e. ' GitHub '.
To update existing posts requires a temporary addition to your functions file --
https://gist.github.com/balbuf/d232769f1e7d66fe91b8ecd7795ef3cb
Note: automatically downloads the titlecase.php from GitHub. https://github.com/Kroc/PHPtitleCase/
*/
$print_titles = true;
if (!isset($_POST["input"])) { //check to see if there's content to clean if not, prompt for it
?>
Enter a WordPress XML file with titles that are all caps, and it will output title case titles:
<form action="index.php" method="post">
<textarea name="input" rows="50" cols="160"></textarea><br><br>
<input type="submit">
</form>
<?php
exit();
} else {
if(!file_exists('titlecase.php')){
file_put_contents('titlecase.php',file_get_contents('https://raw.githubusercontent.com/Kroc/PHPtitleCase/master/titlecase.php'));
}
require 'titlecase.php';
$caps_words = array( ' USA ', ' WordPress ');
$input = $_POST["input"];
$dom = new DOMDocument();
$dom->loadXML($input);
$xpath = new DOMXPath($dom);
$elements = $xpath->query("//title");
if($print_titles){echo "<table border=\"3\"><tr><th>Title Case</th><th>Original Title</th></tr>\n";}
foreach ($elements as $element) { //loops through all the elements
$dirty_title = $element->nodeValue;
$clean_title = trim(titleCase( str_ireplace($caps_words, $caps_words, strtolower( ' '. $dirty_title ) .' ' ) ) );
$input = str_ireplace($dirty_title,$clean_title,$input); //does a replace so as to introduce the minimum nubmer of changes into the XML file
if($print_titles){echo "<tr><td>$clean_title</td><td>$dirty_title</td></tr>\n";} //print the titlecase and non title case
}
if($print_titles){echo "</table><br><br>";}
echo "<pre>" . htmlspecialchars($input) . "</pre>"; //displays the cleaned html directly in the page for easy copy and paste
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment