Support

Account

Home Forums Front-end Issues posts_clauses drop ACF get_field function

Solved

posts_clauses drop ACF get_field function

  • Hello
    I try to use function for order by stock status in my store catalog but this code drop ACF get_field() function
    when function on, get_field return only ID of post (https://skr.sh/sGyfgZ3GwaP)
    and when function off, all right, get_field return array (https://skr.sh/sGyHPC9UUOw)
    please help me to find a reason

    add_filter( 'posts_clauses', 'order_by_stock_status', 2000 );
    function order_by_stock_status( $posts_clauses ) {
    global $wpdb;
    
    if ( is_woocommerce() && ( is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy() ) ) {
        $posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta istockstatus ON ( $wpdb->posts.ID = istockstatus.post_id ) ";
        $posts_clauses['orderby'] = " istockstatus.meta_value ASC, " . $posts_clauses['orderby'];
        $posts_clauses['where'] = " AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '' " . $posts_clauses['where'];
    }
    return $posts_clauses;
    }
  • Your filter on the hook posts_clauses affects every query that is done, in this case it will happen on any page load where this is true

    
    if ( is_woocommerce() && ( is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy() ) ) {
    

    and this will effect ACF queries to get values of fields.

    I cannot tell you how to correct this, when I’m altering a WP query I generally do this by using a pre_get_posts action and for example if I want to change the orderby value I do it by altering the main query, not by adding clauses to the query.

  • Its work for me

    add_filter('posts_clauses', 'sem_order_by_stock_status');
    function sem_order_by_stock_status($posts_clauses) {
        global $wpdb;
        // only change query on WooCommerce loops when ACF fields are not requested in the WHERE statement
        if (!is_acf_request($posts_clauses['where']) && is_woocommerce() && (is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy())) {
            $posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id) ";
            $posts_clauses['orderby'] = " istockstatus.meta_value ASC, " . $posts_clauses['orderby'];
            $posts_clauses['where'] = " AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '' " . $posts_clauses['where'];
        }
        return $posts_clauses;
    }
    
    function is_acf_request($text){
    	if (strpos($text, 'acf-field'))
    		return true;
    	return false;
    }
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.