Custom Query Filter for Elementor Posts by relationship field (ACF) - wordpress

I have a custom post type setup called 'Artists'. Each Single Artist is a page (artist profile if you wish), has a list of products that are associated with that artist via the relationship field type through Advanced Custom Fields (ACF). I need the products to be displayed within their categories on the artist page. So within Elementor I need to specify a 'Query Filter ID' to simply split the products into categories.
What I have tried so far
I am trying to display only products from a certain category in a list via a custom query as I need to generate a Query ID.
I've been trying a bunch of different ways to do this but now I'm at a loss. The latest code I have is here... what am I missing?
/** Product category 'SOFTWARE' **/
add_filter( 'software_product', 'product_category_software' );
function product_category_software( $variable ) {
$query_args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'software',
),
),
);
return $variable;
}

Answer
You need to use this
https://developers.elementor.com/custom-query-filter/#Using_the_Custom_Filter
arbitrary_name_query_id - the QUERY ID that you fill in the Elementor field,
the code to be placed within functions.php:
add_action( 'elementor/query/arbitrary_name_query_id', function( $query ) {
$meta_query = $query->get( 'meta_query' );
$meta_query[] = [
'key' => 'acf_key', // put ACF relationship field name
'value' => get_the_ID(),
'compare' => '=',
];
$query->set( 'meta_query', $meta_query );
} );
Regarding to the given code
First of all, as Wordpress Documentation on filters says:
They (i.e. filters) provide a way for functions to modify data of other
functions.
Which means that the filter function, in this case it's product_category_software, receives data that subsequntly modifies and returns it back:
add_filter( 'software_product', 'product_category_software' );
function product_category_software( $variable ) { // receive $variable
/**
* Modify $variable here
*/
return $variable; // return modified $variable
}
In your case product_category_software doesn't modify what receives, but introduces new peace of data $query_args which makes no sence, since it is not going to be returned.
Secondly, the first argument of the add_filter function should be an existent filter name, the software_product is not.
Thirdly, the correct name of the taxonomy of product categories is product_cat.
Getting products from a certain category
Aproach #1 Modfying main query with pre_get_posts
function your_arbitrary_name( $query ) { // receive
if ( ! is_admin() && is_post_type_archive( 'product' ) && $query->is_main_query() ) {
$tax_query = array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array('software'),
)
);
$query->set( 'meta_query', $tax_query ); // modify
}
return $query; // and return
}
add_action( 'pre_get_posts', 'your_arbitrary_name', 20 );
Aproach #2 Use wc_get_products or WC_Product_Query
Example, use in your Controller or even in the template:
$args = array(
'category' => array( 'software' ),
);
$products = wc_get_products( $args );
Read the Docs about wc_get_products and WC_Product_Query

Related

Woocommerce display Reviews and Ratings by tags

I am building an e-commerce website and I have installed the following plugin (Customer reviews for Commerce - https://wordpress.org/plugins/customer-reviews-woocommerce/) for Reviews and Ratings of Orders once user completes the order process.
However, the nature of the products we deal with (like fabrics, dresses, sarees etc.) will run out of stock and the same product will not be available again to procure. So, I would want to display the reviews and ratings of old orders using the 'tags' of the products which the order had (For this reason, I would like to have review at order line item). Further, the new product page should fetch the reviews and ratings using it's own tags from old orders which had the same tags.
Any guidance would be helpful in this matter!
To approach this problem, first thing to do is to get all tags associated with a given product into an array. And then, WP_Comments_Query needs to be queried with the array of product ids generated in the first step.
Here is a snippet with the above mentioned approach.
function get_reviews_by_tags(){
global $product;
$productid = $product->get_id();
// get all product_tags of the current product in an array
$current_tags = get_the_terms( $productid, 'product_tag' );
//only start if we have some tags
if ( $current_tags && ! is_wp_error( $current_tags ) ) {
//get all related product ids mapped by tags array we created earlier
$relatedproductids_by_tags = get_posts( array(
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'publish',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_tag',
'field' => 'term_id',
'terms' => $current_tags,
'operator' => 'IN'
)
),
));
// create a wp comment query object as wc uses comments for reviews
$reviews_args = array(
'post__in' => $relatedproductids_by_tags
);
$reviews_query = new WP_Comment_Query;
$reviews = $reviews_query->query( $reviews_args );
if ( !empty( $reviews ) ) {
foreach ( $reviews as $review ) {
echo '<p>' . $review->comment_content . '</p>';
}
} else {
echo 'No reviews found.';
}
}
add_action( 'woocommerce_after_single_product_summary', 'get_reviews_by_tags', 10, 2 );
}
The above code does not consider any modifications being made by the plugin you mentioned in your question. Also, please note that this code is for fetching and displaying reviews as mentioned in your question. This is not for creating reviews.

Get product variation ID from variation SKU [duplicate]

