通过帖子标题得到wordpress帖子

时间:2014-01-10 09:48:13

标签: php wordpress

我正在使用此代码在外部网站上显示wordpress帖子:

<?php
require('wp_blog/wp-blog-header.php');

    if($_GET["p"] > '') { ?>

    <?php query_posts('p='.$_GET["p"].''); ?>
    <?php while (have_posts()) : the_post(); ?>
        <h4><?php the_title(); ?></h4>
        <?php the_content(); ?>
    <?php endwhile; ?>
    <?php } else { ?>

    <?php
    $posts = get_posts('numberposts=10&order=ASC&orderby=post_title');
    foreach ($posts as $post) : setup_postdata( $post ); ?>
        <?php the_date(); echo "<br />"; ?>
        <?php the_title(); ?>    
        <?php the_excerpt(); ?> 
    <?php endforeach; ?>

    <?php } ?>

而不是根据ID选择帖子,如何根据帖子标题选择帖子?

3 个答案:

答案 0 :(得分:24)

您可以使用get_page_by_title()按标题提取帖子。就像这样:

$page = get_page_by_title('About', OBJECT, 'post');
echo $page->ID

详情为here

  

OR自定义查询,如下所示:

$posttitle = 'About';
$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );
echo $postid;

答案 1 :(得分:2)

像这样添加功能

function get_page_by_post_name($post_name, $output = OBJECT, $post_type = 'post' ){
    global $wpdb;
    $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $post_name, $post_type ) );

    if ( $page ) return get_post( $page, $output );

    return null;
}

 add_action('init','get_page_by_post_name');

就这样跑:

 $page = get_page_by_post_name('hello-world', OBJECT, 'post');
 echo $page->ID; 

答案 2 :(得分:2)

试试这个

$post_id = get_page_by_title($post_title, OBJECT, 'your_post_type_name');
$post_id->ID; // your id