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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?