Skip to content

Instantly share code, notes, and snippets.

@mattheu
Last active February 1, 2021 21:39
Show Gist options
  • Save mattheu/19add11a7e5ff70f04c2a35ed130d73d to your computer and use it in GitHub Desktop.
Save mattheu/19add11a7e5ff70f04c2a35ed130d73d to your computer and use it in GitHub Desktop.
Automatic Gutenberg Ad Placement
/* global wp */
import edit from './edit';
import defaultOptions from '../default';
const { __ } = wp.i18n;
export const name = 'rbmh/ad';
export default Edit;
export const options = {
...defaultOptions,
description: __( 'Displays an MPU ad.' ),
edit: () => {
return (
<div className="rbmh-block-placeholder rbmh-block-placeholder--ad-leaderboard">
<b>Ad (Leaderboard)</b>
</div>
);},
title: __( 'Post Ad' ),
supports: {
html: false,
customClassName: false,
inserter: false,
align: false,
// multiple: false,
reusable: false,
},
}
import * as AdBlock from './block-ad';
const { subscribe } = wp.data;
const { registerBlockType, createBlock } = wp.blocks;
registerBlockType( AdBlock.name, AdBlock.options ) );
// Helper to create a block.
const createAdBlock = () => createBlock( AdBlock.name, { size: 'mpu' } );
subscribe( e => {
const {
getBlocks,
} = wp.data.select( 'core/editor' );
const {
insertBlock,
moveBlockToPosition,
} = wp.data.dispatch( 'core/editor' );
const blocks = getBlocks();
const firstAdIndex = blocks.findIndex( b => b.name === AdBlock.name );
const targetIndex = 3;
const targetRange = 5;
if ( blocks.length >= targetIndex ) {
if ( firstAdIndex < 0 ) {
insertBlock( createAdBlock(), targetIndex );
return;
} else if ( firstAdIndex < targetIndex ) {
moveBlockToPosition( blocks[ firstAdIndex ].clientId, '', '', targetIndex );
return;
} else if ( firstAdIndex > ( targetIndex + targetRange ) ) {
moveBlockToPosition( blocks[ firstAdIndex ].clientId, '', '', targetIndex + targetRange );
return;
}
}
const secondAdIndex = blocks.findIndex( ( b, i ) => b.name === AdBlock.name && i !== firstAdIndex );
const secondTargetIndex = 8 + 1 + ( firstAdIndex - targetIndex );
if ( blocks.length >= secondTargetIndex ) {
if ( secondAdIndex < 0 ) {
console.log( 'inserting ad' );
insertBlock( createAdBlock(), secondTargetIndex );
return;
} else if ( secondAdIndex < secondTargetIndex ) {
console.log( 'moving ad to start', {
firstAdIndex,
secondTargetIndex,
} );
moveBlockToPosition( blocks[ secondAdIndex ].clientId, '', '', secondTargetIndex );
return;
} else if ( secondAdIndex > ( secondTargetIndex + targetRange ) ) {
console.log( 'moving ad to end', {
firstAdIndex,
targetIndex,
secondAdIndex,
secondTargetIndex,
targetRange,
} );
moveBlockToPosition( blocks[ secondAdIndex ].clientId, '', '', secondTargetIndex + targetRange );
return;
}
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment