Search code examples
phpwordpressphpmailer

How to echo the contents of a function in PHP


I am using WP mail to send out an email. I have 2 different versions of hte email that I wish to send based on a particular value. The code below is self expalnitory.

function implement_ajax_apartmentsearchemail() {



    if ( ($_POST['email']) ) {
        //get the correct page ID
        $to = ($_POST['email']);
        $name = ($_POST['name']);
        $subject = 'Our Recommendations.';
        $postidstring = ($_POST['postidstring']);   
        $reseller = ($_POST['reseller']);   

        if ($reseller == '') {
            $message = emailcontentscp($postidstring, $name);
        } else {
            $message = emailcontentreseller($postidstring, $reseller, $name);
        }            

        $subject = 'Our Recommendations';
        $headers = "Content-type: text/html;charset=UTF-8\n";
        $headers .= "X-Priority: 3\n";
        $headers .= "X-MSMail-Priority: Normal\n";
        $headers .= "X-Mailer: php\n";
        $headers .= "From: Serviced City Pads  <[email protected]>\n";    
        wp_mail( $to, $subject, $message, $headers);   

        die();
    }


}   

add_action('wp_ajax_apartmentsearchemail', 'implement_ajax_apartmentsearchemail');
add_action('wp_ajax_nopriv_apartmentsearchemail', 'implement_ajax_apartmentsearchemail');

I am trying to check if the $reseller variable is true or not, if it is then run the reseller mail template and if not, then run the normal SCP mail template.

My condition works to the point where I am returning the correct email template in the console however, when I dump the $message variable it comes back with nothing.

My functions are laid out as follows in different files.

function emailcontentscp($postidstring, $name) {
 //wp query to get some posts in a nice looking layout

 //loop start
     <div id="post-entry">some content</div>
 //loop end resetpostdata();

 //there is no return() here.  
}

Solution

  • In order to get the return value of a function and assigning it to $message, the function needs to return something. Instead of outputting the HTML, store it in a variable and return it:

    function emailcontentscp($postidstring, $name) {
        $template = '<div ...>';
    
        foreach (...) {
            $template .= '<li ...>';
        }
    
        return $template;
    }