Sunday, 15 June 2014

jquery - Add a php function to a javascript file with AJAX (tinymce + wordpress related) -



jquery - Add a php function to a javascript file with AJAX (tinymce + wordpress related) -

i creating tinymce button wp wysiwyg editor. happens when utilize clicks on button modal form pops , have come in few fields. 1 of fields needs list box lists every post category , user select one. basic syntax follows:

{ type: 'listbox', name: 'sds-category', label: 'category', 'values': [ {text: 'name of cat', value: 'cat id'}, {text: 'name of cat', value: 'cat id'}, {text: 'name of cat', value: 'cat id'}]}

so in order categories displaying have used phpfunction spit out {text: '', value: ''} syntax every category , goes follows:

function write_cat_list($cat){ $cats = get_categories('hide_empty=false&orderby=name&order=asc&parent=' . $cat); if($cats) : foreach ($cats $cat) : $tinymce_list[] = "{text: '".$cat->name."', value: '".$cat->term_id."'}"; write_cat_list($cat->term_id); endforeach; echo implode(',', $tinymce_list); endif; }

so left placing php function write_cat_list(0) .js file, , stuck!

i not sure how go doing this, because very inexperienced ajax, there easy way or jquery function create easy include php function js file?

since recursively collecting categories, print value within foreach loop, or collect values array ( doing ) , pass further. here example:

function list_categories( $cat_id, &$output = array() ) { $categories = get_categories( 'hide_empty=0&orderby=name&order=asc&parent=' . $cat_id ); foreach( $categories $cat ) { $output[] = array( 'text' => $cat->name, 'value' => $cat->term_id ); list_categories( $cat->term_id, $output ); } homecoming $output; } $list = list_categories(0); // array of categories

there several ways include output .js file. if script generated .php file use:

'values': <?php echo json_encode( list_categories(0) ); ?>

if external file 1 alternative localize script:

wp_localize_script( 'some_handle', 'mce_options', array( 'categories' => json_encode( list_categories(0) ) ) ); // later in .js file 'values': mce_options.categories

another alternative print values straight in admin_head:

add_action( 'admin_enqueue_scripts', 'mce_admin_scripts' ); function mce_admin_scripts( $hook ) { if ( $hook == 'post.php' || $hook == 'post-new.php' ) { add_action( "admin_head-$hook", 'mce_admin_head' ); } } function mce_admin_head() { echo '<script type="text/javascript">var mce_options=' . json_encode( array( 'categories' => list_categories(0) ) ) . '; </script>'; }

php jquery ajax wordpress

No comments:

Post a Comment