Search

הדרך הנכונה לשלוף מוצרים של ווקומרס בתבנית שלכם

הפונקציות wc_get_products ו WC_Product_Query מספקות את הדרך הסטנדרטית והנכונה לשליפת מוצרים כאשר עובדים עם ווקומרס. זו הדרך הנכונה מכיוון והיא לא תשבר מפאת שינויים עתידיים במסד הנתונים בעקבות גירסאות חדשות של ווקומרס.

השימוש ב WP_Queries או שאילתות למסד הנתונים סופן להשבר בעתיד מכיוון ומידע מסויים וטבלאות כאלו ואחרות עוברות שינויים בגירסאות חדשות לטובת ביצועים טובים יותר.

אז כמפתחי תבניות וורדפרס ותוספים, הדרך הנכונה לשליפה של מספר מוצרים היא שימוש ב wc_get_products ו WC_Product_Query ואלו זהות במהותן לפונקציות get_posts ו WP_Query השייכות לליבה וורדפרס. וגם במקרה זה כמובן שאתם יכולים להשתמש במערך של ארגומנטים המגדירים את הקריטריונים של השאילתא או החיפוש.

הפונקציות  wc_get_products ו WC_Product_Query

הנה מספר דוגמאות לשימוש באותן פונקציות, נאמר באופן כללי לגבי פוסט זה, שכנראה ומבט ב comments שבקוד עצמו יסביר טוב יותר מה הקוד מבצע…

// Get downloadable products created in the year 2016.
$products = wc_get_products( array(
    'downloadable' => true,
    'date_created' => '2016-01-01...2016-12-31`,
) );
// Get 10 most recent product IDs in date descending order.
$query = new WC_Product_Query( array(
    'limit' => 10,
    'orderby' => 'date',
    'order' => 'DESC',
    'return' => 'ids',
) );
$products = $query->get_products();
// Get products containing a specific SKU.
// Does partial matching, so this will get products with SKUs "PRDCT-1", "PRDCT-2", etc.
$query = new WC_Product_Query();
$query->set( 'sku', 'PRDCT' );
$products = $query->get_products();

WC_Product_Query – מתודות

