Running PHP cron job in new hook created in theme function.php - php

I created a hook in function.php in wordpress that I want to run every minute, and added the function in the hook with PHP code. At the same time, I use the WP-Control plugin to try to make this hook run every minute.
But when I set up the cron job in the plug-in, I found that even if the hook is run every minute, the function still does not work properly. I am a little confused about the reason of the function running.
Here is my php code:
// add autocheck function into a hook to get WP-Control
add_action( 'autocheck_run_every_minute', 'run_autocheck_every_minute' );
function run_autocheck_every_minute() {
// add autocheck.php function in custom-auction into this method
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
$args = array(
'post_type' => 'product',
'posts_per_page' => 1,
'orderby' => 'ID',
'order' => 'ASC',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
),
array(
'key' => '_auction_has_started',
'value' => '1',
'compare' => '=',
),
array(
'key' => '_auction_current_bid',
'value' => '',
'compare' => '!=',
),
array(
'key' => '_auction_current_bider',
'value' => '',
'compare' => '!=',
),
array(
'key' => '_reserved_option',
//'value' => '',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_auction_dates_to',
'value' => date( "Y-m-d H:i" ),
'compare' => '<', // '>' auction still fresh, '<' auction ended!
),
),
);
//echo "1<br>";
//print_r($args);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
//$product_id = '7771';
//$product = wc_get_product($product_id);
if ($product->get_type() !== "auction"){
return;
}
$product_id = $product->get_id();
//echo $product_id;
$user_id = get_post_meta($product_id, '_auction_current_bider', true);
$auction_id = $product_id;
$product_name = $product->get_name();
$current_bid = $product->get_curent_bid();
$reserve = get_post_meta($product_id, '_auction_reserved_price', true);
$reserved_option = get_post_meta($product_id, '_reserved_option', true);
if ((!isset($reserve)) || ($reserve == "") || (empty($reserve))){
$reserve == 0;
}
$vendor_id = get_post( $auction_id )->post_author;
//echo $vendor_id;
$vendor = new WP_User( $vendor_id );
//print_r($vendor);
$vendor_recipient = $vendor->user_email;
//$vendor_name = $vendor->first_name." ".$vendor->last_name;
$vendor_name = $vendor->display_name;
$customer = new WC_Customer( $user_id );
$customer_recipient = $customer->get_email();
//print_r($customer);
//if ((!isset($reserved_option)) || ($reserved_option == "") || (empty($reserved_option))){
if ($reserve <= $current_bid){
//touch reserved price
//echo $reserve - $current_bid;
$data = array();
$data['billing_first_name'] = $customer->get_billing_first_name();
$data['billing_last_name']= $customer->get_billing_last_name();
$data['billing_company']= $customer->get_billing_company();
$data['billing_address_1']= $customer->get_billing_address_1();
$data['billing_address_2']= $customer->get_billing_address_2();
$data['billing_city']= $customer->get_billing_city();
$data['billing_state']= $customer->get_billing_state();
$data['billing_postcode']= $customer->get_billing_postcode();
$data['billing_country']= $customer->get_billing_country();
$data['billing_email']= $customer->get_email();
$data['billing_phone']= get_user_meta( $user_id, 'billing_phone', true );
//print_r($data);
//echo $product['name'] = $product->get_name();
//print_r($product->get_tax_class());
$taxes = WC_Tax::get_rates( $product->get_tax_class());
$tota_tax_rate = 0;
foreach($taxes as $tax){
$tota_tax_rate = $tota_tax_rate + $tax['rate'];
$tax_label = $tax['label'];
}
$data['taxes'] = $taxes;
$data['product'][$product_id]['stock_status'] = $product->get_stock_status();
$data['product'][$product_id]['price'] = $product->get_curent_bid();
$data['product'][$product_id]['name'] = $product->get_name();
$data['product'][$product_id]['type'] = $product->get_type();
$data['product'][$product_id]['total_tax_rate'] = $tota_tax_rate;
$data['product'][$product_id]['taxes'] = $taxes;
$data['product'][$product_id]['sub'] = $sub = $product->get_curent_bid();
$data['product'][$product_id]['sub_tax'] = $product_tax = round($product->get_curent_bid() * ($tota_tax_rate / 100), 2);
$data['product'][$product_id]['sub_total'] = $subtotal = $product->get_curent_bid() + $product_tax;
$data['product'][$product_id]['tax_class'] = $product->get_tax_class();
//service fee:
$service_fee = get_service_fee($user_id, $product_id, $product->get_curent_bid());
$service_fee_tax = round($service_fee * ($tota_tax_rate / 100), 2);
$service_fee_total = $service_fee + $service_fee_tax;
$total = $product->get_curent_bid() + $product_tax ;
$data['service_fee'][0]['amount'] = $service_fee;
$data['service_fee'][0]['tax'] = $service_fee_tax;
$data['service_fee'][0]['total'] = $service_fee;
$data['service_fee'][0]['tax_class'] = $product->get_tax_class();
$data['service_fee'][0]['taxes'] = $taxes;
$data['total_before_tax'] = $sub + $service_fee;
$data['total_tax'] = $product_tax + $service_fee_tax;
$data['total'] = $subtotal + $service_fee_total;
$result = CreateOrder($data, $user_id, $vendor_id);
if(strpos($result, "error") == false){
$order_id = $result;
}else{
return;
}
//print_r($order_id);
$data_pdf = array();
$data_pdf['order_id'] = $order_id;
$data_pdf['tax_rate'] = $tota_tax_rate;
$data_pdf['service_fee_total'] = $service_fee_total;
$data_pdf['order_total'] = $subtotal + $service_fee_total;
$data_pdf['order_subtotal'] = $sub + $service_fee;
$data_pdf['order_GST'] = $tax_label=="GST"?$product_tax + $service_fee_tax:0;
$data_pdf['order_PST'] = $tax_label=="PST"?$product_tax + $service_fee_tax:0;
$data_pdf['customer_name'] = $customer_name = $customer->get_billing_first_name()." ".$customer->get_billing_last_name();
$data_pdf['first_name'] = $customer->get_billing_first_name();
$data_pdf['last_name'] = $customer->get_billing_last_name();
$data_pdf['date'] = date("Y-m-d");
$data_pdf['address'] = $customer->get_billing_address_1().$customer->get_billing_address_2();
$data_pdf['city'] = $customer->get_billing_city();
$data_pdf['postcode'] = $customer->get_billing_postcode();
$data_pdf['phone'] = get_user_meta( $user_id, 'billing_phone', true );
$data_pdf['username'] = get_user_meta( $user_id, 'nickname', true );
//$data_pdf['invoice_number']
$data_pdf['orders'][$order_id]['order_id'] = $order_id;
$data_pdf['orders'][$order_id]['service_fee'] = $service_fee;
$data_pdf['orders'][$order_id]['service_fee_PST'] = $tax_label=="PST"?$service_fee_tax:0;
$data_pdf['orders'][$order_id]['service_fee_GST'] = $tax_label=="GST"?$service_fee_tax:0;
$data_pdf['orders'][$order_id]['products'][$product_id]['product_name'] = $product->get_name();
$data_pdf['orders'][$order_id]['products'][$product_id]['qty'] = 1;
$data_pdf['orders'][$order_id]['products'][$product_id]['unit_price'] = $product->get_curent_bid();
$data_pdf['orders'][$order_id]['products'][$product_id]['echo_PST'] = $tax_label=="PST"?$product_tax + $service_fee_tax:0;
$data_pdf['orders'][$order_id]['products'][$product_id]['echo_GST'] = $tax_label=="GST"?$product_tax + $service_fee_tax:0;
$data_pdf['orders'][$order_id]['products'][$product_id]['description'] = $product->get_short_description();
//print_r($data_pdf);
$file = generate_new_pdf_download($data_pdf, "customer", 0, 0);
$title = "Successful Bid on Reserved ".$product_name." at $".$current_bid." for Lot".$product_id;
// print_r($title);
//$dir = plugin_dir_path();
//print_r($dir);
$content = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/12_self_service_agree_bid_customer.html');
//print_r($content);
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$content = str_replace('[current_bid]',$current_bid, $content);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$customer_recipient,
$title,
$content,
$headers,
$file,
);
//echo $auction_id."--".$product_name."--".$current_bid;
//print_r($content);
$profileid = get_user_meta($user_id, 'wc_authorize_net_cim_customer_profile_id', true);
$paymentprofileid = json_decode(get_user_meta($user_id, 'wc_authorize_net_cim_customer_payment_id', true))[0];
$service_fee_total = number_format($service_fee_total, 2);
//echo gettype($service_fee_total);
$res = chargeCustomerProfile($profileid, $paymentprofileid, $service_fee_total);
//die();
if (!$res){
//pay failed
//echo "no";
update_post_meta( $order_id, '_auction_payment', "1" );
//failed payment first time sent email to buyer
$title = 'Failed Payment by Bidder';
//$dir = plugin_dir_path( __DIR__ );
$content = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/14_self_service_1st_payment_fail_customer.html');
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$customer_recipient,
$title,
$content,
$headers,
);
//failed payment first time sent email to seller
$title = 'Failed Payment by Bidder';
$content = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/16_self_service_1st_payment_fail_vendor.html');
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$vendor_recipient,
$title,
$content,
$headers,
);
}else{
//pay successful
//echo "yes";
update_post_meta( $order_id, '_auction_payment', "TRUE" );
$order = wc_get_order( $order_id );
if (!empty($order)) {
$order->update_status( 'wc-processing' );
}
//for customer
$title = 'Purchase Information of '.$product_name.' for Lot'.$product_id ;
$content = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/22_self_serivce_breach_customer.html');
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$content = str_replace('[current_bid]',$current_bid, $content);
$content = str_replace('[vendor_name]',$vendor_name, $content);
$content = str_replace('[vendor_email]',$vendor_recipient, $content);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$customer_recipient,
$title,
$content,
$headers,
);
//for vendor
$title = 'Sale Information of '.$product_name.' for Lot'.$product_id ;
$content = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/23_self_service_payment_success_vendor.html');
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$content = str_replace('[current_bid]',$current_bid, $content);
$content = str_replace('[customer_name]',$customer_name, $content);
$content = str_replace('[customer_email]',$customer_recipient, $content);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$vendor_recipient,
$title,
$content,
$headers,
);
}
}else{
//no touch resered price
//echo $reserve - $current_bid;
//for customer email
$service_type = get_post_meta($auction_id, 'service_type', true);
if ($service_type == "delegation"){
$headers[] = 'Content-Type: text/html; charset=UTF-8';
$headers[] = 'Cc:'.ADMIN_EMAIL;
$title = " High Bidder on Reserved on ".$product_name." for Lot ".$auction_id;
$content = file_get_contents(__DIR__ .'/templates/7_angeldd_no_reserve_customer.html');
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$content = str_replace('[current_bid]',$current_bid, $content);
wp_mail(
$customer_recipient,
$title,
$content,
$headers,
);
}else if ($service_type == "self_service"){
$title = "High Bidder on Reserved ".$product_name." for Lot ".$auction_id;
$content_customer = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/9_self_service_no_reserve_customer.html');
$content_customer = str_replace('[product_id]',$auction_id, $content_customer);
$content_customer = str_replace('[product_name]',$product_name, $content_customer);
$content_customer = str_replace('[current_bid]',$current_bid, $content_customer);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$customer_recipient,
$title,
$content_customer,
$headers,
);
//for vendor email
//$vendor_recipient = $vendor->user_email;
$title = "Reserve Not Met on Reserved ".$product_name." for Lot ".$auction_id;
$content_vendor = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/10_self_service_no_reserve_vendor.html');
$content_vendor = str_replace('[product_id]',$auction_id, $content_vendor);
$content_vendor = str_replace('[product_name]',$product_name, $content_vendor);
$content_vendor = str_replace('[current_bid]',$current_bid, $content_vendor);
//$content_vendor = str_replace('[user_id]',$user_id, $content_vendor);
$data = $product_id.OPTION_SPLITE.$user_id;
$data = _encrypt($data, OPTION_KEY);
$content_vendor = str_replace('[data]',$data, $content_vendor);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
//$headers[] = 'Cc:neo.itcg#gmail.com';
wp_mail(
$vendor_recipient,
$title,
$content_vendor,
$headers,
);
/* echo $data."--".$auction_id."--".$product_name."--".$user_id;
echo "<br>";
print_r($content_vendor); */
update_post_meta( $product_id, '_reserved_option', 'none' );
}
}
/* }else{
echo "1";
} */
endwhile;
wp_reset_query();
}

