Skip to content

Instantly share code, notes, and snippets.

@badabingbreda
Last active September 8, 2016 06:37
Show Gist options
  • Save badabingbreda/88b55a1498a86f57fe1409c93ca39b49 to your computer and use it in GitHub Desktop.
Save badabingbreda/88b55a1498a86f57fe1409c93ca39b49 to your computer and use it in GitHub Desktop.
Shortcode for Beaver Builder to target a row and set it's background using a ACF value, using jQuery and CSS.
<?php
/**
* Target a row higher in the DOM using style-attr for temp-class
* @example shortcode: [targetrow field="backgroundurl" removemodule="true"]
* this will use the posts ACF backgroundurl as a value for the background-image,
* it will also remove the module in the DOM so that when used on a row without any HTML or editor module it will still be silent.
*
* @param $atts attributes, field is required;
* @return [type] [description]
*/
function target_row( $atts ) {
$atts = shortcode_atts( array(
'field' => '',
'removemodule' => false,
'removescript' => true,
), $atts );
// return early when no field-value has been set
if ( $atts['field'] == '' ) return '';
// get a unique id
$unique = md5( date( ) );
/**
* remove the module, removes the <script> as well.
* No-one will ever know how you did it!
**/
if ( (bool)$atts['removemodule'] && !isset( $_GET['fl_builder'] ) ) $remmodule = '$mod = $(\'.'.$unique.'\').closest(\'.fl-module\').remove();';
/**
* remove the script (class) only if this code is run inside an editor
*/
if ( (bool)$atts['removescript'] && !isset( $_GET['fl_builder'] ) ) $remscript = '$(\'.'.$unique.'\').remove();';
return sprintf(
'<div class="myrowstyle '.$unique.'" style="background-image:url(%s);background-size:cover;background-repeat:no-repeat;">
<script>
(function($) {
$(document).ready( function(){
/* get the style */
var style = $(\'.'.$unique.'\').attr(\'style\');
/* add style to the row */
$(\'.'.$unique.'\').closest(\'.fl-row\').attr(\'style\', style );'.
$remmodule .
$remscript .
'
});
})(jQuery);
</script>
</div>',
get_field( $atts['field'] , get_option( 'page_for_posts' ) ) // ACF // types_render_field( $atts['field'] ) // Toolset
);
}
/* add a shortcode that is called using [targetrow] using the callback/function target_row */
add_shortcode ( 'targetrow', 'target_row' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment