Fixing “Edit with Elementor” and Autoptimize

A regularly reported issue for Autoptimize + Elementor users is that JavaScript optimization breaks the “Edit with Elementor” button in the front-end admin bar. The easiest workaround is to disable the “also optimize for logged in administrators/ editors” option, but below code snippet is more surgical as it will only disable JS optimization, leaving e.g. CSS & Image, which do not impact “Edit with Elementor”, active;

if ( defined( 'ELEMENTOR_VERSION' ) && is_user_logged_in() && current_user_can( 'edit_posts' ) ) {
    add_filter( 'autoptimize_filter_js_noptimize', '__return_true' );
}

When in doubt, you can use the code snippets plugin to safely add this.

Fix for Elementor 3.1 YouTube not LYTE anymore

Elementor 3.1 came with “refactored YouTube source to use YouTube API in Video widget” which resulted in WP YouTube Lyte not being able to lyten up the YouTubes any more. Below code snippet (consider it beta) hooks into Elementor to fix this regression;

add_filter( 'elementor/frontend/widget/should_render', function( $should_render, $elementor_element ) {
	if ( function_exists( 'lyte_preparse' ) && 'Elementor\Widget_Video' === get_class( $elementor_element ) ) {
		$pas = get_private_property( $elementor_element , 'parsed_active_settings');
		if ( ! empty( $pas['youtube_url'] ) ) {
			echo lyte_preparse( $pas['youtube_url'] );
			return false;
		}
	}
	return $should_render;
}, 10, 2 );
// from https://www.lambda-out-loud.com/posts/accessing-private-properties-php/
function get_private_property( object $object, string $property ) {
    $array = (array) $object;
    $propertyLength = strlen( $property );
    foreach ( $array as $key => $value ) {
        if ( substr( $key, -$propertyLength ) === $property ) {
            return $value;
        }
    }
}

Hat tip to Koen for his assistance in digging into Elementor, much appreciated!