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

标签 jquery wordpress meta-boxes

我试图以编程方式在帖子中添加自定义元框,但 js 给出错误,目标是当我单击添加按钮时,附加相同的文本区域框 是之前创建的。我在二十七个主题的 function.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代码错误是:“Uncaught TypeError: $ is not a function 在 myjs.js:2"

我的js代码是:

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

最佳答案

同时this answer是正确的,值得一提的是,您也可以这样做

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

无需在任何地方编写 jQuery 而不是 $

关于jquery - 如何在帖子中使用 jQuery 附加自定义元框字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45913645/

相关文章:

html - 在 Wordpress 中通过 CSS 将 Logo 居中

javascript - 事件监听器未在 Chrome 扩展中的 options.js 中触发

jquery - 使用 Magnific Popup 仅显示具有特定类别或 ID 的图像

javascript - 如何选择数组中的图像进行淡入和淡出

c# - 如何在网页中显示我的 Wordpress 站点的最新博客条目?

jquery - 获取 alt 标签以在悬停时显示在图像上

javascript - 使用 "background-size: contain"获取调整大小的背景图像的高度

php - 如何使自定义元框支持 WordPress 中的可视化编辑器?

php - 自定义帖子类型元框单选按钮输出