简体   繁体   English

用于联系表的Wordpress插件开发

[英]Wordpress Plugin development for Contact Form

I am developing a simple WordPress plugin for contact form. 我正在为联系表格开发一个简单的WordPress插件。 But I don't know how to save the information in database? 但是我不知道如何将信息保存在数据库中? Could you gives some references? 您能提供一些参考吗?

The answer by Haninder has a great start but doesn't store the data in a database as per the OP. Haninder的答案是一个很好的开始,但没有按照OP将数据存储在数据库中。

This is where it starts getting tricky, as there are many options. 这是开始变得棘手的地方,因为有很多选择。

You can easily store the data in various places, but none are semantically correct, or maintainable over a long period of time. 您可以轻松地将数据存储在各个位置,但是从语义上讲,没有一个是正确的,也不能长期维护。

In a single option in the options table 在选项表中的一个选项中

function save_request( $data ){ 

    $opts = get_option( 'contact_requests' );

    if( ! $opts || ! is_array( $opts ) ){
         $opts = array();
    }

    $opts[] = $data;

   update_option( 'contact_requests', $opts );

}

This would mean a slow request to save and defeats the point of a database in the first place, after several hundred contact requests, also diaplying and sorting the data would get tricky. 首先,这将意味着缓慢的保存请求,并且在数百次联系请求之后,首先破坏数据库的位置,而且对数据进行分散和排序将变得棘手。

The best way would really to have a custom database table but there is a lot to consider when going down this path. 最好的方法实际上是拥有一个自定义数据库表,但是沿此路径进行操作时要考虑很多因素。

https://code.tutsplus.com/tutorials/custom-database-tables-creating-the-table--wp-28124 https://code.tutsplus.com/tutorials/custom-database-tables-creating-the-table--wp-28124

Custom Post Type 自定义帖子类型

This is how I would approach this problem. 这就是我解决这个问题的方法。

perhaps you could create a custom post type, say "contact_requests" and create a post with some post meta to represent a contact request. 也许您可以创建一个自定义帖子类型,例如“ contact_requests”,然后创建带有一些帖子元的帖子来表示联系人请求。

This way you already get a neat list in admin, and can sort and access the data quickly and easily as required. 这样,您已经在admin中获得了一个整洁的列表,并且可以根据需要快速轻松地对数据进行排序和访问。 This would be stable and fast through hundreds of thousands of entries. 通过成千上万的条目,这将是稳定且快速的。

function save_request( $data ){

    $content = '';

    foreach( $data as $key => $name ){
        $content .= sprintf( '%s - %s' . PHP_EOL, $key, $name );
    }

    $post_data = array(
        'post_title'   => 'Contact Request ' . esc_html( $data['name'] ),
        'post_content' => $content,
        'post_type'    => 'contact_requests'
    );
    $post_id = wp_insert_post( $post_data );

    //Add Post Meta Here
    add_post_meta( $post_id, 'contact_name', esc_html( $data['name'] ) );
    add_post_meta( $post_id, 'contact_email', esc_html( $data['email'] ) );
    add_post_meta( $post_id, 'contact_message', esc_html( $data['message'] ) );

    return $post_id;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM