【问题标题】:get submitted form's post_id from outside the loop PHP从循环PHP外部获取提交表单的post_id
【发布时间】:2018-09-27 18:40:37
【问题描述】:

我正在开发一个应用程序,该应用程序有一个帖子表单,可以将收养导师与受指导者进行匹配。 这是在 Wordpress/PHP/MySQL/ACF(高级自定义字段)中。

提交表单后,我无法获取该帖子的 post_id,因此我可以保存列出所有匹配项的屏幕的 ACF 字段“标题”。

当我处于“循环之外”时,是否需要检索该表单的$post_id?我该怎么做?

function match_post_title_auto( $post_id ) {

    // get mentor & new mentee user array
    $mentee = get_field('match_mentee', $post_id);
    $mentor = get_field('match_mentor', $post_id);

    $title = ' Mentor: ' . $mentor['display_name'] . ' and Mentee: ' . $mentee['display_name']; 

    $postdata = array(
         'ID'          => $post_id,
         'post_title'  => $title,
         'post_type'   => 'match'
    );

    wp_update_post( $postdata );
    return $value;
}

var_dump($post_id);  //returns NULL

//what do I put here to get that `post_id`? Thanks!

add_action('acf/save_post', 'match_post_title_auto', 10, 1);

【问题讨论】:

  • 不清楚您要做什么。你说的是什么形式?照原样,您的函数看起来会在保存时更改任何具有自定义字段的帖子的标题,但听起来这不是您想要做的。此外,当过滤器只接受一个 $post_id 时,您将三个参数传递给您的函数
  • 您的“var_dump($post_id);//returns NULL”预计无法正常工作。您正在函数范围之外访问 $post_id 。打开一个 wordpress 调试选项codex.wordpress.org/Debugging_in_WordPress 并使用 error_log() 对函数 match_post_title_auto 中的代码进行故障排除。

标签: php wordpress forms advanced-custom-fields


【解决方案1】:

acf/save_post 挂钩仅将 $post_id 作为单个参数传递。您的回调中有 3 个参数。 https://www.advancedcustomfields.com/resources/acf-save_post/。此外,您需要具有高于 10 的优先级才能从您的帖子中获取 更新的值。

function match_post_title_auto( $post_id ) {
    // do stuff
}
add_filter('acf/save_post', 'match_post_title_auto', 20 );

【讨论】:

  • 谢谢大家,你们帮了大忙。我会消化和测试这个并回复你。
  • 这对理解问题有很大帮助。一旦一切配置正确,它就能找到 post_id。我将其设置为: add_action('acf/save_post', 'match_post_title_auto', 20);然而,我对 update_field() 在某些情况下写入数据库的延迟感到困惑。有没有一种设置可以更快地发生这种情况?或者可能是由于某种缓存问题?我找不到太多关于优先级设置的文档。
【解决方案2】:

您正试图通过过滤器挂钩捕获值。实际上你只需要动作钩子和 1 个参数。像这样:

add_action('acf/save_post', 'match_post_title_auto', 10, 1);

希望它会起作用。

有关更多信息,请查看标准文档:
https://www.advancedcustomfields.com/resources/acf-save_post/

【讨论】:

  • add_action 调用add_filter,所以应该没关系。
  • 是的,有时这是正确的。但在这种情况下,也需要触发 apply_filters 钩子。当他们在文档中说的时候。也就是说,它应该通过 add_action 调用,这意味着您需要通过这种方式调用它。所以基本上他们最终会触发 do_action 钩子。在这里查看这些钩子的简要说明 - wpsmith.net/2011/…
猜你喜欢
  • 1970-01-01
  • 2017-07-06
  • 2013-01-23
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多