【问题标题】:(WordPress)Trying to implement jquery to my CPT plugin script(WordPress)尝试在我的 CPT 插件脚本中实现 jquery
【发布时间】:2019-08-27 11:57:14
【问题描述】:

首先我对开发 wordpress 插件有点陌生,很抱歉,如果 dint 找到了正确的答案,它检查了很多东西但无法让它工作。

到目前为止,我正在尝试为我的 wordpress 插件实现一个 jQuery。

我已经在 html 脚本中尝试过,然后加载 jQuery 警报以检查它是否有效。而且它也很少做添加字段的代码。但现在我想保持我的代码干净,以便代码保留在自己的代码文件中。但是最后一部分不起作用。

forms.htm.php
----

<div class="bk-cpt-fields"> <!-- Create the BK CPT meta box -->
  <!-- Create the BK CPT coach name meta box -->
  <div class="coach-name"> 
    <label for="Coach_name">Coach naam </label>
    <input id="coach_name" name="coach_name" type="text" value="<?php echo esc_attr(get_post_meta(get_the_id(), 'coach_name', TRUE)) ?>">
  </div>
  <!-- Ends the BK CPT coach name meta box -->

  <!-- Create the BK CPT coach location meta box -->
  <div class="coach_loaction">
    <table class="coach_location" id="dynamic-locations">
      <label for="coach_location">Coach locatie </label>
      <tr><input id="coach_location" name="coach_location" type="text" value="<?php echo esc_attr(get_post_meta(get_the_id(), 'coach_location', TRUE)) ?>"></tr>
      <tr><input type="button" name="add_location" id="add_location" value="add location"></tr>
      <!-- <button name="add" id="add">Add location</button> -->
    </table>
  </div>
  <!-- Ends the BK CPT coach name meta box -->

  <!-- Create the BK CPT coach image meta box -->
  <div class="coach_image">
    <label for="coach_image"> Foto </label>
    <input id="coach_image" name="coach_image" type="text" value="<?php echo esc_attr(get_post_meta(get_the_id(), 'coach_image', TRUE)) ?>">
  </div>
  <!-- Ends the BK CPT coach name meta box -->
</div> <!-- Ends the BK CPT meta box -->

<!-- Start loading the Jquery script for managing the forms -->

这就是我现在得到的 html。我也尝试过 但这会导致控制台错误。

index.php
---------


/**
 * @file
 * create custom post type.
 */
function custom_post_type () {
  // Set UI labels for Custom Post Type:
  $labels = array(

      'name'                => _x( 'Coaches', 'Post Type General Name', 'gardener' ),
      'singular_name'       => _x( 'Coaches', 'Post Type Singular Name', 'gardener' ),
      'menu_name'           => __( 'Coaches', 'gardener' ),
      //'parent_item_colon'   => __( 'Parent Movie', 'gardener' ),
      'all_items'           => __( 'Alle Coaches', 'gardener' ),
      'view_item'           => __( 'Bekijk de Coaches', 'gardener' ),
      'add_new_item'        => __( 'Voeg een nieuwe Coach toe', 'gardener' ),
      'add_new'             => __( 'Voeg een nieuwe Coach toe', 'gardener' ),
      'edit_item'           => __( 'Bewerk de Coaches', 'gardener' ),
      'update_item'         => __( 'Update de Coaches', 'gardener' ),
      'search_items'        => __( 'Zoek een Coaches', 'gardener' ),
      'not_found'           => __( 'Niet Gevonden', 'gardener' ),
      'not_found_in_trash'  => __( 'Niet Gevonden in Prullenbak', 'gardener' ),
  );
  // Set other options for Custom Post Type:
  $args = array(
      'label'               => __( 'Coaches', 'gardener' ),
      'description'         => __( 'Essentiële Coaches en Eigenschappen', 'gardener' ),
      'labels'              => $labels,
      // Features this CPT supports in Post Editor
      'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', ),
      // You can associate this CPT with a taxonomy or custom taxonomy. 
      'taxonomies'          => array( 'taxonomies_coach_location'),
      /**
       * A hierarchical CPT is like Pages and can have Parent and child items.
       * A non-hierarchical CPT is like Posts.
       **/ 
      'hierarchical'        => true,
      'public'              => true,
      'show_ui'             => true,
      'show_in_menu'        => true,
      'show_in_nav_menus'   => true,
      'show_in_admin_bar'   => true,
      'menu_position'       => 4,
      'menu_icon'           => 'dashicons-palmtree',
    // dashicons-palmtree, icofont-flora
    // nametag, heart, products, award, carrot, palmtree
      'can_export'          => true,
      'has_archive'         => true,
      'exclude_from_search' => false,
      'publicly_queryable'  => true,
      'capability_type'     => 'page',
      'rewrite'             => array(
                            'slug' => 'Coaches'
    )
  );
  // Registering the Custom Post Type:
  register_post_type( 'Coaches', $args );
}

add_action('init' , 'custom_post_type');


/**
 * @file
 * This function whil register the new meta fields for the CPT.
 */
