Skip to content

Instantly share code, notes, and snippets.

@thefrosty
Created October 14, 2011 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thefrosty/1288692 to your computer and use it in GitHub Desktop.
Save thefrosty/1288692 to your computer and use it in GitHub Desktop.
do_shortcode() in an AJAX call
function add_twitter_discount() {
global $post;
$post_id = $_POST['id'];
$item = get_post_meta( $post_id, 'item_number_discount', true );
$numb = str_replace( 'theme-', '', $item );
//if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'confirmed' ) {
$arr = array();
$entry['code'] = "success";
$entry['id'] = $post_id;
$entry['link'] = '<a class="purchase discount" href="javascript:{}" onclick="document.getElementById(\'cartButtonForm_'. $numb .'\').submit(); return false;">Purchase discount</a>';
ob_start();
echo do_shortcode("[add_to_cart item='".$item."' showprice='no' ]");
$entry['form'] = ob_get_contents();
ob_get_clean();
$arr[] = $entry;
header("Content-Type: application/json");
echo json_encode($arr);
exit();
//}
}
add_action( 'wp_ajax_add_discount', 'add_twitter_discount' ); //hook to ajax action
add_action( 'wp_ajax_nopriv_add_discount', 'add_twitter_discount' ); //hook to ajax action
@thefrosty
Copy link
Author

Related: I adding in the ob_* stuff today trying it out. I had it as $entry['form'] = do_shortcode("[add_to_cart item='".$item."' showprice='no' ]"); which was working last time I checked (which was pre WP 3.1)...

@Steveorevo
Copy link

The ob_start and ob_get_clean seem suspect. Dunno why, but how about just $x = do_shortcode(); then cast $x into you $entry['form']; ?

@thefrosty
Copy link
Author

Tried that, but it's not working. Ended up calling the shortcode function directly and avoiding do_shortcode which stopped working in this manner..

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