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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题