How to conditionally add function to completed order when custom field to order_id is set in woocommerce - email

I try to add a function to the completed order email in woocommerce if a specific custom field is set.
I am certain the custom field is attached to the order, as i can output it on the admin order page.
so far i have:
function test(){
global $woocommerce, $post;
$check = get_post_meta( $order->ID, '_digital', TRUE);
if (!empty($check)){
function order_completed_email_add_cc_bcc( $headers, $email_id, $order ) {
if ( 'customer_completed_order' == $email_id ) {
$headers .= "Bcc: admin <admin#example.com>" . "\r\n";
}
return $headers;
}
add_filter( 'woocommerce_email_headers', 'order_completed_email_add_cc_bcc', 9999, 3 );
}
}
However, this doesn't work...

Ok i found it.
function order_completed_email_add_cc_bcc( $headers, $email_id, $order ) {
$check = $order->get_meta('_digital',true);
if ( 'customer_completed_order' == $email_id && !empty($check)) {
$headers .= "Bcc: admin <admin#example.com>" . "\r\n";
}
return $headers;
}
add_filter( 'woocommerce_email_headers', 'order_completed_email_add_cc_bcc', 9999, 3 );

Related

Gravity Forms - Get a Date value and adjust it, make it into a merge tag

So what I want to be able to do is take a field value, a date field, and add a set period of time to it and then make that into a merge tag that I can then add back into that value or use else where.
I know how to make a new merge tag, that's not the issue. My question is how do I get a field value to use in that calculation?
add_filter( 'gform_replace_merge_tags', 'new_date_plus_30', 10, 7 );
function new_date_plus_30( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
$merge_tag = '{date_plus_30}';
$new_date = date('m/d/Y', strtotime('+30 days'));
return str_replace( $merge_tag, $new_date, $text );
}
So where I do the new date calculation, I need to be able to pull in a field from that post and use it.
I was also thinking of doing a If / Else script where I would do the date calculation based on what was set in a form. So if a user said repeat this every 15 days, I would have something like:
add_filter( 'gform_replace_merge_tags', 'new_date_plus_30', 10, 7 );
function new_date_plus_30( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
if ( $form_id == 34 && $field_id == 2 && $value == 'add 30 days') {
$merge_tag = '{date_plus_30}';
$new_date = date('m/d/Y', strtotime('+30 days'));
}
else if ( $form_id == 34 && $field_id == 2 && $value == 'first of month') {
$merge_tag = '{first_of_month}';
$new_date = date('m/d/Y', strtotime('first of next month'));
}
}
return str_replace( $merge_tag, $new_date, $text );
}
But my issue is still the same. How can I use two filters at the same time? I assume I need to use the gform_get_input_value. Kindly review my code and give feedback is there other way?
Or maybe something like this...
add_filter( 'gform_merge_tag_filter', function ( $value, $merge_tag, $options, $field, $raw_value ) {
if ( $field->id == '2' && $value == 'first of the month') {
$merge_tag = '{the_next_date}';
$thedatetochange = 'Not sure how to get the date value here...';
$value = date('m/d/Y', strtotime($thedatetochange . 'first of the next month'));
return $value;
}
else if ( $field->id == '2' && $value == 'the 15th') {
$merge_tag = '{the_next_date}';
$thedatetochange = 'Not sure how to get the date value here...';
$the_first_date = date('m/d/Y', strtotime($thedatetochange . 'first of the next month' ));
$value = date('m/d/Y', strtotime($the_first_date . '+15 days' ));
return $value;
}
}, 10, 5 );
So after doing more digging, would I be able to use something like this to get the value of the field?
$theDateToChange = rgar( $entry, ‘3’);
This assumes that the field 3 is a date value. Would this work for retrieving the current entry date?
The $entry is passed through the gform_replace_merge_tags filter. You can fetch any field value from the $entry by its field ID. For example, if your field ID was 1:
$value = $entry[1];
Alternately, if you're open to capturing this modified date as a secondary Date field in your form, we have a snippet that can handle the functionality for you.
https://gravitywiz.com/populate-dates-gravity-form-fields/
new GW_Populate_Date( array(
'form_id' => 1,
'target_field_id' => 2,
'modifier' => '+30 days'
) );
So here is my current working code...
add_action( 'gform_admin_pre_render', 'add_merge_tags' );
function add_merge_tags( $form ) {
?>
<script type="text/javascript">
gform.addFilter('gform_merge_tags', 'add_merge_tags');
function add_merge_tags(mergeTags, elementId, hideAllFields, excludeFieldTypes, isPrepop, option){
mergeTags["custom"].tags.push({ tag: '{the_next_date}', label: 'The Next Date' });
return mergeTags;
}
</script>
<?php
//return the form object from the php hook
return $form;
}
add_action('wp', 'add_merge_tags');
/** MY MERGE TAGS HERE */
add_filter( 'gform_replace_merge_tags', 'new_date', 10, 7 );
function new_date( $value, $merge_tag, $options, $field, $raw_value, $entry, $text, $form, $url_encode, $esc_html, $nl2br, $format ) {
$pmoptions = $entry[7];
if ( $pmoptions == 'Monthly') {
$merge_tag = '{the_next_date}';
$old_date = $entry[2];
$new_date = date('m/d/Y', strtotime( $old_date . '+1 month'));
return str_replace( $merge_tag, $new_date, $text );
}
else if ( $pmoptions == 'Quarterly') {
$merge_tag = '{the_next_date}';
$old_date = $entry[2];
$new_date = date('m/d/Y', strtotime( $old_date . '+3 month'));
return str_replace($merge_tag, $new_date, $text);
}
}
apply_filters( 'gform_replace_merge_tags', $value, $merge_tag, $options, $field, $raw_value, $entry, $text, $form, $url_encode, $esc_html, $nl2br, $format );

