通过帖子名称而不是id来发帖

时间:2012-10-16 00:09:14

标签: php wordpress

好的,我目前有这个代码。

<?php

$post_id = 266;
echo "<div id='widgets-wrapper3'><div id='marginwidgets' style='overflow: auto; max-    width: 100%; margin: 0 auto; border: none !important;'>";
$queried_post = get_post($post_id); 
echo "<div class='thewidgets'>";
echo substr($queried_post->post_content, 0, 500);
echo "<a href='".get_permalink( 26 )."' title='Read the whole post' class='rm'>Read     More</a>";
echo "</div>";

echo "</div></div>";

?>

正如您可以看到上面的代码,例程是通过ID获取帖子,但我的固定链接更改为帖子名称而不是用于搜索引擎优化目的的帖子ID。如何通过帖子名称获得帖子?

希望有人能在这里找到答案。谢谢。

3 个答案:

答案 0 :(得分:16)

get_page_by_path()

WordPress有一个内置功能可能会有所帮助,只需要提醒一下。

<?php get_page_by_path( $page_path, $output, $post_type ) ?>

Here's the relevant Codex entry

要获取帖子而不是网页,您只需提供“帖子”作为$post_type参数,通常OBJECT(没有引号)作为$output类型,像这样:

<?php get_page_by_path( 'my_post_slug', OBJECT, 'post' ) ?>

注意此功能不会检查匹配帖子的已发布状态或私有状态。如果您要查找的项目是附件,这很好,但对于帖子和页面(即草稿,私人帖子等)可能会有问题。

注意如果您正在寻找的页面,并且该页面是分层的(即:它有父级),那么您需要提供整个路径,即:'parent_page_slug / my_page_slug'。

WP_Query / get_posts()

如果其中任何一个对您有疑问,那么您应该考虑使用WP_Query课程来name发布您的帖子:

$found_post = null;

if ( $posts = get_posts( array( 
    'name' => 'my_post_slug', 
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 1
) ) ) $found_post = $posts[0];

// Now, we can do something with $found_post
if ( ! is_null( $found_post ) ){
    // do something with the post...
}

答案 1 :(得分:9)

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

    return null;
}

这个。

答案 2 :(得分:1)

使用WP_Query。此函数将检索具有给定名称的第一篇文章,如果未找到任何内容,则为 null

function get_post_by_name(string $name, string $post_type = "post") {
    $query = new WP_Query([
        "post_type" => $post_type,
        "name" => $name
    ]);

    return $query->have_posts() ? reset($query->posts) : null;
}

默认情况下,这将搜索 post 类型的项目:

get_post_by_name("my-post")

作为第二个参数,您可以将其设置为其他内容:

get_post_by_name("my-page", "page")