admin管理员组

文章数量:1124163

  • I am working on a project and it has a requirement of adding separate background image for mobile devices.

  • So is there any way that I can add InspectorControl on the core/group block for the mobile background image and use it instead of the default specified for smaller displays?

  • I am using the below approach but I don't know why it's working for the editor but not on the actual front end can anyone suggest an issue?

/**
 * WordPress dependencies
 */
const { addFilter } = wp.hooks;
const { InspectorControls } = wp.blockEditor;
const { PanelBody } = wpponents;
const { createHigherOrderComponent } = wppose;
const { MediaUpload, MediaUploadCheck } = wp.blockEditor;
const { Fragment } = wp.element;

// Function to modify the core/group block attributes
/**
 *
 * @param settings
 */
function addMobileBackgroundImageAttribute( settings ) {
    if ( 'core/group' !== settings.name ) {
        return settings;
    }

    settings.attributes = {
        ...settings.attributes,
        mobileBackgroundImage: {
            type: 'string',
            default: '',
        },
    };

    return settings;
}

addFilter( 'blocks.registerBlockType', 'addMobileBackgroundImageAttribute', addMobileBackgroundImageAttribute );

/**
 *
 * @param url
 */
function updateBackgroundImageURL( url ) {
    const css = `
        @media (max-width: 768px) {
            .has-mobile-background-image {
                background-image: url('${ url }') !important;
                background-size: cover !important;
            }
        }
    `;

    // Remove existing style tag if it exists
    const existingStyleTag = document.getElementById( 'custom-background-image-css' );
    if ( existingStyleTag ) {
        existingStyleTag.remove();
    }

    // Create and append new style tag
    const style = document.createElement( 'style' );
    style.id = 'custom-background-image-css';
    style.type = 'text/css';
    style.innerHTML = css;
    document.head.appendChild( style );
}

// Function to update background image URL on the front end
/**
 *
 * @param url
 */
function updateBackgroundImageURLFrontend( url ) {
    console.log( 'updateBackgroundImageURLFrontend', url );
    const css = `
        @media (max-width: 768px) {
            .has-mobile-background-image {
                background-image: url('${ url }') !important;
                background-size: cover !important;
            }
        }
    `;

    // Update existing style tag if it exists
    const existingStyleTag = document.getElementById( 'custom-background-image-css' );
    if ( existingStyleTag ) {
        existingStyleTag.innerHTML = css;
    } else {
        // Create and append new style tag
        const style = document.createElement( 'style' );
        style.id = 'custom-background-image-css';
        style.type = 'text/css';
        style.innerHTML = css;
        document.head.appendChild( style );
    }
}

// Enqueue the CSS when the document is ready for the editor
wp.domReady( () => {
    // Initially update background image URL with empty string
    updateBackgroundImageURL( '' );

    // Update background image URL whenever it changes in the editor
    const blockEdit = wp.data.select( 'core/block-editor' ).getBlocks().find( ( block ) => 'core/group' === block.name );
    if ( blockEdit ) {
        const { attributes } = blockEdit;
        if ( attributes.mobileBackgroundImage ) {
            updateBackgroundImageURL( attributes.mobileBackgroundImage );
            updateBackgroundImageURLFrontend( attributes.mobileBackgroundImage ); // Update background image URL on the front end
        }
    }

    // Listen for block changes and update background image URL accordingly in the editor
    wp.data.subscribe( () => {
        const blockEdit = wp.data.select( 'core/block-editor' ).getBlocks().find( ( block ) => 'core/group' === block.name );
        if ( blockEdit ) {
            const { attributes } = blockEdit;
            if ( attributes.mobileBackgroundImage ) {
                updateBackgroundImageURL( attributes?.mobileBackgroundImage );
                // console.log('mobileBackgroundImage', blockEdit?.attributes?.mobileBackgroundImage);
            }
        }
    } );
} );

// Server-side rendering function to add class name to core/group block
addFilter( 'blocks.getSaveContent.extraProps', 'addClassNameToGroupBlockFrontend', ( extraProps, blockType, attributes ) => {
    // const blockEdit = wp.data.select( 'core/block-editor' ).getBlocks().find( ( block ) => 'core/group' === block.name );
    // const { attributes } = blockEdit ?? {};
    if ( attributes?.mobileBackgroundImage ) {
        console.log( 'mobileBackgroundImage', attributes?.mobileBackgroundImage );
        // extraProps.className = extraProps.className ? extraProps.className + ' has-mobile-background-image' : 'has-mobile-background-image';
        updateBackgroundImageURLFrontend( attributes?.mobileBackgroundImage ); // Update background image URL on the front end
    }

    // console.log('extraProps', attributes?.mobileBackgroundImage);
    console.log( 'extraProps',blockType, extraProps, attributes );
    return extraProps;
} );

const withClassNameAndInspectorControls = createHigherOrderComponent( ( BlockEdit ) => {
    return ( props ) => {
        const { name, attributes, setAttributes } = props;

        const updatedProps = {
            ...props,
            className: 'has-mobile-background-image',
        };

        if ( 'core/group' === name ) {
            return (
                <>
                    <BlockEdit { ...props } />
                    <InspectorControls>
                        <PanelBody title="Mobile Background Image">
                            <MediaUploadCheck>
                                <MediaUpload
                                    onSelect={ ( media ) => {
                                        setAttributes( { mobileBackgroundImage: media.url, className: 'has-mobile-background-image' } );
                                    } }
                                    type="image"
                                    value={ attributes.mobileBackgroundImage }
                                    render={ ( { open } ) => (
                                        <>
                                            <button className="button button-large" onClick={ open }>
                                                { attributes.mobileBackgroundImage ? 'Change Image' : 'Select Image' }
                                            </button>
                                            { attributes.mobileBackgroundImage && (
                                                <img src={ attributes.mobileBackgroundImage } alt="Mobile Background" className="mobile-background-image" style={ { marginTop: '10px', maxWidth: '100%' } } />
                                            ) }
                                        </>
                                    ) }
                                />
                            </MediaUploadCheck>
                        </PanelBody>
                    </InspectorControls>
                </>
            );
        }

        if ( 'core/group' === name && attributes?.mobileBackgroundImage ) {
            return <BlockEdit { ...updatedProps } />;
        }

        return <BlockEdit { ...props } />;
    };
}, 'withClassNameAndInspectorControls' );

addFilter( 'editor.BlockEdit', 'addMobileBackgroundImageControl', withClassNameAndInspectorControls );

本文标签: pluginsHow can we extent coregroup or cover block