New fields for editing a record


In WordPress, there is a very powerful tool for creating unique types of records – these are arbitrary fields or Custom Fields. In new versions they are undeservedly hidden by default, apparently so as not to injure the user with an abundance of strange fields under the visual editor. It’s true that only an experienced user can understand how they work, the developer’s task is to make everything as practical as possible, for example So:

Agree that this is much more obvious than explaining to the user how to create, select from the list and fill a new arbitrary field. The solution has been borrowed from foreign colleagues from the site of the Deluxe Blog Tips, for which they have a special thanks. It is built on the add_meta_box() function. Below, we give the code in which we create a panel of individual SEO settings for each blog entry without a plug-in. Adding fields is done by creating new arrays in $meta_box[‘fields’], and all the code should be placed in the function.php file, in the folder with your theme.

<?php 

//------------------------------------- Улучшаем произвольные поля -------------------------// 

$prefix = 'seo_'; 
$meta_box = array( 
    'id' => 'my-meta-box',
    'title' => 'SEO оптимизация',
    'page' => 'post',
    'context' => 'normal',
    'priority' => 'high',
    'fields' => array(

        array(
            'name' => 'Заголовок страницы:',
            'id' => $prefix . 'title',
            'type' => 'text'
        ),
        array(
            'name' => 'Ключевые слова:',
            'id' => $prefix . 'keywords',
            'type' => 'text'
        ),
        array(
            'name' => 'Описание:',
            'id' => $prefix . 'description',
            'type' => 'textarea'
        )
    )
);

add_action('admin_menu', 'mytheme_add_box');
 
function mytheme_add_box() {
    global $meta_box;
 
    add_meta_box($meta_box['id'], $meta_box['title'], 'mytheme_show_box', 
                 $meta_box['page'], $meta_box['context'], $meta_box['priority']);
}
 
function mytheme_show_box() {
    global $meta_box, $post;
 
    // Use nonce for verification
    echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
 
    echo '<table class="form-table">';
 
    foreach ($meta_box['fields'] as $field) {
        // get current post meta data
        $meta = get_post_meta($post->ID, $field['id'], true);
 
        echo '<tr>',
                '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
                '<td>';
        switch ($field['type']) {
            case 'text':
                echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="',
 $meta ? $meta : $field['std'], '" size="30" style="width:97%" />',
                    '<br />', $field['desc'];
                break;
            case 'textarea':
                echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4"
style="width:97%">', $meta ? $meta : $field['std'], '</textarea>',
                    '<br />', $field['desc'];
                break;
            case 'select':
                echo '<select name="', $field['id'], '" id="', $field['id'], '">';
                foreach ($field['options'] as $option) {
                    echo '<option', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
                }
                echo '</select>';
                break;
            case 'radio':
                foreach ($field['options'] as $option) {
                    echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', 
$meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name'];
                }
                break;
            case 'checkbox':
                echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', 
$meta ? ' checked="checked"' : '', ' />';
                break;
        }
        echo    '<td>',
            '</tr>';
    }
 
    echo '</table>';
}
 
add_action('save_post', 'mytheme_save_data');
 
// Save data from meta box
function mytheme_save_data($post_id) {
    global $meta_box;
 
    // verify nonce
    if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) {
        return $post_id;
    }
 
    // check autosave
    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;
        }
    } elseif (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }
 
    foreach ($meta_box['fields'] as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
 
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    }
} 
?>

Now we can only output the received data in the “header” of the topic: go to editing the file header.php and insert the following code inside the head tag:

Instead of the title tag:

<?php if(is_single()) { $title = get_post_meta($post->ID, 'seo_title', true);
          if($title) {
             echo '<title>'.$title.'</title>';
          } else {
             echo '<title>'.get_the_title().'</title>';
          }
        } else {
          echo '<title>'.get_bloginfo('name').'</title>';
        }
?>

If the SEO header of the page is filled, then it will be displayed, otherwise – the usual title of the entry. The rest of the pages will display the name of the site. Let’s move on to meta keywords:

<?php if(is_single()) { $keywords = get_post_meta($post->ID, 'seo_keywords', true);
          if($keywords != "") {
            echo '<meta name="keywords" content="'.$keywords.'"/>';
          }
         }
?>

If the “Keywords” are not filled, the meta keywords tag is not displayed. And finally meta decription:

<?php if(is_single() and $description != "") { $description = get_post_meta($post->ID, 'seo_description', true);
            echo '<meta name="description" content="'.$description.'"/>';
          } else {
            echo '<meta name="description" content="'.get_bloginfo('description').'"/>';
          }
?>

If the “Description” field is not filled, a Short description will be displayed from the Options – General menu.


Требуется подобная доработка? Напишите нам.


Name

Email


Website


Messagge