How to decode booking dates in Wordpress DB - wordpress

I ran this query in Wordpress DB and found out that Booking dates are stored in some coded way.
SELECT post_id, meta_id, post_title, meta_key, meta_value
FROM a40443635734677.wp_7n2ncdd4yn_postmeta, a40443635734677.wp_7n2ncdd4yn_posts
where post_id = ID and post_type = 'estate_property'
and meta_key in ('property_price', 'cancellation', 'booking_dates',
'prop_featured', 'min_days_booking') and meta_key = 'booking_dates' and post_id = 248
order by post_id;
Output: a:2:{i:1600646400;i:374;i:1600732800;i:374;}
From UI, it shows that booking dates are sept-21-2020 to sept-23-2020.
how to decode the data from DB (a:2:{i:1600646400;i:374;i:1600732800;i:374;}) to these dates?

You can use unserialize() to convert it into an array.
$dbdata = 'a:2:{i:1600646400;i:374;i:1600732800;i:374;}';
$dbdata = unserialize($dbdata);
//result
array (
1600646400 => 374,
1600732800 => 374,
)
Then use PHPs DateTime to convert to human readable format e.g.
$returnDate = date('d.m.Y H:i:s', 1600646400);
//result
21.09.2020 02:00:00

The larger set of numbers you showed us look like seconds since the Epoch (January 1, 1970). You could use MySQL's FROM_UNIXTIME function convert these epoch values to a bona-fide human readable date. For example:
SELECT FROM_UNIXTIME(1600646400); -- 21.09.2020 02:00:00

That is serialized data. Use PHPs built in unserialize( your output variable here ). You'll get an array since the serialized data is an array (a:2 means array with two indexes).
The date is in UNIX time. You can use PHPs DateTime to convert to human readable format.
$output = SELECT post_id, meta_id, post_title, meta_key, meta_value
FROM a40443635734677.wp_7n2ncdd4yn_postmeta, a40443635734677.wp_7n2ncdd4yn_posts
where post_id = ID
and post_type = 'estate_property'
and meta_key in ('property_price', 'cancellation', 'booking_dates', 'prop_featured', 'min_days_booking') and meta_key = 'booking_dates'
and post_id = 248 order by post_id;
// Unserialize the data.
$unserialized = unserialize($output);
// Get the date for each array key. The date is the $key, so you pass that to the php date function.
foreach( $unserialized as $key => $date ) {
echo date('M-d-Y', $key ) . "\n";
}
This will output Sept-20-2020 and Sept-21-2020 with the data you supplied.

Related

Count number of posts have particular meta key or value?

What I want to achieve is display the number of posts which have particular meta key or value I am getting a list of posts and meta key and value but don't know how to display them I'm storing data using repeatable fields. Storing work properly.
Now, for example, I have age meta value in two posts so how can I count no of a post with age. Age = No of post 2.
My Code :
global $wpdb;
$query = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}postmeta WHERE (meta_key = 'repeatable_fields') ");
$array = wp_json_encode($query);
print_r($array);
Outout :
[{"meta_id":"312","post_id":"108","meta_key":"repeatable_fields","meta_value":"a:2:{i:0;a:2:{s:4:\"name\";s:6:\"Zaheer\";s:5:\"phone\";s:3:\"123\";}i:1;a:2:{s:4:\"name\";s:6:\"Sageer\";s:5:\"phone\";s:11:\"09190219218\";}}"},{"meta_id":"323","post_id":"121","meta_key":"repeatable_fields","meta_value":"a:2:{i:0;a:2:{s:9:\"iif_label\";s:4:\"City\";s:11:\"iif_details\";s:7:\"karachi\";}i:1;a:2:{s:9:\"iif_label\";s:3:\"Age\";s:11:\"iif_details\";s:2:\"12\";}}"},{"meta_id":"329","post_id":"126","meta_key":"repeatable_fields","meta_value":"a:1:{i:0;a:2:{s:9:\"iif_label\";s:3:\"Age\";s:11:\"iif_details\";s:2:\"12\";}}"},{"meta_id":"332","post_id":"128","meta_key":"repeatable_fields","meta_value":"a:3:{i:0;a:2:{s:9:\"iif_label\";s:7:\"Country\";s:11:\"iif_details\";s:8:\"Pakistan\";}i:1;a:2:{s:9:\"iif_label\";s:4:\"City\";s:11:\"iif_details\";s:9:\"Islamabad\";}i:2;a:2:{s:9:\"iif_label\";s:3:\"Age\";s:11:\"iif_details\";s:2:\"12\";}}"}]
You could try something like this:
$count_age = $wpdb->get_col( $wpdb->prepare(
"
SELECT count(meta_id)
FROM {$wpdb->prefix}postmeta
WHERE meta_value LIKE '%%%s%%'
",
'Age'
));
More about get_col() here: https://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Column

Woocommerce - Showing only products in stock