Newbie on Fb messenger Sender_action function

I am under a learning process in chatbot, and kinda new to coding overall ( learning by doing right? )
Trying to execute a messenger function so our chatbot gets the little "writing" bubble for x amount of time before it sends a template. = sender_action_typing_on.
I have tried sleep, await, wait, and so on but the code doesn´t seem to be executed, but the template still shows after the time I chose.
The json is also correct by the documentation from Facebook, and if it get´s executed alone it runs for 20 sek before a timeout.
Code:
if ( $response == "")
{
$jsonData = '{"recipient":{"id":"' . $sender . '"},"message":{"text":"' . $message_to_reply.'"}}';
$jsonDataEncoded = $jsonData;
}
else
if ( $response == "123456")
{
$sender_action_typing_on = '{
"recipient":{
"id":"<PSID>"
},
"sender_action":"Typing_on"
}';
$sender_action_typing_on = str_replace("<PSID>", $sender, $sender_action_typing_on);
$jsonDataEncoded = $sender_action_typing_on;
$velkommenTemplateJSON = str_replace("<PSID>", $sender, $velkommenTemplateJSON);
$jsonDataEncoded = $velkommenTemplateJSON;
}
I have now fixed this issue, this may be very self-explaining for many but for the "lost soul" looking for answers u can see the way i dealed with the problem here:
First i created a new function:
function sendToMessenger($access_token, $sender, $sender_actiontemplateJSON)
{
$content = str_replace("<PSID>", $sender, $sender_actiontemplateJSON);
$opts = array(
'http'=>array(
'method'=>"POST",
'header' => "Content-Type: application/json",
'content' => $content
)
);
$context = stream_context_create($opts);
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=' . $access_token;
// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
return $file;
Then i rearranged the way i´m sending template since the template got sent at det end of my code "Sender_action" would always be overwritten, Now with the "SendToMessenger" Function it gets sent right away.
else
if ( $response == "123456")
{
sendToMessenger($access_token, $sender, $sender_actiontemplateJSON);
sleep(1);
sendToMessenger($access_token, $sender, $velkommenTemplateJSON);
}
Now it works like a charm!

How to get order id in Woocomerce Email

I try to get the order id when adding extra content in woocommerce email, is anyone knows what goes wrong with this...?
Thanks
add_action( 'woocommerce_email_after_order_table', 'add_content', 20 );
function add_content() {
global $woocommerce;
echo $order_id
echo $order->id;
}
you can pass the parameter $order and get $order->get_id();
something like this:
function add_content( $order ) {
echo $order->get_id();
}
Look in the source, $order is the first variable passed to the woocommerce_email_after_order_table hook.
add_action( 'woocommerce_email_after_order_table', 'so_43612005_add_content', 20, 4 );
function so_43612005_add_content( $order, $sent_to_admin, $plain_text, $email ) {
// WooCommerce 3.0
if( method_exists( $order, 'get_id' ) ) {
$order_id = $order->get_id();
// WooCommerce 2.6.x
} else {
$order_id = $order->id;
}
echo $order_id;
}
add_action( 'woocommerce_email_after_order_table', 'wdm_add_shipping_method_to_order_email', 10, 2 );
function wdm_add_shipping_method_to_order_email( $order, $is_admin_email ) {
echo '<p><h4>Order Id:</h4> ' . $order->get_order_number() . '</p>';
}

How do I attach a pdf file to a Gravity Forms Notification?

Gravity forms offers a way to attach files from the file uploader (See code below), but how would I change this code to simply attach my own PDF file from either a hidden field value or simply paste the pdf file within this code? I tried a few things but it didn't work. Any help would be appreciated!
add_filter( 'gform_notification', 'change_user_notification_attachments', 10, 3 );
function change_user_notification_attachments( $notification, $form, $entry ) {
//There is no concept of user notifications anymore, so we will need to target notifications based on other criteria, such as name
if ( $notification['name'] == 'User Notification' ) {
$fileupload_fields = GFCommon::get_fields_by_type( $form, array( 'fileupload' ) );
if(!is_array($fileupload_fields))
return $notification;
$attachments = array();
$upload_root = RGFormsModel::get_upload_root();
foreach( $fileupload_fields as $field ) {
$url = $entry[ $field['id'] ];
$attachment = preg_replace( '|^(.*?)/gravity_forms/|', $upload_root, $url );
if ( $attachment ) {
$attachments[] = $attachment;
}
}
$notification['attachments'] = $attachments;
}
return $notification;
}
Based on that code, something like this should work. Replace the $url value with the URL to your PDF.
add_filter( 'gform_notification', 'change_user_notification_attachments', 10, 3 );
function change_user_notification_attachments( $notification, $form, $entry ) {
if ( $notification['name'] == 'User Notification' ) {
$url = 'http://yoursite.com/path/to/file.pdf';
$notification['attachments'][] = $url;
}
return $notification;
}

Redisplaying a form with fields filled in

I need a bit of help with redisplaying a form.
Basically, currently a user will fill out my contact form, the form and it's contents are passed to my verification page, and if the recaptcha was entered correctly it goes to a Thank You page.
When the recaptcha is entered INCORRECTLY, I want to redisplay the contact form with the fields already filled out. How do I do this? (As you'll see below, it currently goes to google on incorrect captcha)
Here is my verification code. Any help would be great:
<?php require('sbsquared.class.php'); ?>
<?php
require_once('recaptchalib.php');
$privatekey = "myprivatekey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
header("Location: http://www.google.com"); <--- this is the bit that I want to redisplay the form with fields already filled out.
} else {
$sb = New SBSquared;
$name = $_POST['FullName'];
$post_keys = array_keys($_POST);
$my_db_string = "<table>";
$ip_address = $_SERVER['REMOTE_ADDR'];
foreach($post_keys as $field)
{
if($_POST[$field] != "" && $field != "submit_y" && $field != "submit_x" && $field != "submit_x")
{
$my_db_string .= "<tr><td><b>".$field.":</b></td><td>";
if($field == "Email")
{
$my_db_string .= ''.$_POST['Email'].'';
}
else
{
$my_db_string .= $_POST[$field];
}
$my_db_string .= "</td></tr>";
}
}
$my_db_string .= "<tr><td><b>IP ADDRESS LOGGED: </b></td><td>".$ip_address."</td></tr>";
$my_db_string .= "</table>";
if(get_magic_quotes_gpc() != 1)
{
$my_db_string = addslashes($my_db_string);
$name = addslashes($name);
}
$conn = $sb->openConnection();
$dts = time();
$sql = "INSERT INTO `contact_queries` VALUES ('', '$name', '$my_db_string', 'n/a', 0, $dts)";
$result = mysql_query($sql, $conn) or die(mysql_error());
$content = '<div id="main_middle">';
$content .= '<span class="title">'.$sb->dt('Contact').'</span>
<p>'.$sb->dt('Thank you for your enquiry. We will contact you shortly.').'</p>
</div>';
// admin auto email.
$dts = date("d.m.y h:ia", time());
$admin_content = "New contact query at $dts";
$admin_content .= "\n\n--\n\n \r\n\r\n";
mail("email address", 'NOTIFICATION: new query', $admin_content, 'From: email address');
$FILE=fopen("./log/auto-contact.txt","a");
fwrite($FILE, $admin_content);
fclose($FILE);
echo pageHeader($sb);
echo pageContent($sb, $content);
echo pageFooter($sb);
}
?>
You probably already answered this for yourself, but if not you can set ReCaptcha to validate prior to submitting the form, much the same as HTML5 validation. It just won't let the user submit until the Captcha is correct. Now, I don't know if it will refresh the captcha if it is incorrect but most of the time I see people putting it into an iFrame so it doesn't refresh the page when refreshing the captcha.
As an alternative, you can use sessions to keep the data filled in.