當(dāng)前位置:首頁(yè)>WordPress建站>WordPress開(kāi)發(fā)>使用 WP_Error 類(lèi)進(jìn)行 WordPress 錯(cuò)誤處理(二)

使用 WP_Error 類(lèi)進(jìn)行 WordPress 錯(cuò)誤處理(二)

在《使用 WP_Error 類(lèi)進(jìn)行 WordPress 錯(cuò)誤處理》這個(gè)系列的第一篇文章中,我們對(duì) WP_Error 這個(gè)類(lèi)做了一個(gè)介紹,我們通過(guò)代碼示例來(lái)講解了這個(gè)類(lèi)的屬性、方法,以及它的作用和職能。

本文,也是該系列的最后一篇,我們將建立一個(gè)非常簡(jiǎn)單的聯(lián)系表單插件來(lái)演示如何處理插件開(kāi)發(fā)的錯(cuò)誤。這個(gè)聯(lián)系表單插件將有簡(jiǎn)碼和模板標(biāo)簽支持,簡(jiǎn)碼可以直接在文章和頁(yè)面中插入使用,模板標(biāo)簽則可以在主題文件中嵌入。

注:由于時(shí)間精力有限,本教程沒(méi)辦法翻譯分享,希望朋友們可以加入我們,幫助我們進(jìn)行翻譯,有小酬謝,有意者請(qǐng)聯(lián)系倡萌QQ 745722006(注明:教程翻譯)。

以下為原文:http://code.tutsplus.com/tutorials/wordpress-error-handling-with-wp_error-class-ii–cms-21142

In the first part of this series on handling errors in WordPress with the WP_Error class, we took a look at an introduction of the PHP class, we examined the class properties and methods and their roles and functions complemented by code examples.

In this final part of the series, we will be building a fairly simple contact form plugin to demonstrate how to handle errors in plugin development. The contact-form plugin will have shortcode and template tag support so it can be implemented in posts and pages using the former and in a theme using the latter. 

Contact-Form Plugin Development

The contact form will consist of five form fields – four input elements and a textarea element.

contact-form-plugin-agbonghama

I’m sure you are familiar with all the contact-form field. Note that when an email is sent via the contact-form, the phone number get appended to the message. This is evident in the send_mail function.

Let’s get started coding the plugin. First the plugin header:

<?php
/*
 Plugin Name: Contact Form Lite
 Plugin URI: http://code.tutsplus.com
 Description: Easy contact form plugin
 Author: Agbonghama Collins
 Author URI: http://tech4sky.com
 */

The plugin will consist of five PHP functions as outlined below.

  1. contact_html_form() will contain the HTML form code of the plugin.
  2. validate_form() handles the plugin error. we will see error handling using WP_Error in action in this function.
  3. send_mail() handles the sending of email.
  4. contact_form_function() brings together and process the above functions
  5. contact_form_shortcode() is the shortcode callback function.

The HTML form code of the plugin contained in contact_html_form() function  is as follows.

function contact_html_form() {
    global $name, $email, $phone_number, $subject, $message;
     
    echo '<form action="' . get_permalink() . '" method="post">
     
    <label for="name">Name <strong>*</strong></label>
    <input type="text" name="sender_name" value="' . ( isset( $_POST['sender_name'] ) ? $name : null ) . '" />
     
    <div>
    <label for="email">Email <strong>*</strong></label>
    <input type="text" name="sender_email" value="' . ( isset( $_POST['sender_email'] ) ? $email : null ) . '" />
    </div>
     
    <div>
    <label for="phonenumber">Phone Number <strong>*</strong></label>
    <input type="text" name="sender_phonenumber" value="' . ( isset( $_POST['sender_phonenumber'] ) ? $phone_number : null ) . '" />
    </div>
     
    <div>
    <label for="subject">Subject <strong>*</strong></label>
    <input type="text" name="email_subject" value="' . ( isset( $_POST['email_subject'] ) ? $subject : null ) . '" />
    </div>
     
    <div>
    <label for="message">Message <strong>*</strong></label>
    <textarea name="email_message">' . ( isset( $_POST['email_message'] ) ? $message : null ) . '</textarea>
    </div>
     
    <div>
    <input type="submit" name="send_message" value="Send" />
    </div>
    </form>';
}

Next is the error handling function validate_form().

The following are the constraint to be implemented by the plugin which will be enforced by the error handling function.

Note that:

  • no field should be left empty
  • the name field must contain an alphabetic character
  • the email should be valid
  • the phone number should be numeric

The validate_form() function will accept the form fields as it argument so it can validate the form data for errors. Below is the code for the error-handling function that enforces the above plugin constraint fully commented so you’ll easily trace its code

function validate_form( $name, $email, $phone_number, $subject, $message ) {
 
    // Make the WP_Error object global    
    global $form_error;
     
    // instantiate the class
    $form_error = new WP_Error;
     
    // If any field is left empty, add the error message to the error object
    if ( empty( $name ) || empty( $email ) || empty( $phone_number ) || empty( $subject ) || empty( $message ) ) {
        $form_error->add( 'field', 'No field should be left empty' );
    }
     
    // if the name field isn't alphabetic, add the error message
    if ( ! ctype_alpha( $name ) ) {
        $form_error->add( 'invalid_name', 'Invalid name entered' );
    }
     
    // Check if the email is valid
    if ( ! is_email( $email ) ) {
        $form_error->add( 'invalid_email', 'Email is not valid' );
    }
     
    // if phone number isn't numeric, throw an error
    if ( ! is_numeric( $phone_number ) ) {
        $form_error->add( 'phone_number', 'Phone-number is not numbers' );
    }
     
    // if $form_error is WordPress Error, loop through the error object
    // and echo the error
    if ( is_wp_error( $form_error ) ) {
        foreach ( $form_error->get_error_messages() as $error ) {
            echo '<div>';
            echo '<strong>ERROR</strong>:';
            echo $error . '<br/>';
            echo '</div>';
        }
    }
 
}

The send_mail function handles the email sending.

function send_mail( $name, $email, $phone_number, $subject, $message ) {
    global $form_error;
     
    // Ensure WP_Error object ($form_error) contain no error
    if ( 1 > count( $form_error->get_error_messages() ) ) {
             
        // sanitize user form input
        $name           =   sanitize_text_field( $name );
        $email          =   sanitize_email( $email );
        $phone_number   =   esc_attr( $phone_number );
        $subject        =   sanitize_text_field( $subject );
        $message        =   esc_textarea( $message );
         
        // set the variable argument use by the wp_mail
        $message    .=  '\n Phone Number:' . $phone_number;
        $to         =   'admin@tech4sky.com';
        $headers    =   "From: $name <$email>" . "\r\n";
         
        // If email has been process for sending, display a success message 
        if ( wp_mail( $to, $subject, $message, $headers ) ) {
            echo "Thanks for contacting me.";
        }
 
    }
}

Let’s take a look at what’s going on in the send_mail function.

First, the $form_error object is made global so it can be accessed outside the function scope. A check is made to ensure the $form_error object contains no error message. If true, the contact form input is sanitized.

The $to variable stores the email address the message sent via the contact form will be sent to. On a standard contact-form plugin, the variable should contain the WordPress administrator email retrieve from the database or from the plugin settings.
Take note of how the phone number get concatenated to the message.
Finally, the wp_mail function sends the mail. 

The contact_form_function() function processes the function and also serve as the plugin template tag.

function contact_form_function() {
    global $name, $email, $phone_number, $subject, $message;
    if ( isset($_POST['send_message']) ) {
        // Get the form data
        $name           =   $_POST['sender_name'];
        $email          =   $_POST['sender_email'];
        $phone_number   =   $_POST['sender_phonenumber'];
        $subject        =   $_POST['email_subject'];
        $message        =   $_POST['email_message'];
         
        // validate the user form input
        validate_form( $name, $email, $phone_number, $subject, $message );
         
        // send the mail
        send_mail( $name, $email, $phone_number, $subject, $message );
 
    }
     
    // display the contact form
    contact_html_form();
 
}

Remember the contact-form plugin is going to have shortcode support. Below is the shortcode call-back function together with the add_shortcode function that registers the shortcode.

// Register a new shortcode: [cf_contact_form]
add_shortcode('cf_contact_form', 'contact_form_shortcode');
 
// Shortcode callback function
function contact_form_shortcode() {
    ob_start();
    contact_form_function();
    return ob_get_clean();
}

Using The Plugin

Use the shortcode [cf_contact_form] to include the contact-form in a post or page.
To include the contact-form in your theme, use the template tag :

<?php contact_form_function(); ?>

Summary

In this article, we took a look at how to use the WP_Error class to handle errors in plugins. I also showed us a practical use-case on how to handle errors in plugin using the class. You can find the plugin file attached to this article.

Happy Coding!

聲明:本站所有文章,如無(wú)特殊說(shuō)明或標(biāo)注,均為本站原創(chuàng)發(fā)布。任何個(gè)人或組織,在未征得本站同意時(shí),禁止復(fù)制、盜用、采集、發(fā)布本站內(nèi)容到任何網(wǎng)站、書(shū)籍等各類(lèi)媒體平臺(tái)。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進(jìn)行處理。

給TA打賞
共{{data.count}}人
人已打賞
歡迎關(guān)注WordPress大學(xué)公眾號(hào) WPDAXUE
WordPress開(kāi)發(fā)

使用 WP_Error 類(lèi)進(jìn)行 WordPress 錯(cuò)誤處理(一)

2016-6-27 8:57:20

WordPress開(kāi)發(fā)

WordPress 檢查一篇文章是否存在

2016-9-9 9:56:39

0 條回復(fù) A文章作者 M管理員
    暫無(wú)討論,說(shuō)說(shuō)你的看法吧
?
個(gè)人中心
購(gòu)物車(chē)
優(yōu)惠劵
今日簽到
有新私信 私信列表
搜索

韶山市| 类乌齐县| 区。| 达孜县| 深圳市| 伊吾县| 恩平市| 迁西县| 浦北县| 五华县| 敦煌市| 台湾省| 洛扎县| 山阴县| 三都| 新源县| 嘉义县| 满洲里市| 安陆市| 凤凰县| 利津县| 东明县| 浦城县| 镇赉县| 敖汉旗| 盐亭县| 常宁市| 通河县| 论坛| 永德县| 渑池县| 永清县| 惠水县| 怀集县| 镇安县| 永州市| 阳原县| 新龙县| 武胜县| 阿图什市| 龙门县|