我正在使用Wordpress和Woocommerce,并且试图添加一个链接到随机产品的自定义按钮,以便每次有人单击链接时,它们都会带到另一个产品单页。
对此,任何跟踪都会受到赞赏。
答案 0 :(得分: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]");