两种在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

相关推荐
李纲明2 天前
WordPress 搜站名冒出日文垃圾页或被跳陌生站:先止血备份与换钥匙,再查注入点与收录
wordpress·注入·挂马·后门·收录·devdiy·垃圾页
李纲明6 天前
WordPress 后台极慢但前台正常:先降 Heartbeat 与修订版本,再查 autoload options 与后台专用插件
wordpress·heartbeat·autoload·devdiy·后台性能·修订版本·wp_options
guizhoumen8 天前
2026国内外主流CMS内容管理系统对比
cms·wordpress·建站系统·pageadmin
李纲明8 天前
WordPress 定时发布不生效或计划任务堆积:先核 WP-Cron 与系统 crontab,再查 Action Scheduler
wordpress·crontab·devdiy·wp-cron·定时发布·建站排障
snysy9 天前
WordPress伪静态404故障排查笔记
android·笔记·wordpress
代龙涛10 天前
WordPress Query 查询机制详解(WP_Query)
开发语言·后端·php·wordpress
李纲明10 天前
WordPress 更新插件后白屏或致命错误:先开 debug.log 与恢复模式,再二分法定位冲突插件
wordpress·白屏·致命错误·恢复模式·插件冲突·devdiy·debug.log
孙琦Ray10 天前
PrivacySafe 发布 57 个免费开源安全脚本,覆盖 139 个漏洞
wordpress·开源安全·漏洞防护·php2shell·privacysafe
李纲明10 天前
WordPress 报建立数据库连接时出错:先核 wp-config 四元组,再查 MySQL 服务与表修复
运维·数据库·mysql·wordpress·排障·devdiy
李纲明10 天前
WordPress 登录后跳回登录页或提示「Cookie 被阻止」:先核站点 URL 与 HTTPS 一致,再查安全插件与 CDN
https·登录·cdn·wordpress·cookie·devdiy·站点url