Related

WordPress Send MailChimp Campaign

Im trying to send a MailChimp campaign, from a cron job in a cpanel, in a php file.
The idea is to have a condition and if realized, send a MC campaign.
The test is if there is an unseen message in a certain mailbox with a certain subject. The test is done trough an imap connexion as you will see below.
The unseen email test is working with a cron job, no pb.
But when i add the MC connexion and campaign sending, it is stuck.
Here is the entire code i have tried to write (actually, i tried to use others pieces of code).
Please help if possible.
<?php
//needed for the MailChimp connection
require_once (‘wp-config.php’);
$SCUpdate = 0 ;
$mailbox = imap_open('{imap.server.com:993/imap/ssl}INBOX', 'email#domain.com', 'password');
$unseenMessages = imap_search($mailbox, 'UNSEEN');
if ($unseenMessages != 0) {
$MailHeaders = imap_headers( $unseenMessages );
$Subject = "Subject_Search_Name";
Foreach ($MailHeaders as $Subject) {
$SCUpdate = 1 ;
}
If ($SCUpdate = 1) {
//make the MailChimp connection
function mailchimp_api_request($endpoint,$type=‘POST’,$body = ‘’) {
$api_key = 'xxxxxxx';
$endpoint = ‘https://<dc>.api.mailchimp.com/3.0/’;
list(, $datacenter) = explode( ‘-’, $api_key );
$endpoint = str_replace( ‘<dc>’, $datacenter, $endpoint );
$url = $endpoint . $endpoint;
$request_args = array(
‘method’ => $type,
‘timeout’ => 20,
‘headers’ => array(
‘Content-Type’ => ‘application/json’,
‘Authorization’ => ‘apikey ‘ . $api_key
)
);
if ( $body ) {
$request_args[‘body’] = json_encode( $body );
}
$request = wp_remote_post( $url, $request_args );
$response = is_wp_error( $request ) ? false : json_decode( wp_remote_retrieve_body( $request ) );
return $response;
}
//link campaign to template
$campaign_id = 'xxxxxxx';
function set_mail_campaign_content( $campaign_id, $template_content ) {
$set_content = '';
$set_campaign_content = mailchimp_api_request( "campaigns/$campaign_id/content", 'PUT', $template_content );
if ( $set_campaign_content ) {
if ( ! empty( $set_campaign_content->html ) ) {
$set_content = true;
}
}
return $set_content ? true : false;
}
$list_id = "your-list-id";
$date = date('Y-m-d',strtotime(current_time('mysql')));
$title = "campaign-title";
$subject = "campaign-subject";
$campaign_id = null;
$campaign_id = create_mailchimp_campaign( $list_id, $subject, $title );
if($campaign_id == null){
exit(2);
}
$template_content = array(
'template' => array(
// The id of the template to use.
'id' => xxxxxxx,
)
);
$set_campaign_content = set_mail_campaign_content( $campaign_id, $template_content );
if($set_campaign_content == false){
exit(3);
}
// Schedule time
$time = time();
$schedule = mailchimp_api_request( "campaigns/$campaign_id/actions/schedule", 'POST', array('schedule_time' => $time) );
$campaign = mailchimp_api_request( "/campaigns/$campaign_id", 'GET', '' );
mail('myemail#test.com', 'Test Subject', 'Test Name');
$SCUpdate = 0 ;
}
}
if ($unseenMessages) {
imap_setflag_full( $mailbox, implode(',', $unseenMessages ), '\Seen');
imap_close( $mailbox );
}
?>

