Added Demo posts inserter

This commit is contained in:
Jeremy Rangel
2025-01-02 03:07:43 -08:00
parent 1ce1a08442
commit 4447e50bcf
18 changed files with 278 additions and 360 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 723 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 875 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 698 KiB

View File

@ -0,0 +1,33 @@
document.addEventListener('DOMContentLoaded', function () {
// Check if the button exists before adding the event listener
const importButton = document.getElementById('import-demo-posts');
if (importButton) {
importButton.addEventListener('click', function () {
const formData = new FormData();
// Append action and nonce to the form data
formData.append('action', 'lcp_import_demo_posts');
formData.append('lcp_import_nonce', lcp_ajax_obj.nonce); // Add the nonce passed by wp_localize_script
// Send the AJAX request
fetch(lcp_ajax_obj.ajax_url, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert(data.data); // Success message
} else {
alert('Error: ' + (data.data || 'Unknown error')); // Error message
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while processing your request.');
});
});
} else {
console.warn('Import button not found.');
}
});

View File

@ -1,57 +0,0 @@
<?php
// Path to your icons.json file
$filePath = 'output.json';
// Read the content of the JSON file
$jsonData = file_get_contents($filePath);
// Decode the JSON data into a PHP array
$iconsData = json_decode($jsonData, true);
// Check if the data is decoded successfully
if (json_last_error() !== JSON_ERROR_NONE) {
die('Error decoding JSON data: ' . json_last_error_msg());
}
// Check if the data contains a 'family' key (indicating it has families with SVGs)
if (isset($iconsData[0]['family'])) {
// Handle the case with families and svgs (structure 1)
foreach ($iconsData as &$family) {
if (isset($family['svgs']) && is_array($family['svgs'])) {
// Sort the 'svgs' array alphabetically by the 'name' field
usort($family['svgs'], function($a, $b) {
return strcmp($a['name'], $b['name']);
});
}
}
// Sort the families by the 'family' field (if needed)
usort($iconsData, function($a, $b) {
return strcmp($a['family'], $b['family']);
});
} else {
// Handle the case without families (structure 2)
// Sort the flat array of icons alphabetically by the 'name' field
usort($iconsData, function($a, $b) {
return strcmp($a['name'], $b['name']);
});
}
// Encode the sorted data back to JSON
$sortedJsonData = json_encode($iconsData, JSON_PRETTY_PRINT);
// Check if encoding was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die('Error encoding JSON data: ' . json_last_error_msg());
}
// Write the sorted JSON data back to the file
if (file_put_contents($filePath, $sortedJsonData)) {
echo "The icons data has been sorted and saved successfully!";
} else {
echo "Error writing the sorted data to the file.";
}
?>

View File

@ -1,61 +0,0 @@
<?php
// Function to generate a UUID (compliant with MySQL UUID)
function generateUUID() {
return bin2hex(random_bytes(16)); // Generate a random UUID
}
// Function to convert the raw SVG to JSON format
function convertSymbolsToJSON($svgContent) {
// Match all <symbol> elements and extract them
preg_match_all('/<symbol[^>]*>[\s\S]*?<\/symbol>/', $svgContent, $matches);
$jsonData = [];
foreach ($matches[0] as $symbol) {
// Extract 'id', 'viewBox', and 'path' attributes
preg_match('/id="([^"]+)"/', $symbol, $idMatches);
preg_match('/viewBox="([^"]+)"/', $symbol, $viewBoxMatches);
preg_match('/<path[^>]*d="([^"]+)"/', $symbol, $pathMatches);
// If we have a valid symbol, process it
if (isset($idMatches[1]) && isset($viewBoxMatches[1]) && isset($pathMatches[1])) {
// Generate a UUID for the symbol
$uniqueId = generateUUID();
// Capitalize the name by replacing hyphens with spaces and capitalizing each word
$name = ucwords(str_replace('-', ' ', $idMatches[1]));
// Build the symbol JSON object
$symbolJSON = [
"id" => $uniqueId,
"name" => $name,
"viewBox" => $viewBoxMatches[1],
"path" => "<path d='" . $pathMatches[1] . "'/>"
];
// Add the symbol JSON to the data array
$jsonData[] = $symbolJSON;
}
}
return $jsonData;
}
// Read the SVG file (assumes it's in the same directory)
$svgFilePath = 'input.svg'; // The input SVG file
if (file_exists($svgFilePath)) {
$svgContent = file_get_contents($svgFilePath);
// Convert symbols to JSON
$symbolsJson = convertSymbolsToJSON($svgContent);
// Output the JSON data to a file
$outputFilePath = 'output.json';
file_put_contents($outputFilePath, json_encode($symbolsJson, JSON_PRETTY_PRINT));
echo "JSON file has been created successfully: $outputFilePath\n";
} else {
echo "Error: SVG file not found.\n";
}
?>

View File

@ -0,0 +1,57 @@
{
"posts": [
{
"title": "Mysterious Weather Patterns Reported in Faketown",
"content": "Faketown, USA — In what can only be described as a strange turn of events, Faketown residents have been experiencing unpredictable weather patterns. Local meteorologists have been baffled as sudden temperature shifts have been occurring at all hours of the day. One moment, the sun is shining brightly, and the next, it's snowing. This bizarre occurrence is leaving many questioning whether this is a sign of something more ominous. 'Ive lived here my entire life, and Ive never seen anything like this,' said local resident Jane Doe.",
"excerpt": "Faketown residents have been experiencing unpredictable weather patterns, baffling local meteorologists.",
"category": "Local News",
"tags": ["weather", "Faketown", "mystery"],
"date": "2025-01-01",
"status": "publish",
"thumbnail": "demo-post-thumbnail-1.jpg"
},
{
"title": "Faketown Mayor Announces New Green Initiative",
"content": "In a recent press conference, Faketowns mayor, John Smith, unveiled an ambitious plan to tackle climate change within the city. The initiative aims to reduce carbon emissions by 40% over the next 10 years, primarily by encouraging the use of electric vehicles and expanding the city's public transportation system. 'We are committed to making Faketown a greener place,' said Mayor Smith. 'Our children and grandchildren deserve a sustainable future.' The plan includes installing charging stations for electric cars across the city and offering tax incentives for green energy solutions.",
"excerpt": "Faketowns mayor unveils a new green initiative to reduce carbon emissions by 40%.",
"category": "Politics",
"tags": ["green", "climate change", "Faketown"],
"date": "2025-01-02",
"status": "publish",
"thumbnail": "demo-post-thumbnail-2.jpg"
},
{
"title": "Local Chef Opens Revolutionary Restaurant in Faketown",
"content": "Faketown, USA — In a culinary first for Faketown, renowned chef Sarah Bellamy has opened a new restaurant that combines traditional American cuisine with exotic flavors from around the world. Located in the heart of Faketown, Bellamys restaurant has already become the talk of the town. The menu features a variety of dishes, including 'Fusion Fries' and 'Sushi Burger.' 'I wanted to create something completely unique, a blend of cultures,' said Bellamy. The restaurant offers both dine-in and delivery services, with plans to expand its menu soon.",
"excerpt": "Faketown's new restaurant is offering a fusion of global flavors with a local twist.",
"category": "Food & Drink",
"tags": ["restaurant", "food", "Faketown"],
"date": "2025-01-03",
"status": "publish",
"thumbnail": "demo-post-thumbnail-3.jpg"
},
{
"title": "Strange Creatures Spotted in Faketown's Forests",
"content": "In the deep forests surrounding Faketown, local hikers have begun reporting sightings of strange creatures. Descriptions vary, but many claim to have seen large, mysterious beings with glowing eyes. Some hikers have even reported hearing unusual sounds that have no obvious explanation. 'I was out for a hike last week when I saw something huge moving through the trees,' said Greg Johnson, a local resident. 'I dont know what it was, but it wasnt a bear.' Authorities are urging hikers to stay on well-trodden paths and report any strange occurrences.",
"excerpt": "Faketown residents report strange creatures spotted in nearby forests, baffling experts.",
"category": "Strange Happenings",
"tags": ["mystery", "Faketown", "creatures"],
"date": "2025-01-04",
"status": "publish",
"thumbnail": "demo-post-thumbnail-1.jpg"
},
{
"title": "Faketown's Annual Festival Breaks Attendance Records",
"content": "This year's annual Faketown Festival was a resounding success, breaking all previous attendance records. Held in the town square, the festival featured local bands, food trucks, and street performances. The highlight of the event was the traditional 'Faketown Parade,' which saw thousands of people lining the streets. 'Weve never seen this many people come out,' said event coordinator Lisa Thompson. The festivals success has sparked excitement about next years event, with many suggesting that Faketown could become a regional hub for arts and culture.",
"excerpt": "Faketowns annual festival saw record-breaking attendance, with thousands of people participating.",
"category": "Community Events",
"tags": ["festival", "community", "Faketown"],
"date": "2025-01-05",
"status": "publish",
"thumbnail": "demo-post-thumbnail-2.jpg"
}
]
}

View File

@ -1,57 +0,0 @@
<?php
// Path to the input JSON file
$inputFile = 'font-awesome-v6.1.7-solid-svgs.json';
// Step 1: Load the JSON data
$jsonData = file_get_contents($inputFile);
// Check if the file was read successfully
if ($jsonData === false) {
die("Error reading the JSON file.");
}
// Step 2: Decode the JSON data into a PHP array
$data = json_decode($jsonData, true);
// Check if JSON decoding was successful
if ($data === null) {
die("Error decoding the JSON data.");
}
// Step 3: Modify the structure by extracting the 'd' value and formatting the 'paths' tag
foreach ($data as $index => $iconSet) {
if (isset($iconSet['svgs']) && is_array($iconSet['svgs'])) {
foreach ($iconSet['svgs'] as $svgIndex => $svg) {
// Check if 'path' exists
if (isset($svg['path'])) {
// Extract the 'd' attribute value from the nested path string
preg_match('/d=[\'"]([^\'"]+)[\'"]/i', $svg['path'], $matches);
// If we found the 'd' value, format the paths correctly
if (isset($matches[1])) {
$dValue = $matches[1]; // Get the actual 'd' value from the path
// Escape the 'd' value for JSON format (escape double quotes inside the string)
$escapedDValue = str_replace('"', '\\"', $dValue);
// Now, add the proper <path> tag to the 'paths' field
$svg['paths'] = "<path d=\"{$escapedDValue}\"/>";
}
unset($svg['path']); // Optionally remove the original 'path' key
}
// Save the modified svg back to the array
$data[$index]['svgs'][$svgIndex] = $svg;
}
}
}
// Optional: Save the modified JSON to a new file
$outputFile = 'solid-fixed-paths.json';
file_put_contents($outputFile, json_encode($data, JSON_PRETTY_PRINT));
// Output the success message
echo "Successfully modified and saved the JSON file with 'path' converted to 'paths'.\n";
?>

