/** * Search product data for a term and return ids. * * @param string $term * @param string $type of product * @param bool $include_variations in search or not * @return array of ids */ public function search_products($term, $type = '', $include_variations = false) { global $wpdb; $search_fields = array_map('wc_clean', apply_filters('woocommerce_product_search_fields', array('_sku'))); $like_term = '%' . $wpdb->esc_like($term) . '%'; $post_types = $include_variations ? array('product', 'product_variation') : array('product'); $type_join = ''; $type_where = ''; if ($type) { if (in_array($type, array('virtual', 'downloadable'))) { $type_join = " LEFT JOIN {$wpdb->postmeta} postmeta_type ON posts.ID = postmeta_type.post_id "; $type_where = " AND ( postmeta_type.meta_key = '_{$type}' AND postmeta_type.meta_value = 'yes' ) "; } } $product_ids = $wpdb->get_col($wpdb->prepare("\n\t\t\t\tSELECT DISTINCT posts.ID FROM {$wpdb->posts} posts\n\t\t\t\tLEFT JOIN {$wpdb->postmeta} postmeta ON posts.ID = postmeta.post_id\n\t\t\t\t{$type_join}\n\t\t\t\tWHERE (\n\t\t\t\t\tposts.post_title LIKE %s\n\t\t\t\t\tOR posts.post_content LIKE %s\n\t\t\t\t\tOR (\n\t\t\t\t\t\tpostmeta.meta_key = '_sku' AND postmeta.meta_value LIKE %s\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\tAND posts.post_type IN ('" . implode("','", $post_types) . "')\n\t\t\t\tAND posts.post_status = 'publish'\n\t\t\t\t{$type_where}\n\t\t\t\tORDER BY posts.post_parent ASC, posts.post_title ASC\n\t\t\t\t", $like_term, $like_term, $like_term)); if (is_numeric($term)) { $product_ids[] = absint($term); $product_ids[] = get_post_parent($term); } return wp_parse_id_list($product_ids); }
/** * Retrieve parents of a post. * * @param null|int|WP_Post $post [Optional] Post ID or post object, or null to use the global post. * * @return array Parent post objects or an empty array if none are found. */ function get_post_parents($post = null) { if (!$post || !$post instanceof WP_Post) { $post = get_post($post); } $parents = array(); if (!$post || empty($post->ID) || empty($post->post_parent) || $post->post_parent == $post->ID) { return $parents; } $parent = get_post($post->post_parent); while ($parent) { $parents[] = $parent; $parent = get_post_parent($parent); } return $parents; }