I'm inserting posts into wordpress using a script which is loaded through CRON. Before inserting each post I am checking whether the post with the same title exists or not. Below is the snippet I'm using:

if( is_null(get_page_by_title( $page_title, 'OBJECT', $post_type )) ) {
    // Create post object
    $my_post = array(
        'post_title' => "Food & Wine",  // this is example and it actually inserts $page_title.
        'post_content' => 'Dummy content',
        'post_status' => 'draft',
        'post_author' => 1,
        'post_type' => $post_type,
    // Insert the post into the database
    wp_insert_post( $my_post );
} else {
    echo 'Post already exists.';

Now this insertion part works pretty well, but it stores '&' as html entity (&) in the database. So in the database, the post title looks like "Food & Wine". In the list of posts admin screen, the title looks fine with '&' and once I go to the edit screen, it shows &.

This causes the first 'if' condition to return TRUE and it inserts a duplicate post. My database collation type is "utf8_general_ci". Well this works on my local MAMP installation, but fails on my shared host.

I would like to know what is wrong in the code and how should this situation be handled. Also is it suggested to escape html entities for the 'post_content'?


1 Answer 1


It seems like the crux of the question is this:

This causes the first 'if' condition to return TRUE and it inserts a duplicate post.

Check for the post_name instead. That value is normalized to lowercase and dashes by sanitize_title_with_dashes so you won't have this issue. That value is also the one that WordPress enforces as unique, and the one used as a permalink.

  • So that means I have to fire a query using $wpdb object right? Or is there any inbuilt wordpress function to take care of this? Well this would be an immediate solution to my problem, but I would like to know why on my local MAMP installation wordpress stores & as & and on my server it stores as &? Locally I am running MySql 5.5.25 and PHP 5.2.17 and on my hosting server I have MySql 5.5.23 and PHP 5.2.17.
    – Praz
    May 24, 2013 at 15:05
  • Thank you for pointing out this possibility. Although it's quit obvious (in hindsight), I've been struggling with a similar problem for a few day's now :). Many thanks (y)
    – iSenne
    Mar 10, 2014 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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