5

我正在使用 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
    // ...
}

通过管理页面更新帖子时,这可以正常工作。但是,第一次创建帖子时,my_field_value始终为空。该字段确实正确保存,但此操作触发器似乎无法看到它,也没有任何其他自定义字段值。

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

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


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

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

updated_post_meta我的解决方案是使用和added_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));
}

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

4

1 回答 1

2

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

$my_field_value = get_post_meta($post->ID, 'my_field', true);

法典中的 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);

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

于 2012-10-09T22:53:16.703 回答