Files
WP-LIT-MCP/src/Integrations/WordPress/Schema/MetaFieldSource.php
T

39 lines
1.1 KiB
PHP

<?php
declare(strict_types=1);
namespace LIT\MCP\Integrations\WordPress\Schema;
/**
* Shared read/write via the post meta API.
*/
abstract class MetaFieldSource implements FieldSource
{
public function read(int $postId, FieldDefinition $field): mixed
{
return get_post_meta($postId, $field->key, ! $field->multiple);
}
public function write(int $postId, string $postType, array $values, array $definitions): void
{
foreach ($values as $key => $value) {
$key = (string) $key;
if ($value === null) {
delete_post_meta($postId, $key);
continue;
}
$field = $definitions[$key] ?? null;
if ($field !== null && $field->multiple && is_array($value) && array_is_list($value)) {
delete_post_meta($postId, $key);
foreach ($value as $item) {
add_post_meta($postId, $key, wp_slash($item));
}
continue;
}
update_post_meta($postId, $key, wp_slash($value));
}
}
}