3

I am trying to change the order/position/index of a block programatically.

I see we have this function moveBlockToPosition() however it does not show how to get fromRootClientId and toRootClientId.

I tried moveBlockToPosition( clientId, 2 ); but does not work.

1 Answer 1

1

You can use getBlockRootClientId() from the block editor's data store. E.g.

wp.data.select( 'core/block-editor' ).getBlockRootClientId( clientId )

And here's a working example for you to see how it can be used in an edit() function, where my block contains a demo button which will move the block to the very last or first position:

  • WordPress dependencies:

    import { useBlockProps } from '@wordpress/block-editor';
    import { useSelect, useDispatch } from '@wordpress/data';
    import { Button } from '@wordpress/components';
    
  • The edit() function:

    function edit( { clientId } ) {
        const {
            getBlockRootClientId,
            getBlockIndex,
            getBlocks,
        } = useSelect( 'core/block-editor' );
    
        const { moveBlockToPosition } = useDispatch( 'core/block-editor' );
    
        // Demo callback which moves this block to the very last or first position.
        function demoMoveBlock() {
            const blocks = getBlocks();
            if ( blocks.length < 2 ) {
                alert( 'Stop playing now; there\'s only this block in the editor!' );
                return;
            }
    
            // Use the last block as the target, or the first one if this was the last block.
            let targetBlock = blocks.pop();
            if ( clientId === targetBlock.clientId ) {
                targetBlock = blocks.shift();
            }
    
            const sourceClientId   = clientId;
            const targetClientId   = targetBlock.clientId;
            const fromRootClientId = getBlockRootClientId( sourceClientId );
            const toRootClientId   = getBlockRootClientId( targetClientId );
            const targetIndex      = getBlockIndex( targetClientId );
    
            moveBlockToPosition( sourceClientId, fromRootClientId, toRootClientId, targetIndex );
        }
    
        return (
            <div { ...useBlockProps( { style: {
                backgroundColor: 'pink',
                padding: '10px',
            } } ) }>
                <Button
                    text="Move this block"
                    variant="primary"
                    onClick={ demoMoveBlock }
                />
            </div>
        );
    }
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.