WordPress Query: Combining 'in_stock' and 'sortby' Conditions
To\sadd\sthe\srelation\sto\sthe\smeta_query\scondition\sonly\swhen\sthe"sortby"\skey\sis\spresent,\syou\scan\smodify\syour\scode\sas\sfollows:\n\nphp\n\$idarray\s=\sarray();\n\$data\s=\sarray(\n\t'post_type'\s=>\s'qqproduct',\n\t'post_status'\s=>\s'publish',\n\t'orderby'\s=>\s'DATE',\n\t'order'\s=>\s'DESC',\n\t'posts_per_page'\s=>\s$per_page,\n\t'paged'\s=>\s$paged,\n);\n\n\$meta_query\s=\sarray();\s//\sInitialize\sthe\smeta_query\sarray\soutside\sthe\sloop\n\nforeach\s($results\sas\s$key\s=>\s$value)\s{\n\tif\s($key\s==\s'qcat')\s{\n\t if\s($value)\s{\n\t if\s($value\s!=\s'all')\s{\n\t $cat_query\s=\sarray('relation'\s=>\s'OR');\n\t $catos\s=\sexplode(",",\s$value);\n\t foreach\s($catos\sas\s$cato)\s{\n\t $cat_query[]\s=\s[\n\t 'taxonomy'\s=>\s'qqcpat',\n\t 'field'\s=>\s'term_id',\n\t 'terms'\s=>\s$cato,\n\t ];\n\t $keys[]\s=\s$cato;\n\t }\n\t $data['tax_query']\s=\sarray(array($cat_query));\n\t }\n\t }\n\t}\selseif\s($key\s==\s'offset')\s{\n\t}\selseif\s($key\s==\s'in_stock')\s{\n\t $meta_query[]\s=\sarray(\n\t 'key'\s=>\s'qqp_qty',\n\t 'value'\s=>\sarray('0'),\n\t 'compare'\s=>\s'>'\n\t );\n\t $keys[]\s=\s'in_stock';\n\t}\selseif\s($key\s==\s'sortby')\s{\n\t if\s($value\s==\s'newest')\s{\n\t $data['orderby']\s=\s'DATE';\n\t }\selseif\s($value\s==\s'discount')\s{\n\t $meta_query[]\s=\sarray(\n\t 'key'\s=>\s'qqpd_price',\n\t 'value'\s=>\s'',\n\t 'compare'\s=>\s'NOT\sIN'\n\t );\n\t }\selseif\s($value\s==\s'review')\s{\n\t $meta_query[]\s=\sarray(\n\t 'key'\s=>\s'qq_product_rate',\n\t 'value'\s=>\s'',\n\t 'compare'\s=>\s'NOT\sIN'\n\t );\n\t $data['orderby']\s=\s'meta_value_num';\n\t }\selseif\s($value\s==\s'topsale')\s{\n\t $meta_query[]\s=\sarray(\n\t 'key'\s=>\s'qq_total_views',\n\t 'value'\s=>\s'',\n\t 'compare'\s=>\s'NOT\sIN'\n\t );\n\t $data['orderby']\s=\s'meta_value_num';\n\t }\n\t $keys[]\s=\s$value;\n\t}\n}\n\n\nif\s(!empty($meta_query))\s{\n\t$meta_query['relation']\s=\s'OR';\s//\sAdd\sthe\srelation\swhen\smeta_query\sis\snot\sempty\n\t$data['meta_query']\s=\s$meta_query;\n}\n\n\nThis\scode\swill\sadd\sthe\srelation\sparameter\sto\sthe\smeta_query\sarray\sonly\swhen\sthere\sare\sconditions\spresent\sfor\sthe"sortby"\skey.
原文地址: https://www.cveoy.top/t/topic/qd9L 著作权归作者所有。请勿转载和采集!