function coaches_cpt_regions_checkbox () {

  // This whil get the array for the fields
   $screens = ['Coaches', 'custom_post_type'];

  //  Here it loops trough the array and sets the wordpress meta names.
   foreach ($screens as $screen) {
       add_meta_box(
           'regio_box_id',           // Unique ID
           'Selecteer regio',  // Box title
           'coaches_cpt_regions_checkbox_html',  // Content callback, must be of type callable
           $screen                   // Post type
       );
   }
}

// Start wordpress metabox action.
add_action('add_meta_boxes', 'coaches_cpt_regions_checkbox', 0);

function my_admin_scripts() {
  wp_enqueue_script( 'bk-forms-js', plugin_dir_url(__FILE__).'js/forms.js' , array("jquery"), "1.12.4", true );
}

add_action( 'admin_enqueue_scripts', 'my_admin_scripts' );

/**
 * @file
 * Gets the forms template.
 */
function coaches_cpt_regions_checkbox_html ($post) {
  include plugin_dir_path ( __FILE__ ) . '/forms.htm.php';
}

/**
 * @file
 * This function whil save the values in the form fields.
 */
function save_coach_data_postdata ($post_id) {
  if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
    return;
  }
  if ( $parent_id = wp_is_post_revision( $post_id ) ) {
    $post_id = $parent_id;
  }
  $field_list = array(
    'coach_name',
    'coach_location',
    'coach_image',
  );
  foreach ($field_list as $field_name) {
    if (array_key_exists( $field_name , $_POST )) {
      update_post_meta(
        $post_id,
        $field_name,
        sanitize_text_field( $_POST[$field_name])
      );
    }
  }
}
add_action('save_post', 'save_coach_data_postdata');

在这里,我尝试通过几种加载脚本的方式来做到这一点。 jQuery 负载正在工作,但是当我单击添加位置按钮时,它不会做任何事情。但是当我在 wordpress 之外对其进行测试时,它会正常运行。

forms.js
------

jQuery('bk-cpt-fields').ready(function() {
  var addloactionfield = 1;

  $('#add_location').click(function() {
    addloactionfield++
    $('#dynamic_locations').append('<input id="coach_location" name="coach_location" type="text" value=""> <button name="remove" id="+addloactionfield+ class="remove-field" ">Remove location</button>');
  });
  $(document).on('click', '.remove-field', function() {
    var button_id = $(this).attr("id");
  });
});

这是我最后一次尝试使用 jQuery。我已经删除了 jQuery 警报,因为它可以正常工作,但是尽管 meby 它不会继续运行它。可悲的是,我不是那个专业或初级程序员。

非常感谢您的帮助!!

伟大的 大卫

【问题讨论】:

  • jQuery('bk-cpt-fields').ready 毫无意义。除此之外,它会尝试通过 标签名称 选择元素,而这些元素甚至不存在于您的 HTML 中,这不是 ready 的工作方式。您需要以此处显示的方式使用它,api.jquery.com/ready,等待 DOM 可用,然后在处理函数的内部选择要操作的元素。
  • 非常感谢@misorude。我现在尝试添加 jQuery(document).ready(function().

标签: php jquery wordpress plugins


【解决方案1】:

非常感谢@misorude。

我已将背面更改为文档。它仍然什么都不做。 但它仍然不会做太多。在这里我得到了控制台错误。


jQuery(document).ready(function() {
  var addloactionfield = 1;

  $('#add_location').click(function() {
    addloactionfield++
    $('#dynamic_locations').append('<input id="coach_location" name="coach_location" type="text" value=""> <button name="remove" id="+addloactionfield+ class="remove-field" ">Remove location</button>');
  });
  $(document).on('click', '.remove-field', function() {
    var button_id = $(this).attr("id");
  });
});
console
------


[Violation] 'setTimeout' handler took <N>ms
post.php?post=250&action=edit:481 GET http://docker4wordpress-project.docker.localhost:8000/js/forms.js 404 (Not Found)
load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,moxiejs,plupload&ver=5.2.2:8 JQMIGRATE: Migrate is installed, version 1.4.1
post.php?post=250&action=edit:481 GET http://docker4wordpress-project.docker.localhost:8000/js/forms.js 404 (Not Found)
load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,moxiejs,plupload&ver=5.2.2:2 [Violation] 'DOMContentLoaded' handler took 212ms
[Violation] Forced reflow while executing JavaScript took 50ms
5[Violation] Added non-passive event listener to a scroll-blocking <some> event. Consider marking event handler as 'passive' to make the page more responsive. See <URL>
tinymce.min.js?ver=4940-20190515:2 [Violation] Avoid using document.write(). https://developers.google.com/web/updates/2016/08/removing-document-write
rw @ tinymce.min.js?ver=4940-20190515:2
aw @ tinymce.min.js?ver=4940-20190515:2
mw @ tinymce.min.js?ver=4940-20190515:2
(anonymous) @ tinymce.min.js?ver=4940-20190515:2
(anonymous) @ tinymce.min.js?ver=4940-20190515:2
jt @ tinymce.min.js?ver=4940-20190515:2
u @ tinymce.min.js?ver=4940-20190515:2
n @ tinymce.min.js?ver=4940-20190515:2
l.<computed>.l.<computed>.l.<computed>.o.onload @ tinymce.min.js?ver=4940-20190515:2
tinymce.min.js?ver=4940-20190515:2 [Violation] 'load' handler took 403ms
[Violation] Forced reflow while executing JavaScript took 46ms

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多