a client want to show a total of the amount of products they have in their shop, I have used this code
$numposts = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'product' AND post_status = 'publish'");
Which works fine, however it shows the total number of published products and I want it to only show where stock is at 1 or greater, so basically it only shows the total number of products that are in actually in stock
Try joining to the post_meta table using the _stock_status meta_key where the meta_value is 'instock'. Caching the data is recommended since you don't want to run this on every request but will need to balance an appropriate amount of time to cache the data (since sales within the cache period won't be reflected in the total number of instock items). Only works if you are using a cache (which is highly recommended with WooCommerce due to the number of queries).
global $wpdb;
// cache key
$key = 'in_stock_products';
// we get back 'false' if there is nothing in the cache, otherwise 0+
$in_stock_products = wp_cache_get( $key );
// run the query if we didn't get it from the cache
if ( false === $in_stock_products ){
// create the SQL query (HEREDOC format)
$sql_query = <<<SQL
SELECT COUNT(p.ID) AS in_stock_products
FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} pm
ON p.ID = pm.post_id
AND pm.meta_key = '_stock_status'
AND pm.meta_value = 'instock'
WHERE p.post_type = 'product' AND p.post_status = 'publish'
SQL;
// query the database
$in_stock_products = (int) $wpdb->get_var( $sql_query );
// cache the results, choosing an appropriate amount of time to cache results
$cache_ttl = 0; // 0 is "as long as possible", otherwise cache time in seconds
wp_cache_add( $key, $in_stock_products, $cache_ttl ); // cache as long as possible
}
// $in_stock_products now has the value either from the cache or the database query.
echo "There are $in_stock_products in stock";

Delete posts with custom field date older than current date via cronjob

I want to make a cron job witch deletes all posts older than the date in a custom field of the post. I got following function within my functions.php My custom field name is bewerbungs_frist.
function foobar_truncate_posts(){
global $wpdb;
$currenttime = new DateTime();
$currenttime_string = $currenttime->format('Ymd');
# Set your threshold of max posts and post_type name
$post_type = 'job';
# Query post type
$query = "
SELECT ID FROM $wpdb->posts
WHERE post_type = '$post_type'
AND post_status = 'publish'
ORDER BY post_modified DESC
";
$results = $wpdb->get_results($query);
# Check if there are any results
if(count($results)){
foreach($results as $post){
$customfield = get_field('bewerbungs_frist', $post->ID);
$customfield_object = new DateTime($customfield);
$customfield_string = $customfield_object->format('Ymd');
if ( $customfield_string < $currenttime_string ) {
echo "The value of the custom date field is in the past";
echo $customfield_string;
$purge = wp_delete_post($post->ID);
}
}
}
}
foobar_truncate_posts();
I use a plugin to handle my cronjobs. The Hock name is: foobar_truncate_posts and Arguments is []
The cronjob works but it does not delete those post with the date of the customfield older than todays date. The two variables are the same.
$currenttime_string 20130820
$customfield_string 20130820
there's a typo in your code, you're missing an 's' at the end of $result.
This:
foreach($result as $post){
Should be this:
foreach($results as $post){
I just tried it out. Once you make that fix the wp_delete_post() works great.
EDIT
I'm really unclear on what you're trying to do. You want to check if the custom field is set to some time in the past? What purpose does the continue serve? Also, I'm guessing you're using Advanced Custom Fields (ACF). Using the jquery Date Picker, you can format your date to Ymd by default so you don't have to convert it to a DateTime object.
At any rate, this function should explain how to properly set and compare time values, you should be able to take it from there:
function foobar_truncate_posts(){
global $wpdb;
$currenttime = new DateTime();
$currenttime_string = $currenttime->format('Ymd');
# Set your threshold of max posts and post_type name
$post_type = 'post_type_job';
# Query post type
$query = "
SELECT ID FROM $wpdb->posts
WHERE post_type = '$post_type'
AND post_status = 'publish'
ORDER BY post_modified DESC
";
$results = $wpdb->get_results($query);
# Check if there are any results
if(count($results)){
foreach($results as $post){
$customfield = get_field('bewerbungs_frist', $post->ID);
$customfield_object = new DateTime($customfield);
$customfield_string = $customfield_object->format('Ymd');
if ( $customfield_string < $currenttime_string ) {
echo "The value of the custom date field is in the past";
$purge = wp_delete_post($post->ID);
}
}
}
}
foobar_truncate_posts();

WordPress database error: [Query was empty]

I'm using $wpdb to connect to a different database than my wordpress one like this:
$newdb = new wpdb(DB_NEW_USER, DB_NEW_PASSWORD, DB_NEW_NAME, DB_NEW_HOST);
I need to insert multiple rows into the database.
I used the code from this answer: Wordpress $wpdb. Insert Multiple Records.
To run the query, I use this line:
$newdb->query( $newdb->prepare("$query", $values));
When I do echo $query, this is the result: (there are more than 3 columns, but I shortened if for times sake)
INSERT INTO table (column1, column2, column3) VALUES ('%s', '%s', '%s')
When I var_dump($values), it returns an array with the same amout of strings as I have columns.
When I run the query, I get the following error:
WordPress database error: [Query was empty]
I tried selecting from the database in a similar fashion and it did work, so my connected to the db is working.
What am I doing wrong?
If anyone can help me I would really appreciate it.
Are you sure your query look like this?
$metakey = "Harriet's Adages";
$metavalue = "WordPress' database interface is like Sunday Morning: Easy.";
$wpdb->query( $wpdb->prepare(
"
INSERT INTO $wpdb->postmeta
( post_id, meta_key, meta_value )
VALUES ( %d, %s, %s )
",
array(
10,
$metakey,
$metavalue
)
) );

How do I get the timestamp for my date

The current code below returns my current local time in wordpress and the result looks like this. 2013-07-29 13:45:42
I need to convert this to a timestamp format. What is the answer please?
echo date_i18n( 'Y-m-d H:i:s', current_time( 'timestamp', 0 ) );
The PHP strtotime() function might work.
$timestamp = strtotime('2013-07-29 13:45:42');
EDIT
Here is your use case
$current_date = date('Y-m-d H:i:s'); ## Get current date
$timestamp = strtotime($current_date); ## Get timestamp of current date
echo $timestamp; ## Print timestamp
Come to find out I really just needed the actual date and not a timestamp to achieve my goal. So using this gives you wordpress current local time that is set on the settings page in the admin panel.
date_i18n('Y-m-d');

Resources