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

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();

Related

Get meta_value from GDRating

I am trying to get meta value from GD Rating table for each post ID with following sql:
$querystr = "SELECT meta_value FROM $wpdb->gdrts_itemmeta WHERE meta_key LIKE 'stars-rating_rating'";
$ratings = $wpdb->get_results($querystr);
foreach ($ratings as $rating)
{
$rating->meta_value;
}
$ratingku = get_post_meta($post->ID, $rating, true);
But it failed. It return a word: "ARRAY".
How to get meta_value from another table (created by a plugin) for each post by using SQL or Query?
To get the rating value for the post use below query:
global $wpdb;
$querystr = "SELECT meta_value AS rating FROM ".$wpdb->prefix."gdrts_itemmeta INNER JOIN ".$wpdb->prefix."gdrts_items ON ".$wpdb->prefix."gdrts_items.item_id = ".$wpdb->prefix."gdrts_itemmeta.item_id AND ".$wpdb->prefix."gdrts_itemmeta.meta_key = 'stars-rating_rating' AND ".$wpdb->prefix."gdrts_items.id = ".$post->ID;
$result = $wpdb->get_row($querystr);
echo $result->rating;

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

$wpdb query not working in plugin

I'm trying to do a reviews plugin in Wordpress, and one of the thing that my client asked me to do was that a user should be able to rate only one product every 24 horas, so I have to establish a limit between rates.
And I made this function to check if the limit is reached:
function isAllowedToRate(){
global $wpdb;
$currentDate = date('Y-m-d');
$userId = get_current_user_id();
$table_name = $wpdb->prefix .'esvn_reviews';
$isAllowed = $wpdb->get_results(
"
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE user_id = {$userId}
AND review_date = {$currentDate}
"
);
if( count( $isAllowed > 0 ) ){
return false;
}else{
return true;
}
}
But every time I try to run it, it returns false, the error that I'm getting from Wordpress is this:
<div id='error'>
<p class='wpdberror'><strong>WordPress database error:</strong> []<br />
<code>
SELECT user_id, fecha_calificacion
FROM wp_esvn_reviews
WHERE user_id = 6
AND fecha_calificacion = 2015-10-30
</code></p>
</div>
If I take the same SQL and run it directly into the database, it works like a charm, but I keep getting this error from Wordpress and the function always returns false.
You need to wrap your date in single quotes.
$isAllowed = $wpdb->get_results(
"
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE user_id = {$userId}
AND review_date = '{$currentDate}'
"
);
Alternatively you could use $wpdb->prepare(), which I would consider better form.
$sql = <<<SQL
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE
user_id = %d -- this is formatted as a (d)igit
AND review_date = %s -- this is formatted as a (s)tring
SQL;
$isAllowed = $wpdb->get_results($wpdb->prepare($sql, $userId, $currentDate));
I found the error (in case someone needs the information in the future), I was treating $isAllowed as an array, and it was an object, I had to add ARRAY_A to the get_results:
$isAllowed = $wpdb->get_results(
"
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE user_id = {$userId}
AND review_date = {$currentDate}
",ARRAY_A /* output as an associative array */
);

Want to create a dynamic page to list content by letter

I want to create a dynamic page in WP theme so that when I pass a letter from 'A-Z' it will display all the posts with the title starting from that letter.
Can you please tell me how to proceed?
If you are using themes and getting the index key via a query parameter then you can create a new custom theme file and add the following code to get the list of posts.
$thePostIdArray = null;
$indexkey = $_GET['indexkey'];
if ($indexkey!=null){
$querystr = "
SELECT wposts.ID
FROM $wpdb->posts wposts
WHERE UPPER(wposts.post_title) like '".$indexkey."%'
AND wposts.post_status = 'publish'
AND wposts.post_type = 'post'
ORDER BY wposts.post_title ASC
";
$thePostArray = $wpdb->get_results($querystr);
$i = 0;
foreach ($thePostArray as $currentPost){
$thePostIdArray[$i] = $currentPost->ID;
$i++;
}
After that just just a matter of going through the post array and displaying them.

How to get certain posts in wordpress

I want to implement a function to get certain posts in wordpress.
INPUT
page_number
category_name
VARIABLE
items_per_page = 10
OUTPUT
posts array, like the result of the query_posts() function.
Here is my code:
$page_number = $_GET["page_number"]
$category_name = $_GET["category_name"]
function app_get_posts($page_number, $category,$items_per_page = 10)
{
global $wpdb;
$select ="SELECT POSTS FROM wp_posts WHERE CATEGORY = ".$category." LIMIT (".$page_number." - 1) * ".$items_per_page.",".$page_number." * ".$items_per_page; //it didn't work.
return $wpdb->query($select);
}
When I call the function app_get_posts('2','tech'), it will return the 10th~19th posts in the "tech" category, when I call app_get_posts('3','wordpress'), it will return the 20th~29th posts in the "wordpress" category.
So I am wondering if there is a way to figure out this problem.
Thx in advence.
I guess the reason why the above won't work is because the wp_posts table not has a CATEGORY or POSTS field. I modified you code so you can return posts based on taxonomy:
function app_get_posts($page_number, $category,$items_per_page = 10)
{
global $wpdb;
$start = ($page_number-1) * $items_per_page;
$select ="SELECT DISTINCT wp.* FROM wp_posts wp
INNER JOIN wp_term_relationships rs ON rs.object_id = wp.ID
INNER JOIN wp_terms t ON t.term_id = rs.term_taxonomy_id
WHERE t.name = ".$category." LIMIT ".$start.",".$items_per_page;
return $wpdb->query($select);
}

Resources