I'm working on a separate templates page, which page gets woocommece product sku using custom field of wordpress post. i need to get product id of that sku for create woocommece object and do further things, here is my code.
global $woocommerce;
//this return sku (custom field on a wordpress post)
$sku=get_field( "product_sku" );
if($sku!=''){
//need to create object, but using sku cannot create a object,
$product = new WC_Product($sku);
echo $product->get_price_html();
}
is there way to get product id before create object, then i can pass the product id to WC_Product class constructor and create object.thank you
WooCommerce 2.3 finally adds support for this in core.
If you are using this version, you can call
wc_get_product_id_by_sku( $sku )
You can use this function (found here). Google is your friend!
function get_product_by_sku( $sku ) {
global $wpdb;
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
if ( $product_id ) return new WC_Product( $product_id );
return null;
}
WooCommerce product is a special post type. Because of this WP_Query might be used to find product by SKU and other parameters. This might be used as an alternative when you need to restrict your search by some other criterias.
For example you might want to specify language if you use Polylang (or other plugins) for site translations. Or you can restrict search by product type.
They do direct SQL query in the WooCommerce method get_product_id_by_sku which I think is perfectly fine in many cases. But might not work if you use translations, it will return random product but not the one in current language.
Example code to find product by SKU using WP_Query (with restriction by product type and language):
public function find( string $lang, string $sku ) {
$query = [
'lang' => $lang,
'post_type' => 'product',
'meta_query' => [
[
'key' => '_sku',
'value' => $sku,
'compare' => '='
]
],
'tax_query' => [
[
'taxonomy' => 'product_type',
'terms' => [ 'grouped' ],
'field' => 'name',
]
]
];
$posts = ( new WP_Query() )->query( $query );
return count( $posts ) > 0 ? $posts[0] : null;
}

Wordpress custom template for feed in specific categories

I'm trying to use a custom template for a podcast feed. My podcast is a standard post defined by its category. I would like to access it via the standard url: mysite.com/category/podcast1/feed
I can get the new template to work, but the code below removes the standard category filtering so I get posts from all categories with the new template. When I try to add a new query and limit the posts it overrides all queries. When I try to limit the query with $query->is_feed then it doesn't work either. When I var_dump the $query, the pre_get_posts hook is running the query twice, the first with is_feed as true and the second with false. The last query it runs is 'showposts'. Here's my code:
function my_custom_rss($query) {
if ( 'podcast1' === get_query_var( 'category_name' ) ) {
get_template_part( 'feed', 'podcast' );
}
else {
get_template_part( 'feed', 'rss2' );
}
}
remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'my_custom_rss', 10, 1 );
function feed_category_query($query)
{
if ($query->is_feed && $query->is_category() ) {
$tax_query = array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => get_cat_ID('podcast1')
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => get_cat_ID('podcast2')
),
);
$query->set('post_type','post');
$query->set('orderby','post_date');
$query->set('order','DESC');
$query->set('tax_query', $tax_query);
return $query;
}
}
add_filter('pre_get_posts','feed_category_query');
How can I limit the query to only the feed, or reinstate the the standard query that I suppose was removed with remove_all_acions('do_feed_rss2')?
I'd rather do all of this with a custom plugin, but right now, whatever works. Thanks for the help.
I found the issue in my new feed template. At the top I had:
$posts = query_posts('showposts=' . $postCount);
this was creating the second query that was overriding my pre_get_posts query.

Custom filter in admin post list makes search form unvisible

I want to filter the posts list in admin area by custom field key/value :
So, I do :
add_filter( 'pre_get_posts', 'my_admin_posts_filter' );
function my_admin_posts_filter( $query )
{
global $pagenow;
$metaquery = array(
'relation' => 'AND',
array(
'key' => 'categorie_de_produit',
'value' => array(23559),
'compare' => 'IN'
));
set_query_var( 'meta_query', $metaquery );
//idem : $query->set( 'meta_query', $metaquery );
}
when the value exist, the results are ok. I have 3 results and the search form is visible:
But if the value (ex : 'value' => array(54644848486486486) ) doesn’t exist, the results are also correct (no result but it’s normal) but the search form is not visible…
Why the search form disappears?
It's default of Wordpress, if there have no post, it's will hide search form.
LOGIC = If doesn't have any post, what want search? :)

How to create/modfiy WP_Query to search in post title OR custom field?

I need to modify or create a WP_Query that will search for a search term in both the post title OR a custom field (called 'my_field').
I have been reading and trying for hours, but I am right back to this code (below) which, alas, only searches in 'my_field' and does not take the post_title into account.
function my_pre_get_posts_2( $query ) {
if ( is_admin() && $query->is_main_query() && $query->query['post_type'] === 'post' && isset($query->query['s']) ) {
$search_word = $query->query['s'];
$args = array(
//'s' => $search_word, //If I include this line, the WP query seems to AND post_title and my_field. If I comment out this line, the WP query only searches in my_field. (I need WP to OR post_title and my_field.)
'post_type' => 'post',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'my_field',
'value' => $search_word,
'compare' => 'IN'
),
array(
'key' => 'post_title',
'value' => $search_word,
'compare' => 'IN',
)
)
);
//$query = new WP_Query( $args ); //Need to modify the existing WP_Query
$query->init();
$query->parse_query($args);
}
}
add_action( 'pre_get_posts', 'my_pre_get_posts_2' );
The reason I need to do this is because I need to modify the behaviour of the the 'Search Posts' button in the 'All Posts' (admin) page so that whatever the admin user searches for, it will return the posts that have a matching post title OR my_field value.
To do an OR search, I tried merging two separate WP_Query results as shown here - https://wordpress.stackexchange.com/questions/55519/can-i-merge-2-new-wp-queryvariable-s - in guidod's answer. That wasn't a great solution though, and resulted in erratic behaviour.
The correct solution I found was to modify the query using the WP Custom Query as shown in the code (which requires some modifications) here - http://codex.wordpress.org/Custom_Queries .

Resources