Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now
Sign InSign Up

PHP-J

PHP-J

PHP-J Navigation

  • Главная
  • Контакты
Поиск
Задать вопрос

Mobile menu

Close
Задать вопрос
  • Главная
  • Add group
  • User Profile
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Buy Points
Home/ Questions/Q 78771
Next
Answered
wordpressor
  • 0
wordpressorЭксперт
Asked: 20 марта, 20222022-03-20T07:36:41+03:00 2022-03-20T07:36:41+03:00In: Wordpress (Вопросы и ответы)

Получение значения метабокса?

  • 0

У меня есть собственный метабокс, созданный с использованием кода из справочника WordPress:

http://codex.wordpress.org/Function_Reference/add_meta_box

<?php
/* Define the custom box */

// WP 3.0+
// add_action('add_meta_boxes', 'myplugin_add_custom_box');

// backwards compatible
add_action('admin_init', 'myplugin_add_custom_box', 1);

/* Do something with the data entered */
add_action('save_post', 'myplugin_save_postdata');

/* Adds a box to the main column on the Post and Page edit screens */
function myplugin_add_custom_box() {
    add_meta_box( 
        'myplugin_sectionid',
        __( 'My Post Section Title', 'myplugin_textdomain' ),
        'myplugin_inner_custom_box',
        'post' 
    );
    add_meta_box(
        'myplugin_sectionid',
        __( 'My Post Section Title', 'myplugin_textdomain' ), 
        'myplugin_inner_custom_box',
        'page'
    );
}

/* Prints the box content */
function myplugin_inner_custom_box() {

  // Use nonce for verification
  wp_nonce_field( plugin_basename(__FILE__), 'myplugin_noncename' );

  // The actual fields for data entry
  echo '<label for="myplugin_new_field">';
       _e("Description for this field", 'myplugin_textdomain' );
  echo '</label> ';
  echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="whatever" size="25" />';
}

/* When the post is saved, saves our custom data */
function myplugin_save_postdata( $post_id ) {

  // verify this came from the our screen and with proper authorization,
  // because save_post can be triggered at other times

  if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename(__FILE__) ) )
      return $post_id;

  // verify if this is an auto save routine. 
  // If it is our form has not been submitted, so we dont want to do anything
  if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
      return $post_id;


  // Check permissions
  if ( 'page' == $_POST['post_type'] ) 
  {
    if ( !current_user_can( 'edit_page', $post_id ) )
        return $post_id;
  }
  else
  {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return $post_id;
  }

  // OK, we're authenticated: we need to find and save the data

  $mydata = $_POST['myplugin_new_field'];

  // Do something with $mydata 
  // probably using add_post_meta(), update_post_meta(), or 
  // a custom table (see Further Reading section below)

   return $mydata;
}
?>

И я не уверен, как отображать его значение на каждой странице?

<?php 

    $meta = get_post_meta($post->ID, 'myplugin_new_field'); 

    var_dump($meta);

?>

Дает:

массив (0) {}

Кроме того, поле метабокса не обновляет свое значение после нажатия кнопки «Обновить запись/или страницу». Это потому, что input value=»whathever» должен быть чем-то вроде приведенного выше кода.

Есть идеи?

Спасибо!

[редактировать]

Окончательный код, который не обновляет входное значение:

/* Define the custom box */
add_action('add_meta_boxes', 'myplugin_add_custom_box');

// backwards compatible
add_action('admin_init', 'myplugin_add_custom_box', 1);

/* Do something with the data entered */
add_action('save_post', 'myplugin_save_postdata');

/* Adds a box to the main column on the Post and Page edit screens */
function myplugin_add_custom_box() {
    add_meta_box( 
        'metabox_sidebar_select',
        __( 'My Post Section Title', 'myplugin_textdomain' ),
        'myplugin_inner_custom_box',
        'post' 
    );
    add_meta_box(
        'metabox_sidebar_select',
        __( 'My Post Section Title', 'myplugin_textdomain' ), 
        'metabox_sidebar_select',
        'page'
    );
}

