16

Ok i have this code currently.

<?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>";

?>

As you can see to the above code, the routine is to get the post by ID, but my permalinks change into post name instead of post id for SEO purposes. How do I get the post by post name?

Hope someone here could figure it out. Thank you.

4

3 回答 3

26

get_page_by_path()

WordPress has a built-in function that might help, with a few words of caution.

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

Here's the relevant Codex entry.

To get a post, rather than a page, you just need to supply 'post' as the $post_type argument, and usually OBJECT (with no quotes) as the $output type, like this:

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

Note this function does not check the published or private status of the matched post. This is great if the item you're looking for is and attachment, but can be problematic for posts and pages (ie drafts, private posts etc.)

Note if it is a page you're looking for, and that page is hierarchical (ie: it has a parent), then you need to supply the entire path, that is: 'parent_page_slug/my_page_slug'.

WP_Query / get_posts()

If either of these are a problem for you, then you should consider just using the WP_Query class to get your post by 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...
}
于 2013-11-01T18:12:13.967 回答
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;
}

Something this.

于 2013-11-25T17:04:49.740 回答
2

Use WP_Query. This function will retrieve the first post with the given name, or null if nothing is found:

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;
}

By default this will search for an item of the type post:

get_post_by_name("my-post")

As a second argument you can set that to something else:

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

于 2021-05-05T09:49:44.543 回答