php - Can't successfully check if post with title exist in database

admin2025-06-04  0

In WordPress, I am trying to import posts from a CSV file. I want to check, if post with title already exist. I am trying to do this using a database query, but I am still able to import the same three posts from my example CSV file.

Following PHP code snippet is what I use for checking, if a post with title already exist:

   $check_post_exists = function( $title ) use ( $wpdb, $postTypeArray ) {

        $posts = $wpdb->get_col( "SELECT post_title FROM {$wpdb->posts} WHERE post_type = '{$postTypeArray["custom-post-type"]}' AND post_status = 'publish" );

        return in_array( $title, $posts );
    };

    foreach ( $posts() as $post ) {

        if ( $check_post_exists( $post["zoneid"] ) ) {
            continue;
        }

        $post["id"] = wp_insert_post( array(
            "post_title" => $post["zoneid"],
            "post_content" => $post["bemaerkning"],
            "post_type" => $postTypeArray["custom-post-type"],
            "post_status" => "publish"
        ));         
    }

What am I doing wrong or what am I missing here?

In WordPress, I am trying to import posts from a CSV file. I want to check, if post with title already exist. I am trying to do this using a database query, but I am still able to import the same three posts from my example CSV file.

Following PHP code snippet is what I use for checking, if a post with title already exist:

   $check_post_exists = function( $title ) use ( $wpdb, $postTypeArray ) {

        $posts = $wpdb->get_col( "SELECT post_title FROM {$wpdb->posts} WHERE post_type = '{$postTypeArray["custom-post-type"]}' AND post_status = 'publish" );

        return in_array( $title, $posts );
    };

    foreach ( $posts() as $post ) {

        if ( $check_post_exists( $post["zoneid"] ) ) {
            continue;
        }

        $post["id"] = wp_insert_post( array(
            "post_title" => $post["zoneid"],
            "post_content" => $post["bemaerkning"],
            "post_type" => $postTypeArray["custom-post-type"],
            "post_status" => "publish"
        ));         
    }

What am I doing wrong or what am I missing here?

Share Improve this question asked Jan 17, 2019 at 22:24 DouglessDougless 751 silver badge8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You have typing mistake. You are using the double quotation mark instead of single quotation mark at the end of the code post_status = 'publish"

Please use post_status = 'publish' instead of post_status = 'publish" and then use double quotation mark at the end of query.

And also make sure that dynamic values are correctly entered in the query by printing the query before execution.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748998452a315492.html

最新回复(0)