Last active
June 5, 2023 19:33
-
-
Save batonac/6e21e74fc2ac3b046eb08eff33f6ede3 to your computer and use it in GitHub Desktop.
Normalize WordPress Post Meta using PowerShell and CSV inputs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Import the CSV files | |
$posts_table = Import-Csv -Path "wp_posts.csv" | Group-Object -AsHashTable -Property 'ID' | |
$postmeta_table = Import-Csv -Path "wp_postmeta.csv" | Group-Object -Property 'post_id' | |
$relationships_table = Import-Csv -Path "wp_mb_relationships.csv" | Group-Object -Property 'from' | |
# remove subdirectory "Posts" if it exists | |
if (Test-Path ".\Posts") { | |
Remove-Item -Path ".\Posts" -Recurse | |
} | |
# add subdirectory "Posts" | |
New-Item -ItemType Directory -Path ".\Posts" | |
# Use ConcurrentBag to store modified post objects | |
$postsWithMeta = New-Object System.Collections.Concurrent.ConcurrentBag[pscustomobject] | |
# Iterate over each metadata group | |
$posts_table.GetEnumerator() | ForEach-Object -Parallel { | |
$post = $_ | |
$post_id = $_.Name | |
# Add each meta key-value pair as a new property to the post object | |
try { | |
$postmeta_table = $using:postmeta_table | |
$postmeta = $postmeta_table[$post_id] | |
foreach ($meta in $postmeta) { | |
$post = $post | Add-Member -MemberType NoteProperty -Name $meta.meta_key -Value $meta.meta_value -Force -PassThru | |
} | |
} catch {} | |
# Add the modified post object to the ConcurrentBag | |
$postsWithMeta = $Using:postsWithMeta | |
$postsWithMeta.Add($post) | |
} -ThrottleLimit $env:NUMBER_OF_PROCESSORS | |
# Group the modified post objects by post_type | |
$posts_by_type = $postsWithMeta | Group-Object -Property post_type | |
# Export the posts of each type to their respective CSV files | |
foreach ($postType in $posts_by_type) { | |
$posts_of_type = $postType.Group | |
$posts_of_type | Export-Csv -Path ".\Posts\$($postType.Name).csv" -NoTypeInformation | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment