简体   繁体   English

Wordpress试图在循环数组中使用get_title()作为类别名称

[英]Wordpress Trying to use get_title() in loop array as the category name

On my wordpress page template Im trying to use the get_title() in my arguments array for the a loop but i cant get it to return any posts. 在我的wordpress页面模板上,我试图在参数数组中使用get_title()进行循环,但是我无法获取它以返回任何帖子。

This is where im up to; 这就是我要去的地方;

<?php 
            $args = array( 
                      'category_name' => 'the_title();'
                   );

            $the_query = new WP_Query( $args ); ?>

<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

            <div class="entry"><?php the_content(); ?></div>

<?php endwhile; else: ?>

    <p>Sorry, there are no posts to display</p>

<?php endif; ?>

Im unable to get any posts to return on this page unless i manually enter the slug for the category i want to use which is not ideal as the page slug will always be the same as the post category slug. 我无法获取任何要在此页面上返回的帖子,除非我手动输入要使用的类别的条目,这并不理想,因为页面条目将始终与帖子类别条目相同。

My logic behind this is that i dont want to have an individual page templeate for each page with the different cat as i will end up with hundreds of page templetes. 我这样做的逻辑是,我不想为每页上的每只猫都使用单独的模板,因为我最终将拥有数百页的模板。

Any help appreciated Cheers Jon 任何帮助赞赏干杯乔恩

You're passing the_title(); 您正在传递the_title(); as a string do to ' ' . 作为字符串做' ' Also, the_title() gets title of the object in the loop, not of a category. 同样, the_title()获取循环中对象的标题,而不是类别的标题。
You can do the following: 您可以执行以下操作:

 global $post; 
 $args = array('category_name' => $post->post_name);

You have passed the_title(); 您已通过the_title(); as a string, so will be treated as string, not a function, so it will not return title. 作为字符串,因此将被视为字符串,而不是函数,因此不会返回标题。 You can use global variable $cat , So your code will be, 您可以使用全局变量$cat ,因此您的代码将是

<?php
global $cat;
$args = array('cat' => $cat);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <div class="entry"><?php the_content(); ?></div>
<?php endwhile; else: ?>
    <p>Sorry, there are no posts to display</p>
<?php endif; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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