חיפוש ]

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

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

הימנעו משימוש ב-WP_Query או שאילתות ישירות למסד הנתונים עבור מוצרי ווקומרס. מבנה מסד הנתונים של ווקומרס משתנה בין גירסאות (לאחרונה עם HPOS – High-Performance Order Storage), ושאילתות ישירות עלולות להישבר לאחר עדכונים.

דוגמאות שימוש ב-wc_get_products ו-WC_Product_Query

הנה מספר דוגמאות נפוצות. ההערות בקוד מסבירות מה כל שאילתא מבצעת:

// 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: מספר מקסימלי של תוצאות, או -1 ללא הגבלה.

// 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 foundn';
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(
    'tax_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 כדי להוסיף תמיכה בפרמטרים משלכם:

/**
 * 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' ) );

מאז ווקומרס 8.2, HPOS (High-Performance Order Storage) מופעל כברירת מחדל בהתקנות חדשות. בעוד HPOS משפיע בעיקר על הזמנות (לא מוצרים), זוהי תזכורת שכבת הנתונים של ווקומרס מתפתחת עם הזמן. שימוש ב-wc_get_products() במקום שאילתות ישירות מבטיח תאימות הקוד שלכם.

שאלות נפוצות

שאלות נפוצות על שליפת מוצרים בווקומרס:

מה ההבדל בין wc_get_products() לבין WC_Product_Query?
הן זהות במהותן. wc_get_products() היא פונקציית wrapper שיוצרת WC_Product_Query מאחורי הקלעים. השתמשו ב-wc_get_products() לשאילתות חד-פעמיות פשוטות, וב-WC_Product_Query כשצריכים לשנות את אובייקט השאילתא לפני הפעלתו (למשל, הגדרת פרמטרים דינמיים עם מתודת set()).
האם אפשר להשתמש ב-WP_Query לשליפת מוצרי ווקומרס?
למרות ש-WP_Query עם post_type => 'product' עובד טכנית, זה לא מומלץ. ווקומרס עשוי לשנות את מבנה אחסון הנתונים בין גירסאות (כפי שנעשה עם HPOS להזמנות). שימוש ב-wc_get_products() מבטיח שהשאילתות שלכם יישארו תואמות לעדכוני ווקומרס עתידיים.
איך שולפים את כל המוצרים בקטגוריה מסוימת?
העבירו את ה-slug של הקטגוריה בפרמטר category: wc_get_products( array( 'category' => array( 'shirts' ), 'limit' => -1 ) ). הגדירו limit ל--1 כדי לשלוף את כל המוצרים התואמים ללא הגבלה.
איך שואלים על מוצרים לפי שדות מותאמים (meta)?
השתמשו בפילטר woocommerce_product_data_store_cpt_get_products_query כדי לרשום משתנה שאילתא מותאם, ואז העבירו אותו ל-wc_get_products(). בתוך ה-callback של הפילטר, הוסיפו מערך meta_query המכוון למפתח ה-meta המותאם שלכם.
האם wc_get_products() מחזירה אובייקטים או מזהים (IDs)?
כברירת מחדל היא מחזירה מערך של אובייקטי WC_Product. כדי לקבל רק מזהי מוצרים (מהיר יותר לשאילתות גדולות), הגדירו 'return' => 'ids' במערך הארגומנטים.

סיכום

wc_get_products() ו-WC_Product_Query הן הדרך המומלצת לשליפת מוצרים בווקומרס. הן תומכות במגוון רחב של פרמטרים לסינון לפי סטטוס, סוג, קטגוריה, תגית, מחיר, מלאי, תאריכים ועוד. לצרכי סינון מותאמים, הפילטר woocommerce_product_data_store_cpt_get_products_query מאפשר להוסיף משתני שאילתא משלכם תוך שמירה על תאימות עתידית של הקוד.

דיון ותגובות
0 תגובות  ]

השאירו תגובה

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

Savvy WordPress Development official logo