1 回答

TA貢獻(xiàn)1788條經(jīng)驗 獲得超4個贊
您基本上就在那里,只是錯過了正確位置的產(chǎn)品永久鏈接。
這里使用WP_Query:
// Get a random product (array with one value)
$random_product_id_array = get_posts( array(
'posts_per_page' => 1,
'post_type' => 'product',
'orderby' => 'rand',
'fields' => 'ids'
) );
// Get the first value from the array (the random product ID)
$random_product_id = reset($random_product_array);
// Output
echo '<a href="'.get_permalink($random_product_id).'"><img alt="mylink" src="https://www.mylink.com/images/promo-pic.png" class="img" width="150" height="70"></a>';
這次成功了。
或者您也可以使用WC_Product_query類似的替代:
// Get a random product (array with one value)
$random_product_id_array = wc_get_products( array(
'limit' => 1,
'orderby' => 'rand',
'return' => 'ids'
) );
// Get the first value from the array (the random product ID)
$random_product_id = reset($random_product_array);
// Output
echo '<a href="'.get_permalink($random_product_id).'"><img alt="mylink" src="https://www.mylink.com/images/promo-pic.png" class="img" width="150" height="70"></a>';
也以同樣的方式工作。
另外:您可以將該代碼嵌入到短代碼中,例如(使用WC_Product_query):
add_shortcode('random_img_link', 'display_random_img_link');
function display_random_img_link() {
// Get a random product (array with one value)
$query = wc_get_products( array(
'limit' => 1,
'orderby' => 'rand',
'return' => 'ids'
) );
// Here define your image link
$image_src = 'https://www.mylink.com/images/promo-pic.png';
ob_start(); // Start buffering
echo '<a href="'.get_permalink(reset($query)).'"><img alt="mylink" src="'.$image_src.'" class="img" width="150" height="70"></a>';
return ob_get_clean(); // return buffered content
}
或者(使用WP_Query):
add_shortcode('random_img_link', 'display_random_img_link');
function display_random_img_link() {
// Get a random product (array with one value)
$query = get_posts( array(
'posts_per_page' => 1,
'post_type' => 'product',
'orderby' => 'rand',
'fields' => 'ids'
) );
// Here define your image link
$image_src = 'https://www.mylink.com/images/promo-pic.png';
ob_start(); // Start buffering
echo '<a href="'.get_permalink(reset($query)).'"><img alt="mylink" src="'.$image_src.'" class="img" width="150" height="70"></a>';
return ob_get_clean(); // return buffered content
}
代碼位于活動子主題(或活動主題)的functions.php 文件中。經(jīng)過測試并有效。
用法: [random_img_link]
- 1 回答
- 0 關(guān)注
- 181 瀏覽
添加回答
舉報