如何在帖子中使用jQuery附加自定义元框字段



我正在尝试以编程方式在post中添加自定义元框,但是js给出了一个错误,目标是当我单击添加按钮时,附加了相同的文本区域框 是以前创建的。我在函数中.php文件中的自定义元框在二十七个主题中的代码是:

// including custom js files here
function wptuts_scripts_with_jquery() {
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/js/myjs.js', array( 'jquery' ));
}
add_action( 'admin_enqueue_scripts', 'wptuts_scripts_with_jquery' );
// starting custom meta box
add_action( 'add_meta_boxes', 'm_param_meta_box_add' );
function m_param_meta_box_add() {
add_meta_box( 'm_param_post', 'Box Title', 'm_param_post_meta_box_cb', 'post', 'normal', 'high' );
}
function m_param_post_meta_box_cb( $post )
{
$values = get_post_custom( $post->ID );
if ( isset( $values['m_meta_description'] ) ) {
$m_meta_description_text = esc_attr( $values['m_meta_description'][0] );
}
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<div id="info"></div>
<label> Name: </label>
<textarea rows="1" cols="20" name="m_meta_description" ><?php echo $m_meta_description_text; ?></textarea>
<button type="button" name="add" id="add">Add</button><br><br>
<?php
} // close m_param_post_meta_box_cb function
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
// Make sure your data is set before trying to save it
if( isset( $_POST['m_meta_description'] ) ) {
update_post_meta( $post_id, 'm_meta_description', wp_kses( $_POST['m_meta_description']) );
}     
}

我的js代码错误是:">未捕获的类型错误:$不是一个函数 在myjs.js:2">

我的JS代码是:

// <script type="text/javascript">
$(document).ready(
function(){
$("#add").click(function(){
$("#info").append('fname<input type="text" name="name[]">');
})
}
);
// </script>

虽然这个答案是正确的,但值得一提的是,你也可以这样做

jQuery(document).ready(function ($)
{
$("#add").click(function(){
$("#info").append('fname<input type="text" name="name[]">');
})
})

无需随处书写jQuery而不是$

尝试使用这个:

jQuery(document).ready(
function(){
jQuery("#add").click(function(){
jQuery("#info").append('fname<input type="text" name="name[]">');
})
}
);

根据这篇文章,当WordPress的jQuery加载时,它使用兼容模式,这是一种避免与其他语言库冲突的机制:

这归结为你不能直接使用美元符号 就像您在其他项目中一样。当为WordPress编写jQuery时,你 需要使用 jQuery 代替。

即使在一开始,您也可以删除 JQuery 并放置一个"$">

$(document).ready(function ($)
{
$("#add").click(function(){
$("#info").append('fname<input type="text" name="name[]">');
})
})

最新更新