Skip to content

Instantly share code, notes, and snippets.

@tcrsavage
Last active August 29, 2015 14:14
Show Gist options
  • Save tcrsavage/e61fa2cf1a458671b4bc to your computer and use it in GitHub Desktop.
Save tcrsavage/e61fa2cf1a458671b4bc to your computer and use it in GitHub Desktop.
WorddPress Self unhooking nested anonymous function
//Ensure that we don't allow creation of tickers via insertion of a post with non-existent tickers assigned
//Tickers should only be created via the admin ticker interface or via automatic pull-in from xignite
add_filter( 'wp_insert_post_data', function( $data, $post_arr ) {
if ( empty( $post_arr['tax_input']['ticker'] ) ) {
return $data;
}
$created_tickers = array();
//Can be a comma separated string, ensure we are working with an array
if ( ! is_array( $post_arr['tax_input']['ticker'] ) ) {
$post_arr['tax_input']['ticker'] = explode( ',', str_replace( ' ', '', $post_arr['tax_input']['ticker'] ) );
}
//Find all tickers assigned which do not exist
foreach ( $post_arr['tax_input']['ticker'] as $ticker ) {
if ( ! is_numeric( $ticker ) && ! wpcom_vip_get_term_by( 'name', $ticker, 'ticker' ) ) {
$created_tickers[] = $ticker;
}
}
if ( $created_tickers ) {
//After the post is inserted, delete all created tickers
$f = function() use ( $created_tickers, &$f ) {
foreach ( $created_tickers as $ticker ) {
$term = get_term_by( 'name', $ticker, 'ticker' );
//Only delete the ticker if it exists and does not have other posts assigned (failsafe)
if ( $term && $term->count < 2 ) {
wp_delete_term( $term->term_id, 'ticker' );
}
}
remove_action( 'wp_insert_post', $f, 1 );
};
add_action( 'wp_insert_post', $f, 1 );
}
return $data;
}, 100, 2 );
@Japh
Copy link

Japh commented Feb 5, 2015

I like this 😄

@willmot
Copy link

willmot commented Feb 5, 2015

You should follow @joehoyle on twitter :-)

add_filter( 'foo', $c = function() use ( &$c ) { remove_filter( 'foo', $c ) } ); Nice trick to only run a hook once in #WordPress

— Joe Hoyle (@joe_hoyle) May 3, 2012
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment