admin管理员组文章数量:1323323
I have a arbitrary string and want to check if a post with that slug string exists in the site. I tried to find a way to list all slugs, but can't find such a thing. Thanks
I have a arbitrary string and want to check if a post with that slug string exists in the site. I tried to find a way to list all slugs, but can't find such a thing. Thanks
Share Improve this question edited Aug 22, 2011 at 1:44 lulalala asked Aug 15, 2011 at 10:09 lulalalalulalala 5671 gold badge8 silver badges15 bronze badges 1 |5 Answers
Reset to default 11This is what you're looking for, tested and I use it on my own sites:
function the_slug_exists($post_name) {
global $wpdb;
if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A')) {
return true;
} else {
return false;
}
}
You can then use it like this:
if (the_slug_exists('contact')) {
// do something
}
Replace contact
with whatever slug you want to test for.
Do you mean post slug? You can try to make use of wp_unique_post_slug()
that WP uses to generate those. If I remember right if slug you are trying to use is not unique it will be returned with numerical index appended.
How about this simpler approach?
$post_exists = get_page_by_path( $slug, OBJECT, $post_type );
if ( ! $post_exists )
echo 'No post exists with this slug.';
If a post doesn't exist for the given slug and post type provided then get_page_by_path()
returns null.
$args = array('name' => $slugName, 'post_type' => $postType);
$slug_query = new WP_Query($args);
echo "<pre>";
var_dump($slug_query);
exit;
You then have more than enough information to test if a post was returned or not, hope this helps.
$your_slug = 'my-pageeeeeee';
$wpdb = $GLOBALS['wpdb'];
//==================FIRST method======================
$id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM " . $wpdb->posts . " WHERE post_name = '%s' AND ( post_type = 'page' OR post_type = 'post') ", $slug) );
if (!empty($id)) {
//............
}
//====================SECOND method======================
$counts = $wpdb->get_var($wpdb->prepare("SELECT count(post_name) FROM ".$wpdb->posts ." WHERE post_name like '%s'", $slug) );
if ($counts >=1 ) {
//.............
}
本文标签: How to check if a slug exists
版权声明:本文标题:How to check if a slug exists? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742140541a2422562.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
if(is_page('slug-here')) { echo 'exists'; }
. – Iago Commented Jul 5, 2015 at 12:43