Skip to content

Instantly share code, notes, and snippets.

@batonac
Last active June 5, 2023 19:33
Show Gist options
  • Save batonac/ed6af84e2d5efc4bb29795c3456a0740 to your computer and use it in GitHub Desktop.
Save batonac/ed6af84e2d5efc4bb29795c3456a0740 to your computer and use it in GitHub Desktop.
Normalize WordPress Post Meta and Metabox Relationships using PowerShell and CSV inputs
# 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 each relationship as a new property to the post object
try {
$relationships_table = $using:relationships_table
$relationships = $relationships_table[$post_id]
$posts_table = $using:posts_table
foreach ($relationship in $relationships) {
$relationshipType = $relationship.type
# drop any '-int' suffix from the relationship type
$relationshipType = $relationshipType -replace '-\d+$'
$toPostId = $relationship.to
$toPost = $posts_table[$toPostId]
if ($null -ne $toPost) {
$relationshipColumnName = "$relationshipType $($relationships.IndexOf($relationship) + 1)"
$post = $post | Add-Member -MemberType NoteProperty -Name $relationshipColumnName -Value $toPost.post_title -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