如何获取wordpress发布自定义字段值并将其分配给变量?

时间:2014-10-10 06:59:32

标签: php wordpress forms email

我正在创建一个表单,将表单的详细信息发送到我的电子邮箱。

我的自定义字段是:

enter image description here

我的function.php

function getHotel_contact_number() {
    global $wp_query;
    $postid = $wp_query->post->ID;
    $getHotel_contact_number = get_post_meta($postid, 'hotel_contact_number', true);
    $getHotel_contact_number;
}

我的表格是:

<?PHP
$errors = array();
if (isset($_POST["submit"])) {
    $to = "myemail@email.com";
    $subject = "This is my subject";    
    $hotel = get_permalink();
    $hotel_contact_nmbr = getHotel_contact_number();
    $headers = array('From: '.$_POST['sendername'].' <'.$_POST['senderEmail'].'>');
    //Check the name and make sure that it isn't a blank/empty string.
        if(empty($sender)){
            //Blank string, add error to $errors array.        
            $errors['sendername'] = "Please enter your name!";
        }
        if(empty($senderEmail)){
            //Blank string, add error to $errors array.        
            $errors['senderEmail'] = "Please enter your email!";
        }
    $mailBody = "<h3>Hotel Details</h3><br/>
                    $hotel<br/>
                    $hotel_contact_nmbr<br/>"

    $mail_sent = wp_mail( $to, $subject, $mailBody, $headers ); 

}
    if ($mail_sent) { ?>

<h1 style="color: #007f00;">Request sent.</h1>

<?php 
} else {
?>

<form id="" name="" action="<?php echo get_permalink(); ?>" method="post">
    <div class="label-input-wrapper">
        <div class="form-label">Name</div>
        <div class="form-input">
            <input type="text" name="sendername" value="<?PHP if(!empty($errors)) { echo $sender;} ?>" />
            <div class="error-msg">
                <?php if(isset($errors['sendername'])) { echo '<span style="color: red">'.$errors['sendername'].'</span>'; } ?>
            </div>
        </div>
    </div>
    <div class="label-input-wrapper">
        <div class="form-label">E-Mail</div>
        <div class="form-input">
            <input type="email" name="senderEmail" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required value="<?PHP if(!empty($errors)) { echo $senderEmail;} ?>" />
            <div class="error-msg">
                <?php if(isset($errors['senderEmail'])) { echo '<span style="color: red">'.$errors['senderEmail'].'</span>'; } ?>
            </div>  
        </div>
    </div>

    <input type="submit" value="Submit" name="submit">
</form>

<?php
}  
?>

但是当提交表单时,我只得到hotel contact number的空白值。我做错了什么?如何在提交表单时获得正确的自定义归档值?

无论如何,如果我使用隐藏字段,就像我提到here一样,它正常工作: 看看这个问题的底部区域,我提到了隐藏的字段。

1 个答案:

答案 0 :(得分:0)

使用以下代码更改功能:

function getHotel_contact_number() {
   global $wp_query;
   $postid = $wp_query->post->ID;
   $getHotel_contact_number = get_post_meta($postid, 'hotel_contact_number', true);
   return $getHotel_contact_number;
}