/* Prints the box content */
function myplugin_inner_custom_box() {

  // Use nonce for verification
  wp_nonce_field( plugin_basename(__FILE__), 'myplugin_noncename' );

  // The actual fields for data entry
  echo '<label for="myplugin_new_field">';
       _e("Description for this field", 'myplugin_textdomain' );
  echo '</label> ';
  echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="'.get_post_meta($post->ID, 'myplugin_new_field',true).'" size="25" />';  
}

/* When the post is saved, saves our custom data */
function myplugin_save_postdata( $post_id ) {

  // verify this came from the our screen and with proper authorization,
  // because save_post can be triggered at other times

  if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename(__FILE__) ) )
      return $post_id;

  // verify if this is an auto save routine. 
  // If it is our form has not been submitted, so we dont want to do anything
  if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
      return $post_id;


  // Check permissions
  if ( 'page' == $_POST['post_type'] ) 
  {
    if ( !current_user_can( 'edit_page', $post_id ) )
        return $post_id;
  }
  else
  {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return $post_id;
  }

  // OK, we're authenticated: we need to find and save the data

  $mydata = $_POST['myplugin_new_field'];

  // Do something with $mydata 
  // probably using add_post_meta(), update_post_meta(), or 
  // a custom table (see Further Reading section below)

  global $post;
  update_post_meta($post->ID, myplugin_new_field, $mydata);

   return $mydata;
}
metaboxpost-meta
  • 9 9 ответов
  • 21 просмотров
  • 0 Followers
  • 0
