0

I have written functionality for checking if custom post title exists or not while adding post. like below:

  function wp_exist_post_by_title( $title ) {
    global $wpdb;
    $return = $wpdb->get_row( "SELECT ID FROM wp_dxwe_posts WHERE post_title = '" . $title . "' && post_status = 'publish' && post_type = 'courses' ", 'ARRAY_N' );
    if( empty( $return ) ) {
        return false;
    } else {
        return true;
    }
}

While adding new post my code is below:

$check = $this->wp_exist_post_by_title( $_POST['course_title']  ) ;
if($check==true)
{
  $title = '';
  echo "<div class='conditional-messages'>Course Already Exists !</div>";
}
else 
{
  $title=$_POST['course_title'];
}   
$post = array(
             'post_title'   => $title,
             'post_content'  => $description,
             'post_status'  => 'publish', 
             'post_type'    => "courses"  
            );  
$description = $_POST['description'];
$id = wp_insert_post($post);
update_post_meta($id, 'course_icon', $attachement_id);
update_post_meta( $id, 'inistitute_name', $institute_name);

While I am adding new post(course title) it is checking if post_title exists or not perfectly but my problem here is I want to check post title(course title) belongs to only one 'institute_name' because other institutes can have the same course title(custom post) too. I know I need to join 2 tables i.e. 'wp_posts' & 'wp_postmeta', but I was unable to do. can anyone please tell me how to sort out this? Thanks for any help.

  • Why are you prefixing your own function with wp_? That's worse than having no prefix at all. – fuxia Dec 20 '16 at 13:25
  • @toscho, sorry one of our past developer kept like that but is there any problem if I put like that? – Prasad Patel Dec 20 '16 at 13:32
  • If WordPress ever decides to implement a new function, it will very likely use the prefix wp_. That's the only prefix you absolutely cannot use in your own code. :) – fuxia Dec 20 '16 at 13:33
  • @toscho, got it, I renamed that function name. Thanks for your valuable suggestion. – Prasad Patel Dec 20 '16 at 13:48
2

You can do it like so:

if (get_page_by_title('Some Title', OBJECT, 'post_type')) {
    // Exists
}

post_type can be "post", "page", a custom post type slug, etc.

Reference: https://codex.wordpress.org/Function_Reference/get_page_by_title

  • It will also return the draft and trash post. – Mayank Dudakiya Jul 19 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.