WordPress Find ID of a Post with a specific meta value - php

I have about 25,000 posts here (and rising). All of them under a Custom Post Type "lead".
Each post has meta information, including a variable called "uniqid".
this uniqid is a url parameter. now i need the post id where exactly this uniqid exists.
Now my question is if there is a way to speed up this determination.
I have tried 2 ways once a wp_query and get_results.
I ask because this function that determines the post id is always noted by plugin "query monitor" that it is slow.
These are the 2 approaches, both work. I just wonder if it is possible to speed up here?
The WP_Query solution.
$post_id = false;
$args = array(
'posts_per_page' => -1,
'post_type' => 'lead',
'fields' => 'ids',
'orderby' => 'date',
'order' => 'ASC',
'post_status' => 'publish',
'meta_key' => 'uniqid',
'meta_value' => $uniqid
);
$query = new WP_Query( $args );
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
// Get Post ID for return
$post_id = get_the_id();
// Break loop, when matching id was found
$uniqidGPM = get_post_meta( $post_id, 'uniqid' , true );
if($uniqidGPM == $uniqid) {
$post_found = true;
break;
}
}
}
wp_reset_postdata();
return $post_id;
The select get_results solution.
$post_id = false;
global $wpdb;
$selectQuery = "SELECT wp_wkdm_posts.ID FROM wp_wkdm_posts INNER JOIN wp_wkdm_postmeta ON ( wp_wkdm_posts.ID = wp_wkdm_postmeta.post_id ) WHERE 1=1 AND ( ( wp_wkdm_postmeta.meta_key = 'uniqid' AND wp_wkdm_postmeta.meta_value = '".$uniqid."' )) AND wp_wkdm_posts.post_type = 'lead' AND ((wp_wkdm_posts.post_status = 'publish')) GROUP BY wp_wkdm_posts.ID ORDER BY wp_wkdm_posts.post_date ASC";
$selectQueryResult = $wpdb->get_results($selectQuery);
if (empty($selectQueryResult)) {
return $post_id;
}else{
$post_id = $selectQueryResult[0]->ID;
return $post_id;
};

Please use this meta_query condition on the same query, it helps you.
$args = array(
'post_type' => 'lead',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
'key' => 'uniqid',
'value' => 'YOUR_VALUE'
)
);
$query = new WP_Query($args);

Related

wp_set_object_terms not setting the terms for the post

This code does not set the object terms. Please help me sort out the issue. The code results in the posts list and doesn't set the terms.
I have checked the below data.
The query results in the list of post.
calculation part in the loop results in the value (lesser or greater than 0)
function set_expired_job_categories() {
global $post;
$current_time = time();
$taxonomy = 'current-status';
$job_expired_id = 368;
$job_ongoing_id = 367;
// Set our query arguments
$args = array(
'fields' => 'ids', // Only get post ID's to improve performance
'post_type' => 'job', // Post type
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
'taxonomy' => 'current-status',
'field' => 'slug',
'terms' => array( 'ongoing' ),
),
);
$job_expiration_query = new WP_Query( $args );
// Check if we have posts to delete, if not, return false
if( $job_expiration_query->have_posts() ){
while( $job_expiration_query->have_posts() ){
$job_expiration_query->the_post();
$postid = get_the_ID();
$expire_timestamp = rwmb_meta( 'deadline_date' );
if ( $expire_timestamp ) {
$seconds_between = ( (int)$expire_timestamp - (int)$current_time );
if ( $seconds_between <= 0 ) {
wp_set_object_terms( $postid, (int)$job_expired_id, $taxonomy, true );
wp_remove_object_terms( $postid, (int)$job_ongoing_id, $taxonomy );
}
}
}wp_reset_postdata();
}
}
add_action( 'set_job_categories', 'set_expired_job_categories', 20, 2 );
As it is in the functions file, I need to set the global $wp_taxonomies to populate the taxonomies data initially. Also, instead of using the tag_ID, I have revised with the slug. These two changes helped to work out the code. The revised code is below for reference.
Thank you all for your efforts.
function set_expired_job_categories() {
global $post;
global $wp_taxonomies;
$current_time = time();
$taxonomy = 'current-status';
$job_expired_id = 'expired';
$job_ongoing_id = 'ongoing';
// Set our query arguments
$args = array(
'fields' => 'ids', // Only get post ID's to improve performance
'post_type' => 'job', // Post type
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
'taxonomy' => 'current-status',
'field' => 'slug',
'terms' => array( 'ongoing' ),
),
);
$job_expiration_query = new WP_Query( $args );
// Check if we have posts to set categories, if not, return false
if( $job_expiration_query->have_posts() ){
while( $job_expiration_query->have_posts() ){
$job_expiration_query->the_post();
$postid = get_the_ID();
$expire_timestamp = rwmb_meta( 'deadline_date' );
if ( $expire_timestamp ) {
$seconds_between = ( (int)$expire_timestamp - (int)$current_time );
if ( $seconds_between >= 0 ) {
}else {
wp_set_object_terms( $postid, (int)$job_expired_id, $taxonomy, true );
wp_remove_object_terms( $postid, (int)$job_ongoing_id, $taxonomy );
}
}
}
wp_reset_postdata();
}
}
// hook it to low priority value, due to CPT and Taxonomies
add_action( 'set_job_categories', 'set_expired_job_categories', 20, 2 );
Reference: https://wordpress.org/support/topic/wp_set_object_terms-in-loop-is-not-work-in-taxonomy-cpt/

