1

I am trying to validate post data before saving, specifically checking to see if an image exists within the first 750 characters of the post content. The code below works and display the admin notice when an image is present, but after removing the image and clicking "Publish" again, the notice remains (presumably because the query arg is still present). I've tried to remove the filter if no image is found, but the admin notice persists until I save the post a 2nd time.

function my_image_check( $data, $postarr ) {

    $img_found = false;

    // get the post content
    $content = substr( $data['post_content'], 0, 750 );

    // check for both image and caption strings
    $image_pos = strpos( $content, '<img' );
    $caption_pos = strpos( $content, '[caption' );

    if( ( $image_pos !== false ) || ( $caption_pos !== false ) ) {
        $img_found = true;
    }

    if( $img_found ) {
        $data['post_status'] = 'draft';
        add_filter( 'redirect_post_location', 'my_image_redirect_filter', 99 ); 
    } else {
        // this doesnt work?
        remove_filter( 'redirect_post_location', 'my_image_redirect_filter', 99 );
    }

    return $data;
}
add_filter( 'wp_insert_post_data', 'my_image_check', '99', 2 );

function my_image_redirect_filter( $location ) {
    remove_filter( 'redirect_post_location', __FILTER__, 99 );
    $location = add_query_arg ( 'embedded_featured_image', 1, $location );
    return $location;
}

function my_post_admin_notices() {

    if( !isset( $_GET['embedded_featured_image'] ) )
        return;

    switch( absint( $_GET['embedded_featured_image'] ) ) {
        case 1:
            $message = 'Images cannot appear within the first 750 characters of a post. Please move the image lower in the content area or delete it.';
            break;
        default:
            $message = 'Unexpected error';
    }

    echo '<div class="error"><p>' . $message . '</p></div>';
}
add_action( 'admin_notices', 'my_post_admin_notices' );

Your Answer

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

Browse other questions tagged or ask your own question.