简体   繁体   中英

Custom wordpress query not working

I have the following code in the "archive.php" file (from my current active theme):

list($f_categ_name) = explode('/', get_category_parents($cat));
            if ( $f_categ_name == "X_CATEG") {
                $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
                $args = array(
                    'post_type' => 'post',
                    'category_name' => single_cat_title( '', false ),
                    'meta_key' => 'x_categ_type',
                    'orderby' => 'meta_value',
                    'order' => 'ASC',
                    'paged' => $paged,
                );
                // get results
                $the_query = new WP_Query( $args );                 // The Loop
                ?>
                <?php if( $the_query->have_posts() ): ?>

I have 2 categories : A (with 15 posts) and B (with 7 posts) and they have the same parent category(let's say X_CATEG ). So basically I run the same code but $the_query->have_posts() returns true for A category and false for B category. WHY?

Using $GLOBALS['wp_query']->request I was able to debug the executed query and both queries (for category A and B) returned all post IDs.

In the WP_Query arguments, category_name will be category slug Not Category title.

single_cat_title functions will return the page title if a category or tag archive is queried. see reference

So You should use category slug in WP_Query arguments instead of category title .

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM