Wordpress - 将类别添加到 index.php

Wordpress - add category to index.php

我为 "song of the week" 设置了一个类别。在我网站的桌面版中,它作为一个小部件出现在侧边栏中。

但是,我正在尝试在我的移动网站上显示它。以前,我的主题制作者让我将代码添加到 index.php 以将搜索栏添加到我的移动网站。

到目前为止,我已经尝试使用 "widget shortcode" 插件添加类别。

我尝试将以下内容添加到我的 index.php:

<?php 
    echo do_shortcode(widget id="rpwe_widget-6");
?>

但是当我这样做时,出现了 500 错误。

将类别 (1 post) 添加到 index.php 的正确 PHP 代码是什么?

我知道这种短代码方法不是正确的方法,但我不确定还能做什么。

您在代码中缺少方括号和一些引号。试试这个:

<?php echo do_shortcode('[widget id="rpwe_widget-6"]'); ?>

您可以通过使用循环并为其提供要查找的参数来获取 posts。在您的情况下,您需要找出要显示的类别的 ID。为此,请转到类别概览并将鼠标悬停在要显示的类别上。

然后您会在浏览器底部看到一个 link,类似于:

http://www.yourdomain.com/wp-admin/term.php?taxonomy=category&tag_ID=1&post_type=post...

the part with category&tag_id=X

X 是您要显示的类别的 ID。然后在您的 front-page.php、home.php 或 index.php 中,您可以使用以下代码查询数据库(是的,将其放入您的模板文件中):

<?php
    // Feed PHP with the information you want to show, in our case: a certain category = use of the id, number = amount of posts to show
    $catquery = new WP_Query( 'cat=3&posts_per_page=1' );
    // Let WordPress run the loop for you
    while($catquery->have_posts()) : $catquery->the_post();
?>
<!--Inside the loop, you can use the WP template tags to show the stuff you want, like author, exerpt of the post etc. -->
<h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
<p><?php the_excerpt(); ?></p>
<?php endwhile; ?>
<?php // Don't forget to reset the query (clean the data after it is finished) ?>
<?php wp_reset_query(); ?>

为了帮助您解决问题:查找类别 ID,在显示 cat=3 的圆括号 中输入数字(3 是示例类别)。然后将代码复制到你的主题中你想要的地方,看看你得到了什么:)

希望是你的结果。

这个小查询将为您提供:

linkpost 的标题和摘录(post 的简短预览)。 如需更多 tags/information 展示,请访问 WordPress Codex 或像这样进行谷歌搜索:http://blog.teamtreehouse.com/wordpress-loop-beginners-guide