Ответить
Share
  • Facebook

    9 ответов

    • Лучшие оценки
    • Старые
    • Недавние
    • Случайные
    1. revvoodoo Гуру
      2022-03-20T07:37:15+03:00Добавлен ответ 20 марта, 2022 в 7:37 дп

      voodoopress.com/2011/03/adding-meta-boxes-to-your-post-screen У меня есть статья о коде метабоксов, если она вам поможет. Это для настройки, а затем voodoopress.com/2011/03/… Расскажите об использовании значений, выполнив эхо get_post_meta

      • 0
      • Reply
      • bainternet Гуру
        2022-03-20T07:37:54+03:00Replied to ответ 20 марта, 2022 в 7:37 дп

        у вас есть функция, которая сохраняет метаданные? обычно цепляют за save_post крючок? Если нет, то это ваша проблема, вы не сохраняете метаданные.

        • 0
        • Reply
      • wordpressor Эксперт
        2022-03-20T07:38:37+03:00Replied to ответ 20 марта, 2022 в 7:38 дп

        @Rev. Voodoo, проверю как можно скорее. Спасибо. @Bainternet, как я сказал в первом посте, я использую ТОЧНО код, доступный на codex.wordpress.org/Function_Reference/add_meta_box. Кроме того, я скопировал и вставил его в первый пост.

        • 0
        • Reply
      • wordpressor Эксперт
        2022-03-20T07:40:05+03:00Replied to ответ 20 марта, 2022 в 7:40 дп

        @ Bainternet, Боже, я слепой и глупый. Я просто скопировал вставленный код и сразу же избавился от комментариев :/ Большое вам спасибо. В ЛЮБОМ СЛУЧАЕ последняя строка не работает (входные значения не обновляются, входные данные всегда пусты). Есть идеи, почему?

        • 0
        • Reply
      • bainternet Гуру
        2022-03-20T07:40:43+03:00Replied to ответ 20 марта, 2022 в 7:40 дп

        @Wordpressor: вставь свой код в корзину, и я тебе скажу.

        • 0
        • Reply
      • bainternet Гуру
        2022-03-20T07:41:33+03:00Replied to ответ 20 марта, 2022 в 7:41 дп

        @Wordpressor: добавить «глобальный $post;» для myplugin_inner_custom_box() работы и добавьте метки ‘ к update_post_meta($post->ID, 'myplugin_new_field', $mydata);

        • 0
        • Reply
      • bainternet Гуру
        2022-03-20T07:42:15+03:00Replied to ответ 20 марта, 2022 в 7:42 дп

        @Wordpressor: я обновил свой ответ.

        • 0
        • Reply
      • bainternet Гуру
        2022-03-20T07:42:57+03:00Replied to ответ 20 марта, 2022 в 7:42 дп

        @Wordpressor: рад, что ты понял.

        • 0
        • Reply
    2. Лучший ответ
      bainternet Гуру
      2022-03-20T07:39:13+03:00Добавлен ответ 20 марта, 2022 в 7:39 дп

      есть ваш ответ, в вашем коде, где он говорит:

      // Сделайте что-нибудь с $mydata, вероятно, используя add_post_meta(), update_post_meta() или пользовательскую таблицу (см. раздел «Дополнительная литература» ниже)

      вам нужно фактически вставить/обновить данные в базу данных, поэтому добавьте что-то вроде:

      global $post;
      update_post_meta($post->ID, 'myplugin_new_field', $mydata);
      

      и данные будут сохранены, чтобы вы могли получить их, используя свой код:

      $meta = get_post_meta($post->ID, 'myplugin_new_field'); 
      

      и единственное другое изменение, которое вам нужно, — это функция, которая отображает изменение метабокса:

      echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="whatever" size="25" />';
      

      к

      echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="'.get_post_meta($post->ID, 'myplugin_new_field',true).'" size="25" />';
      

      Обновлять:

      Чтобы ответить на ваш вопрос в комментариях:

      чтобы сохранить список выбора, вы сохраняете его только способом сохранения в виде текстового ввода, а для отображения ранее выбранного параметра в мета-поле вы просто перебираете параметр и видите, что было выбрано, и добавляете «выбранный» атрибут. Например :

      //get last selected value if exists
      $selected = get_post_meta($post->ID, 'myplugin_new_select_field',true);
      echo '<select name="myplugin_new_select_field">';
      $x = 0;
      while ($x < 4){
          echo '<option value="'.$x.'"';
          //check if the last value is the same is current value.
          if ($x == $selected)
              echo ' selected="selected"';
          echo '>'.$x.'</option>';
      }
      echo '</select>';
      
      • 0
      • Reply

    Оставить ответ
    Отменить ответ

    You must login to add an answer.

    Forgot Password?

    Need An Account, Sign Up Here

    Sidebar

    Ask A Question

    Stats

    • Questions : 7k
    • Answers : 38k
    • Best Answers : 4k
    • Users : 5k
    • Popular
    • Answers
    • netconstructorcom

      Лучшая подборка кода для вашего файла functions.php [закрыто]

      • 97 Answers
    • MikeSchinkel

      Объективные рекомендации по разработке плагинов? [закрыто]

      • 83 Answers
    • EAMann

      Как легко перенести установку WordPress из стадии разработки в рабочую ...

      • 60 Answers
    • Karenfreva
      Karenfreva added an answer [url=https://sildenafilviashop.com/]viagra over the counter[/url] cialis vs viagra [url=https://tblsviagra.com/]cheap viagra online[/url]… 27 июня, 2022 at 11:19 дп
    • Karenfreva
      Karenfreva added an answer [url=https://casinoboba.com/]lucky creek[/url] uptown ace casino [url=https://casinowingames.com/]sloto cash casino[/url] andromeda [url=https://realmonetcasino.com/]ignition[/url]… 25 июня, 2022 at 12:21 пп
    • bainternet
      bainternet added an answer попробуй это://first get all agents $agents = new WP_Query(array('post_type' =>… 27 марта, 2022 at 6:12 пп

    Похожие вопросы

    • nmystic

      Как назначить файл по умолчанию в «Внешний вид > Редактор»?

      • 0 Answers
    • billeisenhauer

      Как показать полную публикацию на главной странице

      • 0 Answers
    • atticus

      Создание пользовательских запросов AJAX

      • 0 Answers

    Лучшие участники

    rarst

    rarst

    • 0 Questions
    • 5k Points
    Гуру
    bainternet

    bainternet

    • 0 Questions
    • 5k Points
    Гуру
    janfabry

    janfabry

    • 0 Questions
    • 3k Points
    Гуру

    Trending Tags

    categories comments custom-field custom-post-types custom-taxonomy customization functions images menus multisite pages permalinks php plugin-development plugin-recommendation plugins posts theme-development themes widgets wp-admin

    Footer

    © 2022

    Вставить/изменить ссылку

    Введите адрес назначения (URL)

    Или сделайте ссылку на существующий материал

      Поисковый запрос не задан. Показаны недавние элементы. Воспользуйтесь поиском или клавишами вверх/вниз, чтобы выбрать элемент.