None of my WooCommerce functions are working

Based on Go through certain WooCommerce orders, collect data and then send the results via email anwer code that is supposed to take all the WooComerce orders from yesterday total them and email them to me, but the email prints 0 for all the values.
<?php
define('WP_USE_THEMES', false);
require( dirname( __FILE__ ) . '/wp-load.php' );
// Date
$yesterday = date( 'Y-m-d', strtotime( ' -1 days ' ) );
// Args
$args = array(
'date_created' => $yesterday,
);
// Get WC orders
$orders = Wc()->wc_get_orders( $args );
// Initialize
$subtotal = 0;
$gratuity = 0;
$taxes = 0;
// NOT empty
if ( ! empty ( $orders ) ) {
foreach ( $orders as $order ) {
// DEBUG information, removed if desired
echo '<p>ID = ' . $order->get_id() . '</p>';
// Get subtotal
$subtotal += $order->get_subtotal();
// Get fees
foreach ( $order->get_fees() as $fee_id => $fee ) {
$gratuity += $fee['line_total'];
}
// Get tax
$taxes += $order->get_total_tax();
}
}
// Send e-mail
$to = 'jesse#munerismedia.com';
$subject = 'Order totals for yesterday';
$body = '<p>Subtotal = ' . $subtotal . '</p><p>Gratuity = ' . $gratuity . '</p><p>Taxes = ' . $taxes . '</p>';
$headers = array( 'Content-Type: text/html; charset=UTF-8' );
wp_mail( $to, $subject, $body, $headers );
?>
I think I might be missing a dependency or something. Btw this is a nightly running cron job.

