douyi6168 2017-05-19 14:28
浏览 146
已采纳

Wordpress save_post钩子有错误的帖子?

I'm getting some odd results saving meta values to my custom post types using the save_post hook. The data is saved to the incorrect post.

If I log the post ID using the code below, i see that the is is not the correct, that is while i edit post 7890, the log entry is 3345 (and thats where the saved data is put)

Have i misunderstood how the save_post hook works? Any help appreciated :)

add_action('save_post','save_data');
function save_data($post_id){
        $file = 'log.txt';
        $copystring = $post_id ."
";
        file_put_contents($file, $copystring, FILE_APPEND | LOCK_EX);
    }

thank you

  • 写回答

2条回答 默认 最新

  • dongyi2993 2017-05-19 15:13
    关注

    Basically you are using it correctly. The $post_id should be the ID of the post to save. Read more here: https://codex.wordpress.org/Plugin_API/Action_Reference/save_post

    However there could be various reasons why you are receiving the wrong post ID here.

    • Saving the post triggers the save process of another post
    • you are receiving some revision ID
    • you are sending wrong ID data from your form
    • maybe others ...

    In the save post hook callback you should check if the post is of the correct post type and that it is not a revision or something.

    $post = get_post($post_id);
    
    if($post->post_type != 'desired-post-type') {
    return;
    }
    
    if(wp_is_post_revision( $post_id ) {
    return;
    }
    

    ... maybe some other checks.

    What is post 3345? Print it to your console and check. Most probably it is of a different post type or you are submitting the wrong ID.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改