Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Strip content from between header and footer tags and insert into WordPress database
<?php
function getMiddle($first, $end, $contents, $file)
{
$arrBegin = explode($first, $contents);
if (count($arrBegin) != 2)
{
echo 'Bad Begin: '.$file;
die();
}
$arrEnd = explode($end, $arrBegin[1]);
if (count($arrEnd) != 2)
{
echo 'Bad End: '.$file;
die();
}
return $arrEnd[0];
}
function replaceComponents($content)
{
$content = str_replace(array(
'src="img/',
'.php"',
), array(
'src="/wp-content/themes/custom/img/',
'"',
), $content);
$content = trim($content);
return $content;
}
function getFileName($file, &$arr)
{
$arr[] = str_replace('.php', '', basename($file));
}
function getTitle($content, &$arr)
{
$regex = '#<h1>(.*?)</h1>#';
$code = preg_match($regex, $content, $matches);
if (count($matches) != 2)
{
echo 'Bad Title: ';
print_r($matches);
die();
}
$arr[] = $matches[1];
}
$files = glob(__DIR__.'/source/*.php');
$arrContent = array();
$names = array();
$titles = array();
foreach ($files as $file)
{
// Get the contents
$contents = file_get_contents($file);
// Get the middle (strip header and footer)
$output = getMiddle('/header>', '<footer', $contents, $file);
// Convert absolute links to relative links
$output = replaceComponents($output);
// Get the required WordPress information
getFileName($file, $names);
getTitle($output, $titles);
$arrContent[] = $output;
// Save the new file
file_put_contents(__DIR__.'/dest/'.basename($file), $output);
}
//print_r($titles);
//print_r($names);
//print_r($arrContent);
//die();
$queries = '';
$start = 10;
for($i = 0; $i < count($names); $i++)
{
$content = mysql_real_escape_string($arrContent[$i]);
$title = mysql_real_escape_string($titles[$i]);
$name = mysql_real_escape_string($names[$i]);
$guid = mysql_real_escape_string('http://localhost/page_id='.($start+$i));
$query = "INSERT INTO wp_posts SET
post_author=1,
post_date=now(),
post_date_gmt=now(),
post_content='$content',
post_title='$title',
post_excerpt='',
post_status='publish',
comment_status='open',
ping_status='open',
post_password='',
post_name='$name',
to_ping='',
pinged='',
post_modified=now(),
post_modified_gmt=now(),
post_content_filtered='',
post_parent='107',
guid='$guid',
menu_order='0',
post_type='page',
post_mime_type='',
comment_count='0';
";
$queries .= $query;
}
print_r($queries);
echo 'Done';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.