I'm trying to send emails notification using wp cron but my code doesn't works.
I'm using a plugin to run my wp cron job every day and the function called is named EVENT NOTIFICATION.
In functions.php I put this code:
function EVENT_NOTIFICATION_function() {
global $wpbd;
$test_data = '2025-05-04';
$results=$wpdb->get_results ("SELECT * FROM wp_postmeta WHERE meta_key = 'data_concert' AND meta_value = '$test_data'" );
foreach ($results as $row) {
$post_id = $row->post_id;
// Send email to;
$email_to = 'tester1#gmail.com, tester2#gmail.com';
// Set the email subject
$email_subject = 'Event Alert';
// Set the email content
$content = 'Hey dude remember that you have to play!';
// Set the email headers
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $email_to, $email_subject, $content , $headers );
}
}
add_action( 'EVENT_NOTIFICATION', 'EVENT_NOTIFICATION_function' );
There's something wrong on this part:
$results=$wpdb->get_results ("SELECT * FROM wp_postmeta WHERE meta_key = 'data_concert' AND meta_value = '$test_data'" );
foreach ($results as $row) {
$post_id = $row->post_id;
cause if I delete it everything works well!
I don't find how to fix it.
Related
I have to collect order details and checkout details on my email account on clicking the place an order button in woocommerce and redirect them to home page without paying any order fee. I'm using the elementor with WC.
// Getting an instance of the order object
$order = new WC_Order( $order_id );
$items = $order->get_items();
//Loop through them, you can get all the relevant data:
foreach ( $items as $item ) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
}
`
You can set a default payment gateway in woocommerce without payment(ex:- COD).
you can hook into thank-you page using hook woocommerce_thankyou. then get the order object and relevent inforamtion and send this information using wp_mail() to your email then redirect the user to homepage.
for order information check out this blog.
https://www.businessbloomer.com/woocommerce-easily-get-order-info-total-items-etc-from-order-object/
Use below code and if you need a customized email template.
UPDATE 1.
add_action('woocommerce_thankyou', 'zillion_order_mail_and_redirect', 10, 1);
function zillion_order_mail_and_redirect($order_id)
{
$order = wc_get_order($order_id);
$url = home_url();
$to = 'sendto#example.com';
$subject = 'Order Info';
$body = '';
$headers = array('Content-Type: text/html; charset=UTF-8');
$body .= $order->get_formatted_order_total();
wp_mail($to, $subject, $body, $headers);
wp_safe_redirect($url);
exit;
}
wp_mail() reference: https://developer.wordpress.org/reference/functions/wp_mail/
UPDATE 2:-
You can add your email using woocommerce_email_headers hook to get a copy of the email is being sent to the customer.
add_action('woocommerce_thankyou', 'zillion_order_mail_and_redirect', 10, 1);
function zillion_order_mail_and_redirect($order_id)
{
$url = home_url();
wp_safe_redirect($url);
exit;
}
function zillion_hook_headers( $headers, $id, $order ) {
// The order ID | Compatibility with WC version +3
$order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
$your_email = '<example#gmail.com>';
$headers .= "To: Order Num $order_id $your_email";
return $headers;
}
add_filter( 'woocommerce_email_headers', 'zillion_hook_headers', 10, 3);
When I insert new images from Unsplash.com the image size "full" returns a scaled image with "-scaled.jpg" at the end of the name file and is always limited to 2560 pixels. So how can I retrieve the real "full" size of the image?
You have first to disable this "feature" introduced in WordPress 5.3 by adding this line of code in your functions.php:
add_filter( 'big_image_size_threshold', '__return_false' );
This will disable the scaling down for any FUTURE uploads. But for existing images you have to update the image sizes.
Unfortunately the WordPress team proves once more its incompetence - they dind't provide any functions to update the postmeta for existing attachments and obviously they don't give a single f... about this issue as you can see here, where dozens of people expressed there anger about this so called feature.
I have created today a site with several thousands of dummy posts with featured images from Unsplash.com and where I needed the full size of the images. It took a couple of hours to run the script which downloaded and created the blog posts and the attachments posts. So it wasn't an option to me to delete all the posts and run the dummy script again once I've found out about the new "feature" and how to disable it.
So I wrote another script which took me still a bunch of time...
You need to put the following code in a php file and run/call it from either the browser or terminal. Don't forget to replace the path to the wp-load.php file. On my local machine it took just a couple of seconds for several thousand attachment posts.
<?php
require_once( "/absolute/or/relative/path/to/wordpress/wp-load.php" );
ini_set( 'max_execution_time', 3600 );
set_time_limit( 3600 );
$pdo = new PDO( "mysql:dbname=" . DB_NAME . ";host=" . DB_HOST, DB_USER, DB_PASSWORD );
/**
* replace _wp_attached_file meta_key
**/
global $wpdb;
$wp_postmeta = $wpdb->prefix . "postmeta";
try {
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );//Error Handling
$sql = "UPDATE $wp_postmeta SET meta_value = REPLACE(meta_value,'-scaled.jpg','.jpg') WHERE meta_key='_wp_attached_file' AND meta_value LIKE '%-scaled.jpg%'";
$result = $pdo->exec( $sql );
print_r( $result );
} catch ( PDOException $e ) {
print_r( $e->getMessage() );
}
/**
* replace _wp_attachment_metadata meta_key
**/
$image_metas = [];
try {
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );//Error Handling
$sql = "SELECT * FROM $wp_postmeta WHERE meta_value LIKE '%-scaled.jpg%' AND meta_key='_wp_attachment_metadata'";
$statement = $pdo->query( $sql );
$image_metas = $statement->fetchAll();
foreach ( $image_metas as $meta ) {
$meta_value = unserialize( $meta["meta_value"] );
$file = $meta_value["file"];
$meta_value["file"] = str_replace( "-scaled.jpg", ".jpg", $file );
update_post_meta( $meta["post_id"], $meta["meta_key"], $meta_value );
$result = get_post_meta( $meta["post_id"], $meta["meta_key"] );
print_r( $result );
}
} catch ( PDOException $e ) {
print_r( $e->getMessage() );
}
I'm developing wordpress plugin.
I need to find out post_id from thumbnail_id(not reverse !).
How can I do this?
You can get result by this code
global $wpdb;
$_thumbnail_id = {thumbnail id};
$sql = "SELECT `post_id` FROM `wp_postmeta` WHERE `meta_value` = $_thumbnail_id";
$result = $wpdb->get_results( $sql, ARRAY_A );
//access first returned post id
var_dump($result[0]['post_id']);
If you added same image for multiple posts there will be multiple returns.
You can use get_the_ID() to get the post id. You can find this function in wp-includes/post-template.php
function get_the_ID() {
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
I have a wordpress photo blog that reposts images from instagram for me.
The posts are created from an IFTTT applet through XML-RPC.
For some reason duplicate posts are often created (this is a bug thats been around for years and ifttt dont seem to care about it).
To get around this, I create each post with a title containing the unique instagram ID of the photo. I would like to use this to compare the new post_title to existing ones.
I have tried hooking into transition_post_status, this works for normal posting but all posts coming though XML-RPC are still published. They seem to bypass that action.
Can I hook into XML-RPC when it creates the post and prevent it if it has an already existing post_title?
Here is the code that works for normal posts:
add_action('transition_post_status', 'check_for_duplicates', 10, 3);
function check_for_duplicates($new_status, $old_status, $post) {
if('publish' === $new_status && 'publish' !== $old_status && $post->post_type === 'post') {
global $post;
global $wpdb ;
$title = $post->post_title;
$post_id = $post->ID ;
$wtitlequery = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND post_title = '{$title}' AND ID != {$post_id} " ;
$wresults = $wpdb->get_results( $wtitlequery) ;
if ( $wresults ) {
$error_message = 'This title is already used. Please choose another';
add_settings_error('post_has_links', '', $error_message, 'error');
settings_errors( 'post_has_links' );
$post->post_status = 'draft';
wp_update_post($post);
wp_die( $error_message );
return;
}
//return $messages;
}
}
Firstly, sorry if this has been dealt with before, I've spent quite a while searching posts to no avail.
I have a Wordpress blog and a Concrete5 site. I am trying to write out the three most recent Wordpress blog posts on the Concrete5 site. I cannot use RSS as both sites are on the same server and internal RSS is disabled (is there a way to get around this?).
I have written a block for concrete and have put this code in view.php ...
<?php
define('WP_USE_THEMES', false);
require('path-to-wordpress/wp-blog-header.php');
?>
... This results in "Error establishing a database connection".
If I run this outside of Concrete it works fine (I'm currently using this code elsewhere on the server, no probe).
I've also tried with wp_load.php, same result.
Sorry if this is really obvious, I've been working on it for a while now :(
Thanks in advance.
Sadly this simple approach to loading Wordpress does not work in concrete for whatever reason, some kind of conflicting definition or something. If you are trying to load Wordpress posts on a Concrete5 site on the same server you might well find that using RSS will not work for you as sometimes servers block internal requests to prevent looping.
This is the position I found myself in so I decided to access the Wordpress table myself building on code posted by 'jcrens8392' on the Concrete5 forums , so here it is for anyone who finds them self in the same position.
// posts and stuff
$category = 3
$items = 4
// wordpress db stuff
$dbUser = 'user';
$dbPass = 'password';
$dbHost = 'localhost';
$dbName = 'name';
// connect to wordpress database
$conn = mysql_connect($dbHost, $dbUser, $dbPass);
// handle connection errors
if(!$conn) {
$aDebug['Unable to connect to DB'] = mysql_error();
} elseif(!mysql_select_db($dbName, $conn)) {
$aDebug['Unable to select database'] = mysql_error();
}
// make SQL query
else {
$sQuery = "SELECT wp_posts.post_date, wp_posts.post_content , wp_posts.guid , wp_posts.post_title, wp_posts.post_excerpt, wp_posts.post_name FROM wp_posts , wp_term_relationships WHERE post_type = 'post' AND post_status = 'publish' AND wp_posts.ID = wp_term_relationships.object_id AND wp_term_relationships.term_taxonomy_id = ".$category." ORDER BY post_date DESC LIMIT ".$items;
$rPosts = mysql_query($sQuery, $conn);
}
// plonk posts into a convinient array
$posts = array();
while($row = mysql_fetch_array($rPosts)){
$excerpt = $controller->getExcerpt( utf8_encode( strip_tags( $row['post_content'] ) ) , 0 , 200 ) .' Read More →';
$date = $controller->simplifyDate( $row['post_date'] );
$temp = array ( 'post_title' => $row['post_title'] , 'post_excerpt' => $excerpt , 'post_date' => $date , 'post_link' => $row['guid'] );
array_push( $posts , $temp );
}
I put these functions in controller.php (excerpt function from phpsnaps)...
function getExcerpt($str, $startPos=0, $maxLength=100) {
if(strlen($str) > $maxLength) {
$excerpt = substr($str, $startPos, $maxLength-3);
$lastSpace = strrpos($excerpt, ' ');
$excerpt = substr($excerpt, 0, $lastSpace);
$excerpt .= '...';
} else {
$excerpt = $str;
}
return $excerpt;
}
function simplifyDate($str) {
$months = array("January","February","March","April","May","June","July","August","September","October","November","December");
$strs = split ( ' ' , $str );
$date = split ( '-' , $strs[0] );
$month = $months[ $date[1] - 1 ];
$day = $date[2];
$year = $date[0];
return $day . ' ' . $month . ' ' . $year;
}
This really isn't the ideal solution, it does, however, have the distinct advantage of working. Hope this helps someone.