Filter WooCommerce related products by Polylang language

I'm using polylang plugin to having multi-languages website.
Using WooCommerce with polylang demands duplicating each product for each language, so assuming I have Hebrew and English, that means 2 duplications for each products.
It works fine with WooCommerce plugin, but when I'm displaying "related products" at the end of the product page, it's mixing products in English and Hebrew together.
I expect to filter the related product by website current language (if(get_locale() == 'en_US') - to check website current locale state, else will represent Hebrew).
Polylang functions
Here is what I have tried, but I got stuck on the part of filtering the product by language:
add_filter( 'woocommerce_product_related_posts', 'custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query
) );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
if(pll_get_post_language(get_the_ID())){
//Not sure its the right approach for this..
}
endwhile;
}
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
How can I filter Woocommerce related product section by language?
Edit
So after a little bit of research and help in the comments I found out that 'lang' => 'en' argument does exist, but even when I use it, there is no change on related products language display.
Any ideas?
add_filter( 'woocommerce_product_related_posts', 'custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query,
'suppress_filters' => false
) );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
if(pll_get_post_language(get_the_ID())){
//Not sure its the right approach for this..
}
endwhile;
}
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
suppress_filters There is a way to make get_posts cache the results however, the suppress_filters option is true by default, but if you set it to false, the caching mechanisms inside WordPress will do their work, and results will be saved for later.
You can try this code:
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'meta_query' => $meta_query,
'lang' => 'en'
) );
if ($related_posts) {
foreach ($related_posts as $post) {
setup_postdata($post);
// something like <li><?php the_title(); ?></li>
}
}
wp_reset_postdata();
This code correctly returns code in selected language on my site
While working on a custom WordPress REST Api end point to fetch post by selected language or device language, this worked. See if it can help you out.
function mycustomplugin_posts($params) {
// get the url params
$page = $params->get_param('page') ? $params->get_param('page') : 0;
$per_page = $params->get_param('per_page') ? $params->get_param('per_page') : 10;
$offset = $params->get_param('offset') ? $params->get_param('offset') : 0;
$order = $params->get_param('order') ? $params->get_param('order') : 'desc';
$order_by = $params->get_param('order_by') ? $params->get_param('order_by') : 'date';
$lang = array_search($params->get_param('lang'),polylang_json_api_languages(), true) ? $params->get_param('lang') : pll_default_language();
$args = [
'post_type' => 'post',
'page' => $page,
'numberposts' => $per_page,
'offset' => $offset,
'order' => $order,
'orderby' => $order_by,
'tax_query' => [
[
'taxonomy' => 'language',
'field' => 'slug',
'terms' => $lang
]
]
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach($posts as $post) {
// Extract the post data
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['excerpt'] = e42_the_short_content($post->post_content, 300);
$data[$i]['slug'] = $post->post_name;
$data[$i]['date'] = $post->post_date;
$data[$i]['link'] = get_permalink($post->ID);
$data[$i]['author'] = get_the_author_meta('display_name', $post->post_author);
$data[$i]['categories'] = array();
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$data[$i]['featured_image']['medium'] = get_the_post_thumbnail_url($post->ID, 'medium');
$data[$i]['featured_image']['large'] = get_the_post_thumbnail_url($post->ID, 'large');
foreach(get_the_category($post->ID) as $category){
array_push($data[$i]['categories'],$category->term_id);
}
$i++;
}
// Create the response object
$response = new WP_REST_Response( $data );
// Add a custom status code
$response->set_status( 200 );
return $response;
}
/plugins/woocommerce/templates/single-product/related.php
Move this to child theme
yourtheme/woocommerce/single-product/related.php
And add the following line to the foreach loop
if (pll_current_language()!=pll_get_post_language($post_object->ID)) {
continue;
}
Basically if current language does not match product language we skip over it.

Wordpress: Show three random posts on every page refresh

In my WordPress, I am able to show one random post by using the below code:
global $post;
if ( post_type_exists( 'testimonial' ) ) {
$testimonial_query = new WP_Query( array(
'post_type' => 'testimonial',
'orderby' => 'rand',
'posts_per_page' => -1
) );
if ( $testimonial_query->have_posts() ) {
$random_int = rand( 0, $testimonial_query->post_count - 1 );
$post = $testimonial_query->posts[$random_int];
setup_postdata( $post );
// do something with post - e.g. the_excerpt(), the_content(), etc.
}
// Restore original post data
wp_reset_postdata();
}
Ref: https://barn2.co.uk/how-to-display-a-random-post-in-wordpress/
Help me to show 3 random posts by using the above method.
Can you try using in array property or WP_Query. A sample code is given belwo
$results = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE `post_type` = 'testimonial' ORDER BY RAND() LIMIT 3" );
$ids = array();
foreach($results as $$result){
$ids[] = $results->ID;
}
$args = array(
'post_type' => array( 'testimonial' ),
'orderby' => 'ASC',
'post__in' => $ids
);
$testimonial_query = new WP_Query( $args );

How can I see when a coupon is created in WooCommerce?

I am writing a custom plugin and I need to automatically send information about every newly created coupon. Until now, I can only choose a specific coupon by its name(e.g. 1234):
$coupon = new WC_Coupon("1234");
But I cannot seem to find how to get a coupon right after its created, without knowing its name, or at least how to get all of the available coupons. Can someone help?
May be this might help. Tested and it's working. This will return all coupons since coupons are saved as post_type shop_coupon.
$args = array(
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish',
);
$coupons = get_posts( $args );
Try to get using custom post type or directly mysql query.
1) Using mysql query
// Run a query on the postmeta table to get the id of every coupon that has the email in the customer_email restrictions
$couponlist = $wpdb->get_results("SELECT
`wp_postmeta`.`post_id`
FROM `wp_postmeta`
WHERE `wp_postmeta`.`meta_key` LIKE 'customer_email'
AND `wp_postmeta`.`meta_value` LIKE '%".$email."%'");
$couponarrayfinal = array( ); //Create an array of the ids so we can use wp_query to more quickly grab the data
// Add the ids to the array in a foreach loop
foreach( $couponlist as $key => $row) {
$value = $row->post_id;
$couponarrayfinal[] = $value ;
}
2) Using get_posts method
$arg = array(
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish');
$coupons_list = get_posts( $arg );
Try with this you will get the all the data
// WP_Query arguments
$args = array(
'post_type' => array('shop_coupon'),
'post_status' => array('publish'),
'posts_per_page' => '-1',
'order' => 'DESC',
'orderby' => 'id',
);
// The Query
$query = new WP_Query($args);
// The Loop
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// do something
$coupon = new WC_Coupon(get_the_ID());
$coupnCode = $coupon->code;
$coupnAmount = $coupon->amount;
$minAmount = wc_format_decimal($coupon->minimum_amount, 2);
$maximumAmount = wc_format_decimal($coupon->maximum_amount, 2);
$expire = $coupon->expiry_date;
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();

Wordpress - Meta query with post id

Can I add ID to the $args array? I need to check if the key value pair custom field exists for a particular post. Now it checks if the key value pair exists in any post. Or do I need to perform the query and then check for my value in the returned array?
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'ID' => $_POST['post_id'],
'meta_query' => array(
array(
'key' => 'claim',
'value' => $user_ID
)
)
);
// perform the query
$query = new WP_Query( $args );
$vid_ids = $query->posts;
if ( empty( $vid_ids ) ) {
add_post_meta( $_POST['post_id'], 'claim', $user_ID );
}else{
echo "sorry";
}
Please reference the Codex entry for post/page parameters for WP_Query().
You can pass single post id with this
$query = new WP_Query( array( 'p' => 7 ) );
If you want to pass multiple post id's use
$myarray = array('100', '222');
$args = array(
'post_type' => 'post',
'post__in' => $myarray
);
// The Query
$the_query = new WP_Query( $args );
Use get_post_meta to get custom field value for your object.
$claims=get_post_meta($ID,'claim');
$exists=false;
if(count($claims)>0)
{
foreach($claims as $claim)
{
if($claim==$user_ID)
{
$exists=true;
break;
}
}
}
if(!$exists)
{
add_post_meta( $_POST['post_id'], 'claim', $user_ID );
}

Categories