两种在wordpress网站首页调用woocommerce产品的方法

要在WordPress网站首页调用WooCommerce产品,您可以使用以下方法:

方法1:使用WooCommerce Shortcode

WooCommerce提供了一个内置的shortcode,可以直接在WordPress页面或帖子中插入产品。要在首页显示指定数量的产品,请将以下shortcode添加到您的首页模板文件(例如index.php)中:

复制代码
复制代码
[products limit="4"] <!-- 将4替换为您想要显示的产品数量 -->

或者,您可以在主题的functions.php文件中添加自定义函数,然后在首页模板中调用该函数:

复制代码
复制代码
function display_woocommerce_products($atts) {
    extract(shortcode_atts(array(
        'limit' => 4, // 默认显示4个产品
    ), $atts));

    $shortcode = '[products limit="' . esc_attr($limit) . '"]';
    return do_shortcode($shortcode);
}
add_shortcode('woo_products', 'display_woocommerce_products');

然后,在首页模板文件中调用此shortcode:

复制代码
复制代码
[woo_products limit="4"] <!-- 将4替换为您想要显示的产品数量 -->

方法2:使用自定义查询

您还可以使用WordPress的WP_Query类创建自定义查询来获取WooCommerce产品。在主题的functions.php文件中添加以下函数:

复制代码
复制代码
function display_custom_woocommerce_products($atts) {
    extract(shortcode_atts(array(
        'limit' => 4, // 默认显示4个产品
    ), $atts));

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => $limit,
    );

    $query = new WP_Query($args);

    ob_start();

    if ($query->have_posts()) :
        while ($query->have_posts()) : $query->the_post();
            wc_get_template_part('content', 'product');
        endwhile;
    endif;

    wp_reset_postpots();

    return ob_get_clean();
}
add_shortcode('custom_woo_products', 'display_custom_woocommerce_products');

然后,在首页模板文件中调用此shortcode:

复制代码
复制代码
[custom_woo_products limit="4"] <!-- 将4替换为您想要显示的产品数量 -->

这两种方法都可以在WordPress网站首页调用WooCommerce产品。您可以根据自己的需求选择合适的方法。

https://www.seomoban.com/code/102.html

相关推荐
WordPress学习笔记8 小时前
给wordpress网站的图片加alt标签
wordpress
凉风听雪14 小时前
WordPress+Elementor+Woocommerce配置产品聚合页和分类页多项筛选产品功能
wordpress·外贸·独立站·b to b
凉风听雪16 小时前
WordPress+Elementor+ACF+Premium Addons PRO实现字段判定组件显隐
wordpress
永远的WEB小白2 天前
wordpress定时发布失败!站点健康处提示cURL 错误 35
wordpress
WordPress学习笔记3 天前
WordPress主题之家
wordpress
WordPress学习笔记3 天前
WordPress多语种独立站 打造全球化外贸网站
wordpress
A小辣椒3 天前
WordPress如何隐藏后台登陆网址
安全·wordpress
WordPress学习笔记4 天前
2026正版可商用wordpress主题推荐
wordpress
WordPress学习笔记4 天前
wordpress后台更新插件时出现“链接信息”提示
wordpress
星零岁GZY6 天前
2026年 WordPress 极速优化指南:从服务器底层到前端缓存
服务器·性能优化·wordpress·雨云