I have added the following code to send attachments using wp_mail() function. The Runcloud server on which the code is hosted is configured with Amazon SES. On that, the attachment is not sent with the mail, the same code runs perfectly on the local environment with Flywheel.
Code-
add_action(
'phpmailer_init', function( $phpmailer ) use ( $connection_data ) {
$phpmailer->IsSMTP();
$phpmailer->Host = smtp.gmail.com;
$phpmailer->Port = 587;
$phpmailer->Username = //username;
$phpmailer->Password = //password;
$phpmailer->SMTPAuth = true;
$phpmailer->SMTPSecure = 'tls';
$phpmailer->Timeout = 30;
}
);
add_filter(
'wp_mail_content_type', function() {
return 'text/html';
}
);
$file = 'https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg';
$file_name = basename( $file );
$file_name = ! strrpos( $file_name, '.' ) ? $file_name . '.txt' : $file_name;
$content = #file_get_contents( trim( $file ) ) ? wp_remote_get( trim( $file ) ) : $file;
file_put_contents( $file_name, $content['body'] );
$attachments[] = $file_name;
$headers[] = 'From: //Name <//email>';
$send_email = wp_mail( wp_get_current_user()->user_email, 'STMP connection validation', 'STMP connection validation.', $headers, $attachments );
You have 2 problems, One is to configure correctly the wp_mail function.
I recommend you to use this plugin and configure it to your needs: https://es.wordpress.org/plugins/easy-wp-smtp/
Another problem is to send the attachment. This thread may help you:
How to send an email with attachment in wordpress?
Related
I'm new in plugin development. I would like to use this simple function in Wordpress to send mail to users. I saw this code in the documentation everything is simple and straight forward but this code returns false. Why ?
require_once explode( 'wp-content', __FILE__ )[0] . 'wp-load.php';
function send_mail() {
$to = 't.testmail#gmail.com';
$subject = 'The subject';
$body = 'The email body content';
$headers = array( 'Content-Type: text/html; charset=UTF-8' );
$send_message = wp_mail( $to, $subject, $body, $headers );
if ( $send_message ) {
echo 'Email was sent';
} else {
echo 'Email sending was aborted';
}
}
send_mail();
According to the documentation (https://developer.wordpress.org/reference/functions/wp_mail/) the mail could not be sent.
Reasons could be many. Have you checked the debug log of WordPress (https://wordpress.org/support/article/debugging-in-wordpress/)?
I'm making an API call using the wp_remote_get method to fetch data from an external source (not a WP site). The API call is working and i'm getting back the response i want which is just a number. Now i want to store this number (the response) as a meta_value in wp_postmeta with the following meta_key (donation_amount) and a specific post_id. The database table already exists. What i have so far is the API Call and the response. I've tried wp_update_post but maybe i am doing something wrong or maybe is not the right approach. Any help would be appreciated.
$url = 'https://developer.mozilla.org/en-US/docs/Web/API/URL_API'; // Not the real url
$response = wp_remote_get( $url );
if( is_wp_error( $response ) ) {
return false;
} else {
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
}
echo $api_response ['theNumber'];
Use WP update_post_meta function. check the below code.
$url = 'https://developer.mozilla.org/en-US/docs/Web/API/URL_API'; // Not the real url
$response = wp_remote_get( $url );
if( is_wp_error( $response ) ) {
return false;
} else {
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
}
$donation_amount = $api_response['theNumber'];
replace $post_id with your post id.
update_post_meta( $post_id, 'donation_amount', $donation_amount );
I am trying to create a plugin with a JSON file to store options data. I want the JSON file data replaced with data submitted from a form in the plugin. I have tried to use file_put_contents, but nothing changes in the JSON file. Please check my code below and tell me where I am getting it wrong.
function save_changes() {
// check when the submit button is clicked
if( isset( $_POST['f-submitted']) ) {
// sanitize form values
$campaign = sanitize_text_field( $_POST["campaign"] );
$api_key = sanitize_text_field( $_POST["api_key"] );
$api_url_s = sanitize_text_field( $_POST["api_url_s"] );
$api_url = sanitize_text_field( $_POST["api_url"] );
$api_msg = sanitize_text_field( $_POST["api-msg"] );
empty($_POST["email"]) ? $email = get_option( 'admin_email' ) : $email = sanitize_email( $_POST["email"] );
$path = plugin_dir_url( __FILE__ ) . 'assets/js/data.JSON';
//wp_delete_file($path);
$jsonString = file_get_contents($path);
$data = json_decode($jsonString, true);
$data["campaign"] = utf8_encode($campaign);
$data["email"] = utf8_encode($email);
$data["apiUrlS"] = utf8_encode($api_url_s);
$data["apiUrl"] = utf8_encode($api_url);
$data["apiKey"] = utf8_encode($api_key);
$data["msg"] = utf8_encode($api_msg);
$j_data = json_encode($data);
try{
file_put_contents($path, $j_data);
echo '<p class="regular-text code" >Setings has been saved</p>';
}catch(exception $e){
echo '<p class="regular-text code" style="color:crimson;">Error: something went wrong</p>';
}
}
}
I've searched seemingly every relevant question on this but I'm stuck, as none of them address the particular case of uploads through XML RPC.
I want to conditionally change the Wordpress file upload directory, only if the file is coming in through an XML RPC call and only if the call is coming in from a particular user.
My approach is based on a combination of this Answer, this Answer and the Codex.
Here's what I tried with no luck:
add_filter( 'xmlrpc_methods', 'call_intercept1' );
function call_intercept1( $methods ) {
$methods[ 'metaWeblog.newMediaObject' ] = 'custom_upload1';
return $methods;}
function custom_upload1( $args ) {
global $wpdb;
$username = $this->escape( $args[1] );
$password = $this->escape( $args[2] );
$data = $args[3];
$name = sanitize_file_name( $data['name'] );
$type = $data['type'];
$bits = $data['bits'];
if ( !$user = $this->login($username, $password) )
return $this->error;
if ( $username = "XXX" ) {
add_filter('upload_dir', 'custom_upload_dir1');
}
$upload = wp_upload_bits($name, null, $bits);
if ( ! empty($upload['error']) ) {
/* translators: 1: file name, 2: error message */
$errorString = sprintf( __( 'Could not write file %1$s (%2$s).' ), $name, $upload['error'] );
return new IXR_Error( 500, $errorString );
}
return $upload;
}
function custom_upload_dir1( $param ){
$custom_dir = '/the-desired-directory';
$param['path'] = $param['path'] . $custom_dir;
$param['url'] = $param['url'] . $custom_dir;
error_log("path={$param['path']}");
error_log("url={$param['url']}");
error_log("subdir={$param['subdir']}");
error_log("basedir={$param['basedir']}");
error_log("baseurl={$param['baseurl']}");
error_log("error={$param['error']}");
return $param;
}
The file is being uploaded correctly, but the conditional directory change isn't happening.
Does someone know why that would be?
I was able to get this worked out, essentially using Ulf B's Custom Upload Dir as a model and simplifying it from there.
For anyone else facing the same problem, here's what works:
// XMLRPC Conditional Upload Directory
add_action('xmlrpc_call', 'redirect_xmlrpc_call');
function redirect_xmlrpc_call($call){
if($call !== 'metaWeblog.newMediaObject'){return;}
global $wp_xmlrpc_server;
$username = $wp_xmlrpc_server->message->params[1];
$data = $wp_xmlrpc_server->message->params[3];
if($username !== "XXX"){return;}
else {custom_pre_upload($data);}}
function custom_pre_upload($data){
add_filter('upload_dir', 'custom_upload_dir');
return $data;}
function custom_post_upload($fileinfo){
remove_filter('upload_dir', 'custom_upload_dir');
return $fileinfo;}
function custom_upload_dir($path){
if(!empty($path['error'])) { return $path; } //error; do nothing.
$customdir = '/' . 'your-directory-name';
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;}
I want to upload a file from external URL to the WordPress Media Library (that is common to ALL POSTS/PAGES). The return value I want to get is attachment ID in order to inject them into a shortcode (e.g. img).
I tried using IMEDIA_HANDLE_SIDELOAD but I got lost with $_FILES settings.
However, I am not sure about the parameters:
Is this the right function?
where in the code (aFile) should I place the URL I want to download from?
What is the "tmp_name" and "name"?
See my code:
// my params
$post_id = 0; // is this what makes it common to all posts/pages?
$url = 'www.some_external_url.com/blabla.png';
// example from some forum
$filepath = '/relative/path/to/file.jpg';
$wp_filetype = wp_check_filetype( basename( $filepath ), null );
$aFile["name"] = basename( $filepath );
$aFile["type"] = $wp_filetype;
$afile["tmp_name"] = $filepath;
$attach_id = $media_handle_sideload( $aFile, $post_id, 'sometitle' );
Solution:
private function _uploadImageToMediaLibrary($postID, $url, $alt = "blabla") {
require_once("../sites/$this->_wpFolder/wp-load.php");
require_once("../sites/$this->_wpFolder/wp-admin/includes/image.php");
require_once("../sites/$this->_wpFolder/wp-admin/includes/file.php");
require_once("../sites/$this->_wpFolder/wp-admin/includes/media.php");
$tmp = download_url( $url );
$desc = $alt;
$file_array = array();
// Set variables for storage
// fix file filename for query strings
preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
#unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}
// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $postID, $desc);
// If error storing permanently, unlink
if ( is_wp_error($id) ) {
#unlink($file_array['tmp_name']);
return $id;
}
return $id;
}