Skip to content

Instantly share code, notes, and snippets.

@tallesairan
Last active March 25, 2024 22:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tallesairan/3ad2f37a73ae1a1f5a2d704e98c9556c to your computer and use it in GitHub Desktop.
Save tallesairan/3ad2f37a73ae1a1f5a2d704e98c9556c to your computer and use it in GitHub Desktop.
check if the post exists by slug and post type #wp

Tips

very useful when you can have an attachment with the same slug as a post record_exists_by_slug You can check the post if it exists as an attachment you can change, this way it is practically impossible to duplicate a post

<?php
/**
* post_exists_by_slug
* @param $post_slug
* @param string $type
*
* @return mixed boolean false if no post exists; post ID otherwise.
*/
function post_exists_by_slug( $post_slug,$type = 'post') {
$args_posts = array(
'post_type' => $type,
'name' => $post_slug,
'posts_per_page' => 1,
);
$loop_posts = new WP_Query( $args_posts );
if ( ! $loop_posts->have_posts() ) {
return false;
} else {
$loop_posts->the_post();
return $loop_posts->post->ID;
}
}
/**
* very useful when you can have an attachment with the same slug as a post
* record_exists_by_slug
* @param $post_name
*
* @return mixed boolean false if no post exists; post Object otherwise.
*/
function record_exists_by_slug($post_name)
{
global $wpdb;
$row = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE post_name = '" . $post_name . "' LIMIT 1", 'OBJECT');
if ($row) {
return $row;
} else {
return false;
}
}
/**
* Usage example
* You can check the post if it exists as an attachment you can change, this way it is practically impossible to duplicate a post
*/
$post_name = 'my-post-name';
$customPost = record_exists_by_slug($post_name);
if($customPost){
if ($customPost->post_type === 'attachment') {
$new_post_name = $customPost->post_name . '_' . date('dmY');
wp_update_post(['ID' => $customPost->ID, 'post_name' => $new_post_name]);
// do something
}
}
@Retroperra
Copy link

Very useful!

@tallesairan
Copy link
Author

Look the new function record_exists_by_slug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment