显示在Woocommerce中链接到随机产品的自定义按钮

问题描述 投票:0回答:1

[我正在使用Wordpress和Woocommerce,我试图添加一个链接到随机产品的自定义按钮,以便每次有人单击链接时,都会将他们带到另一个产品的单个页面。

php wordpress random woocommerce product
1个回答
0
投票

更新:下面的示例将显示一个链接到随机产品的按钮:

// Get a random product id (array)
$random_product_array = get_posts( array( 'posts_per_page' => 1, 'post_type' => 'product', 'orderby' => 'rand', 'fields' => 'ids' ) );
$random_product_id    = reset($random_product_array); // Get the random product ID

// Display a linked button to the random product
echo '<a href="' . get_permalink($random_product_id) . '" class="button alt">' . __("Go to a random product") . '</a>';

您甚至可以将其嵌入到类似如下的简码函数中:>

add_shortcode( 'random_product_button', 'shortcode_random_product_button' );
function shortcode_random_product_button( $atts ) {
    // Get a random product id (array)
    $random_product_array = get_posts( array( 'posts_per_page' => 1, 'post_type' => 'product', 'orderby' => 'rand', 'fields' => 'ids' ) );
    $random_product_id    = reset($random_product_array); // Get the random product ID

    // Display a linked button to the random product
    return '<a href="' . get_permalink($random_product_id) . '" class="button alt">' . __("Go to a random product") . '</a>';
}

代码进入您的活动子主题(或活动主题)的function.php文件。经过测试和工作。

用法:

1)在页面或帖子内容文本编辑器内((或文本小部件)

[random_product_button]

2)在php模板或代码上:

echo do_shortcode("[random_product_button]");
© www.soinside.com 2019 - 2024. All rights reserved.