【问题标题】:Wordpress query_posts by title instead of page_id?Wordpress query_posts 按标题而不是 page_id?
【发布时间】:2011-11-06 22:24:59
【问题描述】:

假设我正在显示的页面标题为“About”,id 为 49。有没有办法更改它,以便它提取页面标题而不是 id。

目前我使用的代码如下:

<?php
    query_posts('page_id=49');
    while (have_posts()) : the_post(); ?>
    <?php the_content();
    endwhile;
?>

感谢您的帮助!

【问题讨论】:

  • 你想做什么?似乎有一个奇怪的要求。
  • 如果我理解正确,您希望通过仅提供帖子的title 而不是id 来获取/显示帖子的内容?
  • 我正在把我的网站变成一个 wordpress 主题。它是一个单页滚动投资组合,因此所有页面(关于、投资组合、联系方式)都显示在一个页面上。目前我让它按他们的 ID 显示页面,但我认为如果它使用他们的标题会更容易。主要是因为这些页面的标题永远不会改变,它们是静态的,但是如果 ID 发生变化,则需要对代码进行微小的更改。
  • @John:我以前用过类似的东西,见 -- stackoverflow.com/questions/7245861/…

标签: wordpress title


【解决方案1】:

我在一个项目中使用了类似的东西,使用帖子的slug;将此保存在您主题的functions.php

if ( ! function_exists( 'get_content_by_slug' ) ) :
/**
 * Get content using a slug
 *
 * @param   string
 * @return  string
 */    
function get_content_by_slug($page_slug) {
    $page = get_page_by_path($page_slug);
    if ($page) {
        $page_content = $page->post_content;
        $page_content = apply_filters('the_content', $page_content);            
        return $page_content;
    } else {
        return null;
    }
}
endif;


用法:

<?php echo get_content_by_slug('page-slug'); ?>

【讨论】:

  • 谢谢,这似乎工作。然而一个小问题。它正在显示我的“关于”页面,但由于某种原因,默认的 Hello World 帖子出现在下面。目前我的博客上只有一个帖子,因为所有的部分都是页面。
  • @John:可能是因为你在the loop...中运行它...
  • 嗨,我不太擅长这个,我在原始问题的末尾添加了我尝试使用的代码,我做对了吗?干杯!
  • @John: 如果你删除get_content_by_slug 函数之后的代码,即while (have_posts()) : the_post(); 和直到endwhile; 的其余部分,它不会显示其他帖子。
  • 如此明显。感谢您的帮助
【解决方案2】:

Get WordPress Post ID from Post title

为您找到了这个。但是,您要小心,因为帖子和页面的标题可能会更改。我相信你有你的理由。

编辑

这实际上可能更好...http://codex.wordpress.org/Function_Reference/get_page_by_title

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多