dongluo3331
2017-04-12 17:18
浏览 52
已采纳

获取钩子的当前页面ID

I use a hook from the plugin Formidable Pro (frm_to_email) where I absolutely need to have the ID of the current page (for Advanced Custom Fields). As the code is located in function.php, it seems impossible for me to retrieve it. What can I do to get this value?

function custom_set_email_value($recipients, $values, $form_id, $args){
    global $post;
    $profil_obj = get_field('profil_obj', $post->ID); // If I put the ID directly (10 for example), it works

    if( $form_id == get_field('popup_form_id', 'option') && $args['email_key'] == get_field('popup_email_id', 'option') ){
        if($profil_obj) {
            foreach( $profil_obj as $post) {
                setup_postdata($post);
                $recipients[] = get_field('profil_email', $post->ID);
            }
        }
        wp_reset_postdata();
    }
    return $recipients;
}
add_filter('frm_to_email', 'custom_set_email_value', 10, 4);
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongyin0628 2017-04-12 23:07
    已采纳

    You should be able to get the post ID at that stage from the URL, with url_to_postid():

    <?php
    $scheme  = (!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] === "off") ? "http" : "https";
    $url     = "$scheme://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $post_id = url_to_postid( $url );
    
    打赏 评论
  • duanou1904 2017-04-12 17:59

    Have you tried either of these methods:

    global $post;
    echo $post->ID;
    

    or

    global $wp_query;
    echo $wp_query->post->ID;
    

    Alternatively, if you know the ID of the page you are using the form on, you could add the page id as a hidden form field value. So, if for example, you had 2 pages on which the form appears, you create two identical forms but with a hidden field that has a value equivalent to the id of the page the given form will appear on.

    打赏 评论
  • dounan4479 2017-04-12 18:00

    You have to add global $post to your function.

    function custom_set_email_value($recipients, $values, $form_id, $args){
        global $post;
        $profil_obj = get_field('profil_obj', $post->ID); // If I put the ID directly (10 for example), it works
    
        if( $form_id == get_field('popup_form_id', 'option') && $args['email_key'] == get_field('popup_email_id', 'option') ){
            if($profil_obj) {
                foreach( $profil_obj as $post) {
                    setup_postdata($post);
                    $recipients[] = get_field('profil_email', $post->ID);
                }
            }
            wp_reset_postdata();
        }
        return $recipients;
    }
    add_filter('frm_to_email', 'custom_set_email_value', 10, 4);
    
    打赏 评论

相关推荐 更多相似问题