View File

@ -1,63 +0,0 @@
<?php
// Path to the input JSON file
$inputFile = 'material-icons-twotone.json';
// Path to the output JSON file
$outputFile = 'material-icons-twotone-unescaped-with-ids.json';
// Function to generate a MySQL-style UUID
function generateUUID() {
// Generates a version 4 UUID (random)
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
// Step 1: Load the JSON data
$jsonData = file_get_contents($inputFile);
// Check if the file was read successfully
if ($jsonData === false) {
die("Error reading the JSON file.");
}
// Step 2: Decode the JSON data into a PHP array
$data = json_decode($jsonData, true);
// Check if JSON decoding was successful
if ($data === null) {
die("Error decoding the JSON data.");
}
// Step 3: Iterate through each item and unescape the 'paths' key, and generate a new 'id'
foreach ($data as &$icon) {
// Unescape only HTML entities (without affecting forward slashes)
$icon['paths'] = html_entity_decode($icon['paths'], ENT_QUOTES | ENT_HTML5);
// Generate a new MySQL-style UUID for each 'id'
$icon['id'] = generateUUID();
}
// Step 4: Encode the modified data back into JSON format
$newJsonData = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
// Check if encoding was successful
if ($newJsonData === false) {
die("Error encoding the JSON data.");
}
// Step 5: Save the modified JSON data to the output file
file_put_contents($outputFile, $newJsonData);
// Check if file writing was successful
if (file_put_contents($outputFile, $newJsonData) === false) {
die("Error saving the modified JSON data.");
}
echo "Paths have been unescaped, IDs have been added, and saved to '$outputFile'.\n";
?>

View File

@ -1,86 +0,0 @@
<?php
// Function to capitalize the 'name' field (capitalizes acronyms fully)
function capitalizeName($name) {
// Define a pattern to match acronyms (words in uppercase with no spaces)
$acronymPattern = '/\b[A-Z]{2,}\b/';
// Capitalize each word, and keep acronyms fully uppercase
$name = preg_replace_callback('/\b\w+\b/', function ($matches) use ($acronymPattern) {
$word = $matches[0];
// If it's an acronym (all uppercase), return as is
if (preg_match($acronymPattern, $word)) {
return strtoupper($word);
}
// Otherwise capitalize the first letter of each word and lowercase the rest
return ucfirst(strtolower($word));
}, $name);
return $name;
}
// Function to generate a MySQL UUID format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
function generateMysqlUuid() {
// Generate a UUID using PHP's random_bytes for a total of 16 random bytes
$data = random_bytes(16);
// Set the version to 4 (random UUID)
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Version 4
// Set the variant to RFC4122
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // RFC4122 variant
// Now unpack the data into 5 parts for formatting as UUID
$hexData = unpack('H8a/H4b/H4c/H4d/H12e', $data);
// Return the UUID in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
return $hexData['a'] . '-' . $hexData['b'] . '-' . $hexData['c'] . '-' . $hexData['d'] . '-' . $hexData['e'];
}
// Get the current directory of the script
$currentDir = __DIR__;
// Get all JSON files in the current directory
$jsonFiles = glob($currentDir . '/*.json');
// Iterate over each JSON file
foreach ($jsonFiles as $file) {
// Read the content of the file
$jsonContent = file_get_contents($file);
// Decode JSON to array
$data = json_decode($jsonContent, true);
// Check if the data is valid
if (json_last_error() === JSON_ERROR_NONE) {
// Process each SVG object
foreach ($data as &$set) {
if (isset($set['svgs'])) {
foreach ($set['svgs'] as &$svg) {
// Capitalize the 'name' field
if (isset($svg['name'])) {
$svg['name'] = capitalizeName($svg['name']);
}
// Generate a new MySQL UUID for the 'id' field
if (isset($svg['id'])) {
$svg['id'] = generateMysqlUuid();
}
}
}
}
// Re-encode the modified data to JSON
$newJsonContent = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
// Define the output file name (you can change this as needed)
$outputFile = $currentDir . '/modified_' . basename($file);
// Save the updated content back to a new file
file_put_contents($outputFile, $newJsonContent);
echo "Processed and saved to: " . basename($outputFile) . "\n";
} else {
echo "Invalid JSON in file: " . basename($file) . "\n";
}
}
?>