Support

Account

Home Forums ACF PRO Slug validation Reply To: Slug validation

  • I was just able to finish the function how I expect it to work…

    I think the issue was where I use $_GET[‘id’] I should have used $_POST[‘_acf_post_id’] because with $_POST it works as expected.

    This is the full working result:

    function pg_check_title( $valid, $value, $field, $input ) {
    
        if ( ! $valid ) {
            return $valid;
        }
    
        $post_name = sanitize_title( pg_replace_special_characters( $value ) );
    
        if ( true == pg_slug_exists( $post_name, DpgPostTypes::LONGREAD, $_POST[ '_acf_post_id' ] ) ) {
            $valid = __( 'This title already exists for a longread.', 'dpg' );
        } elseif ( true == pg_slug_exists( $post_name, DpgPostTypes::TEMPLATE, $_POST[ '_acf_post_id' ] ) ) {
            $valid = __( 'This title already exists for a template.', 'dpg' );
        }
        
        return $valid;
        
    }
    add_filter( 'acf/validate_value/key=field_5ae091e84cb7b', 'pg_check_title', 10, 4 );
    
    function pg_slug_exists( $post_name, $post_type, $post_id ) {
        global $wpdb;
        $exclude = false;
        if ( false != $post_id ) {
            $exclude = " AND ID != '" . $post_id . "'";
        }
    
        if ( $wpdb->get_row( "SELECT post_name, ID FROM wp_posts WHERE post_name = '" . $post_name . "' AND post_type = '" . $post_type . "'" . $exclude . "", 'ARRAY_A' ) ) {
            return true;
        } else {
            return false;
        }
    }