在WordPress中创建帖子时掌握元数据

Jas*_*son 5 wordpress

我正在使用save_post操作来检查自定义帖子中的元数据字段并对该值执行一些操作。这是我做事的基本要点:

add_action('save_post', 'my_save_post');

function my_save_post($post_id)
{
    // Check if not autosaving, processing correct post type etc.
    // ...

    // Get the custom field value.
    $my_field_value = get_post_meta($post_id, 'my_field', true);

    // Do some action
    // ...
}
Run Code Online (Sandbox Code Playgroud)

通过管理页面更新帖子时,效果很好。但是,在首次创建帖子时,my_field_value始终为空。该字段确实得到正确保存,但是此操作触发器似乎无法看到它,也看不到任何其他自定义字段值。

我希望对创建的所有此类帖子执行该操作,并且我将通过CSV导入插件导入许多内容。即使这样,也确实可以正确导入自定义字段,并且确实会为导入的每一行触发操作触发器,但是save_post操作仍然看不到自定义字段值。

据我从文档中看到的那样,该操作触发时,该帖子已经创建了,因此我应该始终能够看到该自定义元字段。


答案似乎是事情发生的顺序。从表单创建帖子时,所有自定义字段均由相应的操作收集,并在我的save_post操作触发之前添加到帖子中。这意味着我的触发器能够看到那些自定义字段值。

从CSV导入时,首先创建基本帖子,然后添加自定义元字段。在添加元字段之前,save_post触发器在首次创建时触发,因此自定义字段数据对save_post操作不可见。

我的解决方案是使用updated_post_metaadded_post_meta动作以及save_post动作来捕获元数据的更新:

add_action('updated_post_meta', 'my_updated_post_meta', 10, 4);
add_action('added_post_meta', 'my_updated_post_meta', 10, 4);

function my_updated_post_meta($meta_id, $post_id, $meta_key, $meta_value)
{
    // Make sure we are handling just the meta field we are interested in.
    if ($meta_key != 'my_custom_field') return;
    if (wp_is_post_revision($post_id)) return;
    if (get_post_type($post_id) != 'my_post_type') return;
    if (trim($meta_value) == '') return;

    // Do my custom task (linking this post to a parent post in a different
    // post type). This is the same task performed by the save_post action.
    my_link_product_track($post_id, trim($meta_value));
}
Run Code Online (Sandbox Code Playgroud)

从本质上讲,这就是我所做的,并且似乎运行良好。我确实将以上所有内容封装到主题的自定义类中,并且不建议使用此处所示的全局作用域变量,但这只是为了展示该方法。

Xhy*_*ynk 2

你应该看看使用$post->ID而不是$post_id-

$my_field_value = get_post_meta($post->ID, 'my_field', true);
Run Code Online (Sandbox Code Playgroud)

法典中的 get_post_meta

编辑

你能做这样的事吗?

if($post->ID == ''){
    $pid = $post_id;
} else {
    $pid = $post->ID;
}

//$pid = $post->ID or $post_id, whichever contains a value
$my_field_value = get_post_meta($pid, 'my_field', true);
Run Code Online (Sandbox Code Playgroud)

在 $post->ID 和 $post_id 中查找值并使用不为空的值的东西?