Last active
August 29, 2015 14:14
-
-
Save tcrsavage/e61fa2cf1a458671b4bc to your computer and use it in GitHub Desktop.
WorddPress Self unhooking nested anonymous function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 ); |
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
I like this 😄