Get all persons as a sum from all WooCommerce bookings

I use the official woocommerce booking plugin and I try do get the quantity of all persons that have booked a product.
for a single order that's no problem with:
if ( is_callable( 'WC_booking_Data_Store::get_booking_ids_from_order_id') ) {
$booking_data = new WC_booking_Data_Store();
$booking_ids = $booking_data->get_booking_ids_from_order_id( $order->get_id() );
}
foreach ( $booking_ids as $booking_id ) {
$booking = new WC_booking( $booking_id );
$person_count = array_sum( $booking->get_person_counts() );
$total_person_count .= 'Booking id: ' . $booking_id . ' Person Count: ' . $person_count . ' ';
}
but how can I collect the sum of all bookings? Hope you can help me
To get all "complete" bookings persons count use the following:
// get all bookings Ids with a status "complete"
$bookings_ids = get_posts( array(
'posts_per_page' => -1,
'post_type' => 'wc_booking', // booking post type
'post_status' => 'complete',
'fields' => 'ids',
));
$persons_count = 0; // Initializing
$persons_html = '<table><tr><th>Booking id</th><th>Persons count</th></tr>'; // Initializing
// Loop through booking Ids
foreach ( $bookings_ids as $booking_id ) {
$booking = new WC_Booking( $booking_id ); // Get the WC_Booking instance object
$count = array_sum( $booking->get_person_counts() );
$persons_count += $count;
$persons_html .= '<tr><td>' . $booking_id . '</td><td>' . $count . '</td></tr>';
}
$persons_html .= '<tr><th><strong>Total count</th><td style="color:red">' . $persons_count . '</td></tr>';
// Output
echo $persons_html . '</table>';
Tested and works.
To make it lighter, you could replace:
$booking = new WC_Booking( $booking_id ); // Get the WC_Booking instance object
$count = array_sum( $booking->get_person_counts() );
simply by:
$count = array_sum( get_post_meta($booking_id, '_booking_persons', true) );
following your updated code, please try this
<?php
if ( is_callable( 'WC_booking_Data_Store::get_booking_ids_from_order_id') ) {
$booking_data = new WC_booking_Data_Store();
$booking_ids = $booking_data->get_booking_ids_from_order_id( $order->get_id() );
}
$total_count_data = array();
$total_count_persons = 0;
foreach ( $booking_ids as $booking_id ) {
$booking = new WC_booking( $booking_id );
$person_count = array_sum( $booking->get_person_counts() );
$total_count_persons+= $person_count;
$total_count_data[] = array(
'Booking' => $booking_id,
'Person' => $person_count
);
}

