简体   繁体   中英

Wordpress - Function parameters not passing in

I am trying to write a function that emails my users after I publish a new post. Here is what I have so far:

require_once('db.php');

$sql="SELECT email FROM table";

$result = sqlsrv_query($sqlsrvconnection, $sql);

$emailList="";

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
    $emailList.=", ".$row['email'];
}

add_action('save_post', 'email_members');

function email_members( $post_id, $emailList )  {

    if ( !wp_is_post_revision( $post_id ) ) {

        $to      = 'example@test.com';
        $subject = 'the subject';
        $message = "email list consists of: ".$emailList;
        $headers = 'From: webmaster@example.com' . "\r\n" .
            'Reply-To: webmaster@example.com' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

        mail($to, $subject, $message, $headers);

}

}

In my function I have tried to pass in the $emailList variable, but I am not able to do anything with it. Am I passing it in wrong? Is this not allowed when hooking into another wp action?

I figured out that my function is called somewhere else (with the save_post action). Because of this, the function didn't have access to the $emailList variable. I moved everything (except for the add_action()) inside the function and everything worked great!

add_action('save_post', 'email_members');

function email_members( $post_id, $emailList )  {

    require_once('db.php');

    $sql ="SELECT email FROM table";

    $result = sqlsrv_query($sqlsrvconnection, $sql);

    $emailList="";

    while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
        $emailList.=", ".$row['email'];
    }

    if ( !wp_is_post_revision( $post_id ) ) {

        $to      = 'example@test.com';
        $subject = 'the subject';
        $message = "email list consists of: ".$emailList;
        $headers = 'From: webmaster@example.com' . "\r\n" .
            'Reply-To: webmaster@example.com' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

        mail($to, $subject, $message, $headers);

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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