通过快捷码使用的Api请求的表单插件

时间:2014-08-14 作者:emjay

我有一个小PHP脚本,带有一个用于注册新闻稿的输入表单。此表单只接受电子邮件地址,然后使用curl进行api调用。

现在,我不想将此表单构建为wordpress的插件。它应该很容易用一个短代码在不同的页面上使用。我已经构建了这个插件。我有一个表单,我可以用短代码显示此表单。但我不知道如何从wordpress中的原始php文件构建函数。我不知道如何将表单发送到自身并处理这些值。此外,我需要使用用于确认用户的get参数。

这是我的原始剧本,我认为我不想做的事情更容易理解:

指数php:

    <?php

    require_once(\'functions.php\');

    // task subscribe

        if(isset($_POST[\'task\'])){
            $task = $_POST[\'task\'];
            if ($task == "subscribe"){
                if(!empty($_POST[\'email\'])){
                    $email      = $_POST[\'email\'];
                    $group      = basic;

                    $data = array(
                        "group"       => $group,
                        "email"       => $email
                    );
                    $response = doCurlRequest($task, $data);
                }
            }
        }

    // task = confirm

        if(isset($_GET[\'task\']) && isset($_GET[\'hash\'])){
            $task = $_GET[\'task\'];
            $hash = $_GET[\'hash\'];

            $data = array("hash" => $hash);  

            $response = doCurlRequest($task, $data);
        }

    // send mail with confirm link

        if(isset($response[\'subscriptions\'][\'0\'])){

            $to = $response[\'email\'];
            $title = "confirm your address";
            $from = "From: Newslettersystem <[email protected]>";
            $text = "
                Please confirm your address: http://domain.tld/index.php?task=confirm&hash=".$response[\'subscriptions\'][\'0\'][\'hash\']."
            ";

            mail($to, $title, $text);

        }

?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
        <title>Newsletter Form Test</title>
    </head>
    <body>
        <h1>Newsletter Form</h1>
        <form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" name="newsletterForm">
            <input type="hidden" name="task" value="subscribe">
            <div>
                <label for="email">E-Mail Adresse *</label>
                <input type="text" name="email" id="email" size="30">
            </div>
            <div>
                <input type="submit" value="absenden">
            </div>
        </form>
    </body>
</html>
功能。php:

function doCurlRequest($task, $data){

    $data_string = json_encode($data);

    // Get cURL resources
    $curl = curl_init();

    // Set some options - we are passing in a useragent too here
    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => \'http://domain.tld/api/emailing/v0.1/\'.$task,
        CURLOPT_USERAGENT => \'Wordpress Form cURL Request\',
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data_string,
        CURLOPT_HTTPHEADER => array(\'Content-Type: application/json\', \'Content-Length:\' . strlen($data_string))                                                                       
    ));

    // Send the request & save response to $resp
    $resp = json_decode(curl_exec($curl), true);

    // Close request to clear up some resources
    curl_close($curl);

    return $resp;

}
好的,这是正在运行的原始脚本。以下是我对wordpress的出发点:

<?php

/**
 * Plugin Name: NewsletterFormConnector
 * Description: Newsletter Form to connect to Newsletter Api
 * Author: emjay
 * Version: 1.0
 */

    function addCustomQueryVars( $vars ){
        $vars[] = "task";
        $vars[] = "hash";
        return $vars;
    }

    add_filter( \'query_vars\', \'addCustomQueryVars\' );

    function createForm(){

        $task = get_query_var( \'task\' );
        $hash = get_query_var( \'hash\' );

        $form  ="";

        $form .= \'<form>\';
        $form .= \'E-Mail: <input type="text" name="email">\';
        $form .= \'</form>\';

        return $form;

    }

    add_shortcode(\'newsletterForm\', \'createForm\');

?>
我希望有人能给我一些提示,我如何用一个短代码插件来实现这一点。短代码应该适用于每个页面,表单被发送到自身以进行api调用。但我还需要有表单的页面响应从url获取参数,以便用户可以确认其地址。

谢谢你的帮助,

埃姆杰

1 个回复
最合适的回答,由SO网友:sakibmoon 整理而成

首先,创建一个函数来处理表单。在shortcode函数中,首先处理表单,然后返回要显示给用户的任何表单/消息。

/**
 * Plugin Name: NewsletterFormConnector
 * Description: Newsletter Form to connect to Newsletter Api
 * Author: emjay
 * Version: 1.0
 */

//Add function file
require_once(plugin_dir_path(__FILE__) . \'functions.php\');

//Add query var
function addCustomQueryVars( $vars ){
    $vars[] = "task";
    $vars[] = "hash";
    return $vars;
}

add_filter( \'query_vars\', \'addCustomQueryVars\' );

//Helper function to get current page url. You can put it in functions.php
//This is needed when sending message as the confirm page link needs to come to this page as well.
function current_page_url() {
    $pageURL = \'http\';
    if( isset($_SERVER["HTTPS"]) ) {
        if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    }
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}
//Shortcode function
function createForm(){
    //first process the form submit or confirm email task
    process();

    //All the task taken care of, now create html form and return it.

    $form  ="";

    $form .= \'<form>\';
    $form .= \'E-Mail: <input type="text" name="email">\';
    $form .= \'</form>\';

    return $form;

}

add_shortcode(\'newsletterForm\', \'createForm\');

function process() {
    //Process post request
    if( isset($_POST[\'task\']) ) {
        ....
        ....
        //I believe you can complete the process of send mail here
        if(isset($response[\'subscriptions\'][\'0\'])){
            ...
            ...
            $text = "
            Please confirm your address: " . current_page_url() . "?task=confirm&hash=".$response[\'subscriptions\'][\'0\'][\'hash\']."
        ";
            //Send mail with wp_mail instead
            wp_mail($to, $title, $text, $from);
        }
        //Return to shortcode function
        return;
    }

    //Get query variables
    $task = get_query_var(\'task\');
    $hash = get_query_var(\'hash\');
    if( !empty($task) && !empty($hash){
        ...
        ...
    }
}

结束

相关推荐

Multisite and plugins options

我需要更多关于get_site_option(), update_site_option() 和add_site_option().在codex中,他们说它与单次安装相同,只是在多站点中,它返回网络范围的选项。好吧,但我对这一点感到困惑:这是否意味着一旦设置了网络范围选项,所有站点的选项都是相同的?还是每个站点都会覆盖它?我的意思是如果我这样做: update_site_option(\'option_group\', \'default_options());// default_options() r