我建立了一个Word Press页面构建器元框,我的meta框正常工作,但是我认为这是错误的,或者我有更好的方法来做到这一点,我的问题是append()jquery函数。那是非常复杂和明智的代码。而且我知道我不应该在jquery append()中使用php代码,我想使用jquery Ajax来做到这一点。但我不知道该怎么办,您能给我展示一个真实或更佳的方法吗?
$page_builder = array(
array(
'id' => 'module',
'type' => 'tab',
'title' => __( 'tab', 'tx' ),
'fields' => array(
array(
'id' => 'module_title',
'type' => 'text',
'title' => __( 'Module Title', 'tx' ),
),
array(
'id' => 'module_numbers',
'type' => 'text',
'title' => __( 'Max Number of Post', 'tx' ),
),
array(
'id' => 'module_offset',
'type' => 'text',
'title' => __( 'Posts Offset', 'tx' ),
),
array(
'id' => 'module_category',
'type' => 'category',
'title' => __( 'Filter by Category', 'tx' ),
),
),
),
);
function call_metabox() {
global $page_builder;
$terms = get_terms( 'category', 'get=all' );
?>
<script>
jQuery(document).ready( function() {
var count = 1;
var button = jQuery('.add-module');
var panels = jQuery('.panels');
var geturi = '<?php echo get_template_directory_uri(); ?>';
var category = '<?php foreach ( $terms as $term ){ echo '<option value="'. $term->slug .'">'. $term->name .'</option>'; } ?>';
button.live( 'click', function() {
panels.append(
'<li>'+
'<div><?php _e( 'sample', 'tx' ); ?></div>'+
'<div>'+geturi+'/img.png'+'</div>'+
'<div><select name="<?php echo $page_builder[0]['fields'][0]['id']; ?>" id="">'+category+'</select></div>'+
'<div>'+'<input type="text" name="module_title['+ count +'][title]" id="module_title['+ count +'][title]" value="" />'+'</div>'+
'</li>'
);
count++;
});
});
</script>
<input type="button" id="add-module" class="add-module" value="<?php _e( 'Add New Module', 'tx' ) ?>">
<ul class="panels">
</ul>
< ?php
}
谢谢。
您可以将js代码放在.js文件中,然后使用wp_enqueue_script插入脚本:
//this will register the script
wp_register_script(
'my_script_id',
plugins_url( '/assets/js/scritp.js', PLUGIN_URL ),
[ 'JQuery' ], // define dependencies
null,
true
);
// this will pass data from php to js script
// it will output 'var object = { attribute: 'value' }' before script insertion
wp_localize_script(
'my_script_id',
'object',
[
'attribute' => 'value'
]
);
// this will enqueue the script insertion
wp_enqueue_script( 'my_script_id' );
// this will insert the script
add_action( 'wp_enqueue_scripts', 'my_script_id' );