Advertisement
krzxsiek

Metabox

Jan 30th, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.87 KB | None | 0 0
  1. <?php
  2.  
  3. /* ############################################### */
  4. // Kod w header.php
  5. $meta = strb_get_meta('_stref_ban');
  6. //echo "Post: ".$post_id."<br><br>";
  7. //echo serialize( $get_meta );
  8. echo 'Meta: ' . $meta . '<br>';
  9. if ($meta == '1') {
  10.    echo 'Tresc 1';
  11. } elseif ($meta == '2') {
  12.    echo 'Tresc 2';
  13. }
  14. /* ############################################### */
  15. // Kod w functions.php
  16. function strb_get_meta( $value ) {
  17.     global $wp_query;
  18.     $post_id = $wp_query->post->ID;
  19.  
  20.     $field = get_post_meta( $post_id, $value, true );
  21.     if ( !empty( $field ) ) {
  22.         return is_array( $field ) ? stripslashes_deep( $field ) : stripslashes( wp_kses_decode_entities( $field ) );
  23.     } else {
  24.         return false;
  25.     }
  26. }
  27.  
  28. function strb_add() {
  29.     $screens = ['post', 'page'];
  30.     foreach ($screens as $screen) {
  31.         add_meta_box(
  32.             'strb_box_id',          // Unique ID
  33.             'Strefa banerowa',      // Box title
  34.             'strb_html',            // Content callback, must be of type callable
  35.             $screen                 // Post type
  36.         );
  37.     }
  38. }
  39. add_action('add_meta_boxes', 'strb_add');
  40.  
  41. function strb_html($post) {
  42.     $value = get_post_meta($post->ID, '_stref_ban', true);
  43.     ?>
  44.     <select name="strb_field" id="strb_field" class="postbox">
  45.         <option value="">Domyślna</option>
  46.         <option value="1" <?php selected($value, '1'); ?>>Opcja 1</option>
  47.         <option value="2" <?php selected($value, '2'); ?>>Opcja 2</option>
  48.     </select>
  49.     <?php
  50. }
  51.  
  52. function strb_save_postdata($post_id) {
  53.     if (array_key_exists('strb_field', $_POST)) {
  54.         update_post_meta(
  55.             $post_id,
  56.             '_stref_ban',
  57.             filter_input( INPUT_POST, 'strb_field', FILTER_VALIDATE_INT)
  58.         );
  59.     }
  60. }
  61. add_action('save_post', 'strb_save_postdata');
  62. /* ############################################### */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement