amritansh
9/26/2017 - 5:45 AM

This function checks if a post is inserted in the wp database based on a metakey and a metavalue, and return its postid if it is present

This function checks if a post is inserted in the wp database based on a metakey and a metavalue, and return its postid if it is present

/*
 * This function checks if a post is inserted in the wp database based on a metakey and a metavalue, and return its postid if it is present
 * $is_meta_value_unique contains true or false. if true is passed then one postid is returned else array of postids is returned
 */
check_if_a_post_is_inserted($meta_key_name, $meta_key_value, $posttype, $is_meta_value_unique);

function check_if_a_post_is_inserted($meta_key_name, $meta_key_value, $posttype, $is_meta_value_unique) {

    if ($is_meta_value_unique) {
        $posts_per_page = 1;
    } else {
        $posts_per_page = -1;
    }

    $result = false;
    $args = array(
        'posts_per_page' => $posts_per_page,
        'meta_key' => $meta_key_name,
        'meta_value' => $meta_key_value,
        'post_type' => $posttype,
        'post_status' => 'publish',
    );
    $posts_array = get_posts($args);

    if (is_array($posts_array) && count($posts_array) > 0) {
        if ($is_meta_value_unique) {
            $result = $posts_array;
            $result = $result[0]->ID;
        } else {
            $result = array();
            foreach ($posts_array as $key1 => $value1) {
                array_push($result, $value1->ID);
            }
        }
    } else {
        $result = false;
    }
    return $result;
}