אלו המתודות שניתן להשתמש בהן עם הפונקציה WC_Product_Query, את ההסבר אשאיר באנגלית במקרה זה:

  • get_query_vars() – Get an array of all of the current query variables set on the query object.
  • get( string $query_var, mixed $default = " ) – Get the value of a query variable or the
    default if the query variable is not set.
  • set( string $query_var, mixed $value ) – Set a query variable to a value.
  • get_products() – Get all products matching the current query variables.

פרמטרים

כללי

status – מקבלת string או array of strings: אחד או יותר מהאפשרויות הבאות:  'draft', 'pending', 'private', 'publish' או custom status.

// Get draft products.
$args = array(
    'status' => 'draft',
);
$products = wc_get_products( $args );

type  – מקבלת string או array of strings: אחד או יותר מהאפשרויות הבאות: 'external', 'grouped', 'simple', 'variable' או custom type.

// Get external products.
$args = array(
    'type' => 'external',
);
$products = wc_get_products( $args );

include – מקבלת array of integers: הוסיפו אך ורק מזהים של מוצרים אשר יכללו בשאילתא במערך זה (product ID's)

// Get external products limited to ones with specific IDs.
$args = array(
    'type' => 'external',
    'include' => array( 134, 200, 210, 340 ),
);
$products = wc_get_products( $args );

exclude – מקבלת array of integers: הוסיפו במערך זה  אך ורק מזהים של מוצרים אשר לא יכללו בשאילתא (product ID's).

// Get products that aren't the current product.
$args = array(
    'exclude' => array( $product->get_id() ),
);
$products = wc_get_products( $args );

parent – מקבלת integer: המזהה (ID) של מוצר האב.

// Get products with a specific parent.
$args = array(
    'parent' => 20,
);
$products = wc_get_products( $args );

parent_exclude  – מקבלת array of integers: הוסיפו במערך זה אך ורק מזהים של מוצרי אב אשר לא יכללו בשאילתא (product ID's).

// Get products that don't have parent IDs of 20 or 21.
$args = array(
    'parent_exclude' => array( 20, 21 ),
);
$products = wc_get_products( $args );

limit  – מקבלת integer:

Accepts an integer: Maximum number of results to retrieve or -1 for unlimited.

// Get latest 3 products.
$args = array(
    'limit' => 3,
);
$products = wc_get_products( $args );

page – מקבלת integer: עמוד התוצאות עליו תעבוד הפונקציה. אינו רלוונטי אם הפרמטר offset בשימוש.

// First 3 products.
$args = array(
    'limit' => 3,
    'page'  => 1,
);
$page_1_products = wc_get_products( $args );

// Second 3 products.
$args = array(
    'limit' => 3,
    'page'  => 2,
);
$page_2_products = wc_get_products( $args );

paginate – אחראית לימוד ממוספר (pagination) – מקבלת משתנה בוליאני, True  או False. ברירת מחדל היא False.

// Get products with extra info about the results.
$args = array(
    'paginate' => true,
);
$results = wc_get_products( $args );
echo $results->total . ' products found\n';
echo 'Page 1 of ' . $results->max_num_pages . '\n';
echo 'First product id is: ' . $results->products[0]->get_id() . '\n';

offset – מקבלת integer: ה offset לתוצאות המוצרים.

// Get second to fifth most-recent products.
$args = array(
    'limit' => 4,
    'offset' => 1
);
$products = wc_get_products( $args );

order – מקבלת string: הפרמטרים 'DESC' או 'ASC'. השתמשו יחד עם 'orderby'. ברירת מחדך 'Desc'.

// Get most recently modified products.
$args = array(
    'orderby' => 'modified',
    'order' => 'DESC',
);
$products = wc_get_products( $args );

orderby – מקבלת string: הפרמטרים הינם 'none', 'ID', 'name', 'type', 'rand', 'date', 'modified'. ברירת מחדל 'date'.

// Get some random products.
$args = array(
    'orderby' => 'rand',
);
$products = wc_get_products( $args );

return – מקבלת string: הפרמטרים הינם 'ids' או 'objects'. ברירת מחדל 'objects'.

// Get product ids.
$args = array(
    'return' => 'ids',
);
$products = wc_get_products( $args );

מוצר

sku – מקבלת string: בודק האם ה string קיים ב SKU (מק״ט) של המוצר.

// Get products with "PRDCT" in their SKU (e.g. PRDCT-1 and PRDCT-2).
$args = array(
    'sku' => 'PRDCT',
);
$products = wc_get_products( $args );

tag – מקבלת מערך: הגבלת התוצאות למוצרים בעלי תגית / תגיות מסויימות לפי המזהה של התגיות (slug).

// Get products with the "Excellent" or "Modern" tags.
$args = array(
    'tag' => array( 'excellent', 'modern' ),
);
$products = wc_get_products( $args );

category – מקבלת מערך: הגבלת התוצאות למוצרים בעלי קטגוריה / קטגוריות מסויימות לפי המזהה של הקטגוריות (slug).

// Get shirts.
$args = array(
    'category' => array( 'shirts' ),
);
$products = wc_get_products( $args );

weight, length, width, height – מקבלת float: המימדים שעל המוצרים להיות.

// Get products 5.5 units wide and 10 units long.
$args = array(
    'width' => 5.5,
    'length' => 10,
);
$products = wc_get_products( $args );

price, regular_price, sale_price – מקבלת float: המחיר לפיו התוצאות יתקבלו.

// Get products that currently cost 9.99.
$args = array(
    'price' => 9.99,
);
$products = wc_get_products( $args );

total_sales – מקבלת integer: שליפת המוצרים עם כמות מסויימת של מכירות.

// Get products that have never been purchased.
$args = array(
    'total_sales' => 0,
);
$products = wc_get_products( $args );

virtual, downloadable, featured, sold_individually, manage_stock, reviews_allowed – מקבלת משתנה בוליאני: הגבלת התוצרות לפי מוצרים בעלי הגדרות או פיטצ׳רים ספציפיים.

// Get downloadable products that don't allow reviews.
$args = array(
    'downloadable' => true,
    'reviews_allowed' => false,
);
$products = wc_get_products( $args );

backorders – מקבלת string: האפשרויות הינם 'yes', 'no', or 'notify'.

// Get products that allow backorders.
$args = array(
    'backorders' => 'yes',
);
$products = wc_get_products( $args );

visibility – מקבלת string: האפשרויות הינם 'visible', 'catalog', 'search', או 'hidden'.

// Get products that show in the catalog.
$args = array(
    'visibility' => 'catalog',
);
$products = wc_get_products( $args );

stock_quantity – מקבלת integer: הכמות של המוצר במלאי.

// Get products that only have one left in stock.
$args = array(
    'stock_quantity' => 1,
);
$products = wc_get_products( $args );

stock_status – מקבלת string: מצב המוצרים במלאי – 'outofstock' או 'instock'.

// Get out of stock products.
$args = array(
    'stock_status' => 'outofstock',
);
$products = wc_get_products( $args );

tax_status – מקבלת string: האפשרויות הינם -'taxable', 'shipping', או 'none'.

// Get taxable products.
$args = array(
    'stock_status' => 'taxable',
);
$products = wc_get_products( $args );

tax_class – מקבלת string.

// Get products in the "Reduced Rate" tax class.
$args = array(
    'tax_class' => 'reduced-rate',
);
$products = wc_get_products( $args );

shipping_class – מקבלת string או array of strings.

// Get products in the "Bulky" shipping class.
$args = array(
    'shipping_class' => 'bulky',
);
$products = wc_get_products( $args );

download_limit, download_expiry – מקבלת integer: ההגבלה של כמות ההורדות כאשר 1- הינו ללא הגבלה.

// Get products with unlimited downloads.
$args = array(
    'download_limit' => -1,
);
$products = wc_get_products( $args );

average_rating – מקבלת float: הדירוג הממוצע של המוצר.

// Get products with all 5-star ratings.
$args = array(
    'average_rating' => 5.0,
);
$products = wc_get_products( $args );

review_count – מקבלת integer: כמות ה reviews עבור המוצר.

// Get products with 1 review.
$args = array(
    'review_count' => 1,
);
$products = wc_get_products( $args );

תאריך

date_created, date_modified, date_on_sale_from, date_on_sale_to – מקבלת string: מוצרים לפי תאריך כאשר הפורמט הינו YYYY-MM-DD או TIMESTAMP.

// Get downloadable products created in the year 2016.
$products = wc_get_products( array(
    'downloadable' => true,
    'date_created' => '2016-01-01...2016-12-31`,
) );

הוספת פרמטר משל עצמכם

ניתן להוסיף תמיכה בפרמטרים משלכם. בכדי לעשות זאת עליכם להשתמש בהוק בשם woocommerce_product_data_store_cpt_get_products_query ולפלטר את ה query:

/**
 * Handle a custom 'customvar' query var to get products with the 'customvar' meta.
 * @param array $query - Args for WP_Query.
 * @param array $query_vars - Query vars from WC_Product_Query.
 * @return array modified $query
 */
function handle_custom_query_var( $query, $query_vars ) {
	if ( ! empty( $query_vars['customvar'] ) ) {
		$query['meta_query'][] = array(
			'key' => 'customvar',
			'value' => esc_attr( $query_vars['customvar'] ),
		);
	}

	return $query;
}
add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handle_custom_query_var', 10, 2 );

והשימוש מתבצע כך:

$products = wc_get_products( array( 'customvar' => 'somevalue' ) );

 

רועי יוסף
רועי יוסף

מפתח אתרים ותבניות וורדפרס יעודייות על בסיס עיצוב. אוהב טיפוגרפיה, צבעים ומה שבינהם ומכוון לספק אתרים רספונסיבים עם ביצועים גבוהים, מותאמים למנועי חיפוש ובעלי קוד ולידי, סמנטי ונקי.

0 תגובות...

תגובה חדשה

ניווט מהיר

Up!
לבלוג