How to list recently sold products in WooCommerce

In WooCommerce I would like to show recently sold products in a 4 column layout. An example of what I'm going for can be found here: www.hem.com at recently purchased.
So the listing should have the
- Product Name
- Product Price
- Product Thumbnail
- Buyer first name
The listing should show sold out products since all the products are one of a kind.
I've looked at multiple plugins, but most operate by showing a popup or straight up faking the recent purchases.
I want to show actual purchases.
Please follow this code:
function shortcode($atts) {
$param = get_option($this->pref);
$quantity = isset( $param['quntity'] ) ? $param['quntity'] : '5';
$notification = isset( $param['content'] ) ? $param['content'] : "{fname} {lname} purchased {product} for {price} {time} ago";
$img = isset( $param['shortcode_img'] ) ? $param['shortcode_img'] : 'none';
$img_size = isset( $param['shortcode_img_size'] ) ? $param['shortcode_img_size'] : '32';
$args = array(
'numberposts' => $quantity,
'post_status' => 'wc-completed',
'post_type' => 'shop_order',
'suppress_filters' => true,
);
$payments = get_posts( $args );
$out = null;
if($payments){
$out .= '<ul class="wow_woo_recent_purchases">';
foreach ( $payments as $payment ) {
setup_postdata($payment);
$order = new WC_Order($payment->ID);
$fname = $order->get_billing_first_name();
$lname = $order->get_billing_last_name();
$date = $order->get_date_completed();
$time = human_time_diff( strtotime($date), current_time('timestamp') );
$user_id = $order->get_user_id();
$products = $order->get_items();
$product_ids = array();
foreach($products as $product){
$product_ids[] = $product['product_id'];
}
$product_ids = array_unique($product_ids);
$item_id = $product_ids[0];
$product = wc_get_product( $item_id );
$price = $product->get_price_html();
$url = get_permalink($item_id);
$download = ''.$product->get_title().'';
$message = $notification;
$message = str_replace( '{fname}', $fname, $message );
$message = str_replace( '{lname}', $lname, $message );
$message = str_replace( '{product}', $download, $message );
$message = str_replace( '{price}', $price, $message );
$message = str_replace( '{time}', $time, $message );
if($img == 'download'){
$image = get_the_post_thumbnail( $item_id, array($img_size,$img_size), array('class' => 'alignleft') );
$image = ''.$image.'';
}
elseif($img == 'avatar'){
$url = get_avatar_url( $user_id, array('size' => $img_size,'default'=>'monsterid',) );
$image = '<img src="'. $url .'" class="alignleft" width="'.$img_size.'">';
}
else {
$image = null;
}
$out .= '<li>'.$image.' '.$message.'</li>';
}
wp_reset_postdata();
$out .= '</ul>';
}
return $out;
}

Sequential Number Contact Form 7

I managed to get the info needed to create sequential number for CF7 through https://www.banna360.com/contact-from7-dynamic-number-generation/
function wpcf7_generate_rand_number( $wpcf7_data ) {
$properties = $wpcf7_data->get_properties();
$shortcode = '[rand-generator]';
$mail = $properties['mail']['body'];
$mail_2 = $properties['mail_2']['body'];
$subject = $properties['mail']['subject'];
$subject2 = $properties['mail_2']['subject'];
if( preg_match( "/{$shortcode}/", $mail ) || preg_match( "/[{$shortcode}]/", $mail_2 ) ) {
$option = 'wpcf7sg_' . $wpcf7_data->id();
$sequence_number = (int)get_option( $option ) + 1;
update_option( $option, $sequence_number );
$properties['mail']['body'] = str_replace( $shortcode, $sequence_number, $mail );
$properties['mail_2']['body'] = str_replace( $shortcode, $sequence_number, $mail_2 );
$properties['mail']['subject'] = str_replace( $shortcode, $sequence_number, $subject );
$properties['mail_2']['subject'] = str_replace( $shortcode, $sequence_number, $subject2 );
$wpcf7_data->set_properties( $properties );
}
}
add_action( 'wpcf7_before_send_mail', 'wpcf7_generate_rand_number' );
However, I need to specify a start number (eg. 1000001) instead of just starting from 1. Any idea how I do that with this code?
Thanks!
$sequence_number = (int)get_option( $option ) + 1;
if ($sequence_number == 1) {
$sequence_number = 1000001;
}
update_option( $option, $sequence_number );

Categories