dongsi0625 2016-10-15 23:26
浏览 62
已采纳

WooCommerce pre_get_posts

So I've used pre_get_posts in my functions.php before and it works like a charm, but for some reason I can't figure out why it's not working for a WooCommerce page archive-product.php I have.

Directory Structure:

.
├──woocommerce
|   ├── archive-product.php
├── functions.php

Inside functions.php:

function specific_category( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'cat', '7815' );
    }
}
add_action( 'pre_get_posts', 'specific_category' );

Inside archive-product.php:

var_dump($wp_query); //this should be the main query variable but doesn't exist.

Then I tried this inside archive-product.php:

global $wp_query;

foreach($wp_query->posts as $k){
    print_r($k);
    echo "<br>";
    echo "<br>";
}

Which does output posts but the posts aren't relative to the category set in the functions.php code $query->set( 'cat', '7815' );

Question: Why am I having to declare global $wp_query (it should be initialize by default) and why aren't the post from the category I selected?

  • 写回答

1条回答 默认 最新

  • dousuiben8395 2016-11-30 09:45
    关注

    When in a page, the query you're seeing is the category with one page that's basically the page you're seeing. Its not a list of posts as you expected to see on the homepage.

    if you have a normal blog-style homepage and you check the query you can see [found_posts] => 4. but try to set a 'page' as homepage and check your query. You can see [found_posts] => 1 and that one found item (post/page) in your query is the current one.

    You can try to add a custom query with Wordpress WP_Query class in your Page Template and it gives you a lot of options too.

    Also, if you're trying to check for a homepage that is showing a page, consider using is_front_page().

    and for your other question about declaring $wp_query, unfortunately I don't have an answer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图