1

I have created a super simple theme. What i want to have is the ability to define an array of 3 fields for each post and page.

For example having the fields: Name, Link and a Dropdown for Type

Additionally i want to add multiple items of these "field sets" per post/page. I couldn't find any documentation on this but always results in Google which led me to WP Plugins. In general this is ood, cause in this case this seems to be possible programmatically, but bad cause i couldn't find any kind of information on this.

Hopefully someone can help me.

1
  • Have you read the official documentation yet? If not, that's a good place to start: Custom Fields - WordPress.org. Personally I'd just use a plugin as they often offer more advanced features than what stock custom fields can provide (but only if what I need is something more complex than some input fields.) Commented Dec 28, 2020 at 0:18

1 Answer 1

1

You are looking for custom meta boxes, with the add_meta_box() function:

Adds a meta box to one or more screens.

And the add_meta_boxes action hook.

Fires after all built-in meta boxes have been added:

A simple example would be if we wanted to add a "Listening to..." custom meta box, to share our mood while writing a post.

<?php
add_action( 'add_meta_boxes', 'add_meta_listening_to' );
function add_meta_listening_to() {
  add_meta_box(
    'meta_listening_to', //id
    'Listening to ...', //title
    'listeningto', //callback
    'post', //screen &/or post type
    'normal', //context
    'high', //priority
    null //callback_args
  );
};

function listeningto( $post ) { //function handle same as callback
  $ListeningToInput = get_post_meta( $post->ID, 'ListeningToInput', true );
  echo '<input name="listening_to_input" type="text" placeholder="Listening to ..." value="'. $ListeningToInput .'" style="width:100%;">';
};

add_action( 'save_post', 'save_meta_listening_to' );
function save_meta_listening_to( $post_ID ) {
  if ( isset( $_POST[ 'listening_to_input' ] ) ) {
    update_post_meta( $post_ID, 'ListeningToInput', esc_html( $_POST[ 'listening_to_input' ] ) );
  };
}; ?>

Then to display on the front end, we would use the following:

<?php echo get_post_meta( $post->ID, 'ListeningToInput', true ); ?>

Learn more

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.