php 通过帖子标题获取 wordpress 帖子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21040938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:45:49  来源:igfitidea点击:

get wordpress post by post title

phpwordpress

提问by user2710234

i am using this code to show wordpress posts in an external website:

我正在使用此代码在外部网站中显示 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 } ?>

rather than selecting the post based on the ID, how can i make it select the post based on the post title?

不是根据 ID 选择帖子,我怎样才能让它根据帖子标题选择帖子?

回答by Mahmood Rehman

You can use get_page_by_title()to fetch post by title.Like this:

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

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

Details are here.

详细信息在这里

OR custom query like this :

或者像这样的自定义查询:

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

回答by Andrey Shandrov

try this

尝试这个

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

回答by Anjana

Add Function Like this

像这样添加功能

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');

And run like that:

并像这样运行:

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