How to save select drop down wordpress metaboxes?
in option have a loop from my custom post type.
<select name="music[artists]" class="skant-select" id="artists" style="width: 90%;" multiple="multiple">
<?php
$artists_meta_box_args = array(
'post_type' => array('music_artist'),
//'posts_per_page' => 20,
);
$artists_meta_box = new WP_Query($artists_meta_box_args);
if ($artists_meta_box->have_posts()):
while ($artists_meta_box->have_posts()):$artists_meta_box->the_post();
global $post;
$artistFirstname = get_post_meta($post->ID, 'artist_firstname', true);
$artistLastname = get_post_meta($post->ID, 'artist_lastname', true);
?>
<option value="<?php echo $artistFirstname . ' ' . $artistLastname; ?>"><?php echo $artistFirstname . ' ' . $artistLastname; ?></option>
<?php
endwhile;
endif;
?>
</select>
I haven't tested this out yet, but I think it should work:
function save_custom_meta_box($post_id, $post, $update) {
// Check if user is allowed to edit this
if(!current_user_can("edit_post", $post_id))
return $post_id;
// Don't save meta on auto save
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
return $post_id;
// Check if post-type (Change $slug to post-type metabox is in)
$slug = "post";
if($slug != $post->post_type)
return $post_id;
$meta_box_dropdown_value = "";
// If has value to save (remember to change "metabox-name" to the dropdown name).
if(isset($_POST["artist_dropdown"])) {
$meta_box_dropdown_value = $_POST["artist_dropdown"];
}
// Save the meta under meta-key "artist"
update_post_meta($post_id, "artist", $meta_box_dropdown_value);
}
add_action("save_post", "save_custom_meta_box", 10, 3);
I hope the comments are explaining it for you. Just remember to replace the values mentioned.
You will also need have to add a function to the rendered dropdown on what value to select after value is saved. So the rendered dropdown in the metabox should look something like this:
<select name="artist_dropdown">
<?php
$args = array(
'post_type' => array('music_artist')
);
$posts = get_posts($args);
$option_values = array();
if ( $posts ) {
foreach ( $posts as $post ) {
$artistFirstname = get_post_meta($post->ID, 'artist_firstname', true);
$artistLastname = get_post_meta($post->ID, 'artist_lastname', true);
$option_values[] = $artistFirstname . ' ' . $artistLastname;
}
}
foreach($option_values as $key => $value) {
if($value == get_post_meta($object->ID, "artist", true)) {
?>
<option selected><?php echo $value; ?></option>
<?php
} else {
?>
<option><?php echo $value; ?></option>
<?php
}
}
?>
</select>
Btw, here is an good tutorial on creating and saving wordpress metaboxes. You should also check out CMB2 which is an awesome toolkit for building metaboxes.
Related
I have two custom post types set up - "Books" and "Authors". I am using custom metadata which allows you to link a book to an author via a select box (by querying posts from the authors post type to create the select options).
This works fine, but I'm also trying to create a custom filter on the posts screen for the books post type that allows you to filter by author, which isn't behaving as expected. Here's the code I'm using to add the filter:
function book_filter() {
global $typenow;
global $wp_query;
if ( $typenow == 'book' ) {
$authors = new WP_Query(
array(
'post_type' => 'author',
'nopaging' => true
)
);
wp_reset_postdata();
/*
$authors = get_posts( array(
'post_type' => 'author',
'numberposts' => -1
));
*/
$current_author = '';
if( isset( $_GET['author'] ) ) {
$current_author = $_GET['author'];
} ?>
<select name="author" id="author">
<option value="all" <?php selected( 'all', $current_author ); ?>>All authors</option>
<?php
if ($authors->have_posts()) {
while ($authors->have_posts()) {
$authors->the_post();
if ($current_author == get_the_ID()) {
echo '<option value="' . get_the_ID() . '" selected>' . get_the_title() . '</option>';
} else {
echo '<option value="' . get_the_ID() . '">' . get_the_title() . '</option>';
}
}
}
/* foreach( $authors as $author ) { ?>
<option value="<?php echo $author->ID; ?>" <?php selected( $author->ID, $current_author ); ?>><?php echo get_the_title($author->ID); ?></option>
<?php } */
?>
</select>
<?php }
}
add_action( 'restrict_manage_posts', 'book_filter' );
function do_book_filter( $query ) {
global $pagenow;
$post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
if ( is_admin() && $pagenow=='edit.php' && $post_type == 'book' ) {
if (isset( $_GET['author'] ) && $_GET['author'] !='all' ) {
$query->query_vars['meta_key'] = 'author';
$query->query_vars['meta_value'] = $_GET['author'];
$query->query_vars['meta_compare'] = '=';
}
}
}
add_filter( 'parse_query', 'do_book_filter' );
Initially, all the authors are shown in the filter, and selecting an author to filter by does actually work. The problem is that, once it's been filtered, the authors disappear from the select box dropdown. I tried adding an else statement to if ($authors->have_posts()) {... and this confirmed that it isn't fetching posts from the authors post type after a filter has been set.
I'm also using another custom filter (removed from the code for simplicity) which just uses a standard array variable rather than a query and that one is working fine, so I guess it must something to do with the custom post type query.
You'll see in the code that I've tried get_posts (commented) as well as WP_Query but they both present the same issue.
Where am I going wrong here?
I have problem with metaboxes. I can't put values from form into metabox custom field. I have this code to add custom meta box:
//Field Marka drukarki
function wporg_add_custom_box1()
{
$screens = ['printers', 'wporg_cpt'];
foreach ($screens as $screen) {
add_meta_box(
'mark_printer_box_id', // Unique ID
'Marka drukarki', // Box title
'wporg_mark_of_printer_box_html1', // Content callback, must be of type callable
$screen // Post type
);
}
}
add_action('add_meta_boxes', 'wporg_add_custom_box1');
function wporg_mark_of_printer_box_html1($post)
{
$value = get_post_meta($post->ID, '_wporg_meta_key', true);
?>
<select name="wporg_field" id="wporg_field" class="postbox">
<option value="">Wybierz markę...</option>
<option value="samsung" <?php selected($value, 'samsung'); ?>>SAMSUNG</option>
<option value="hp" <?php selected($value, 'hp'); ?>>HP</option>
<option value="xerox" <?php selected($value, 'xerox'); ?>>XEROX</option>
<option value="brother" <?php selected($value, 'brother'); ?>>BROTHER</option>
<option value="minolta" <?php selected($value, 'minolta'); ?>>MINOLTA</option>
</select>
<?php
}
function wporg_save_printer_mark_postdata1($post_id)
{
if (array_key_exists('wporg_field', $_POST)) {
update_post_meta(
$post_id,
'_wporg_meta_key',
$_POST['wporg_field']
);
}
}
add_action('save_post', 'wporg_save_printer_mark_postdata1');
add_action('post_updated', 'wporg_save_printer_mark_postdata1');
And I'm trying to put value from form with this code:
// Submit post from WordPress
if(isset($_POST['model']) and isset($_POST['marka'])) {
// echo 'Drukarka '.$_POST['marka'].' '.$_POST['model'];
$my_post = array(
'post_type' => 'printers',
'post_title' => 'Drukarka '.$_POST['marka'].' '.$_POST['model'],
'post_content' => $_POST['opis'],
'post_status' => 'publish'
);
$post_id = wp_insert_post($my_post);
if(!function_exists('wp_generate_attachment_metadata')) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if($_FILES) {
foreach ($_FILES as $file => $array) {
if($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "Błąd przesyłania zdjęcia :" . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload($file,$post_id);
}
}
if($attach_id > 0) {
update_post_meta($post_id,'_thumbnail_id',$attach_id);
update_post_meta($post_id,'mark_printer_box_id',$_POST['marka'],true);
}
echo 'Dodano ogłoszenie';
die;
}
Code also add thumbnail to post. Post is adding without meta box mark of printer with thumbnail. Title, Description and thumbnail image are adding correctly. I think problem maybe is in update_post_meta function argument.
Thanks for some help
I have a plugin that adds a meta box with file upload form, the plugin works perfectly, displays the link of the image in the meta box (View Image), load the file, and once published the post, it views in the theme. (in the example I'm using an image file):
<?php
/* Plugin Name: Custom Meta Upload Template*/
add_action('post_edit_form_tag', 'post_edit_form_tag');
function post_edit_form_tag() {
echo ' enctype="multipart/form-data"';
}
function custom_upload() {
add_meta_box( 'meta_upload', __( 'Upload Image', 'meta_upload_domain' ),'meta_upload_callback', 'post' );}
add_action( 'add_meta_boxes', 'custom_upload' );
function meta_upload_callback( $post ) {
global $post;
$custom = get_post_custom($post->ID);
$download_image01 = get_post_meta($post->ID, '_image01', true);
echo '<p><label for="document_file">Upload document:</label><br />';
echo '<input type="file" name="document_file" id="document_file" /></p>';
echo '</p>';
if(!empty($download_image01) && $download_image01 != '0') {
echo '<p>View Image</p>';
}
}
function meta_upload_save( $post_id ) {
global $post;
if(strtolower($_POST['post_type']) === 'page') {
if(!current_user_can('edit_page', $post_id)) {
return $post_id;
}
}
else {
if(!current_user_can('edit_post', $post_id)) {
return $post_id;
}
}
if(!empty($_FILES['document_file'])) {
$file = $_FILES['document_file'];
$upload = wp_handle_upload($file, array('test_form' => false));
if(!isset($upload['error']) && isset($upload['file'])) {
$title = $file['name'];
$ext = strrchr($title, '.');
$title = ($ext !== false) ? substr($title, 0, -strlen($ext)) : $title;
$attachment = array(
'post_mime_type' => 'image',
'post_title' => addslashes($title),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post->ID
);
$attach_key = '_image01';
$attach_id = wp_insert_attachment($attachment, $upload['file']);
$existing_download = (int) get_post_meta($post->ID, $attach_key, true);
if(is_numeric($existing_download)) {
wp_delete_attachment($existing_download);
}
update_post_meta($post->ID, $attach_key, $attach_id);
}
}
}
add_action( 'save_post', 'meta_upload_save' );
and he called the file in the theme:
<?php
$download_image01 = get_post_meta($post->ID, '_image01', true);
if(!empty($download_image01) && $download_image01 != '0') { ?>
<div class="section-content">
<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />
</div>
<?php }?>
I repeat, the plugin works, but the problem is that I can not place a button or a checkbox that deletes the file when, for example, I want to edit the post, and delete the file, and of course the link "View Image" disappears
Any idea!!
Whenever you want to edit these fields echo the value of the custom fields look like this...
<input type="" value="<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />">
When you edit the post it's get the value and show the uploaded image's to you.
I don't know if that can help, but I use this code to exclude Attachment when I delete a Custom Post:
add_action('before_delete_post', 'delete_all_attached_media');
function delete_all_attached_media($post_id)
{
if (get_post_type($post_id) == "your-custom-post-type") {
$attachments = get_attached_media('', $post_id);
foreach ($attachments as $attachment) {
wp_delete_attachment($attachment->ID, 'true');
}
}
}
I'm using WP_Query to get posts from a custom post type to use the result in a metabox. Everything works great with my query. But after this query I can't get the other meta values from database.
This is my helper function to get custom field value:
function my_page_get_custom_field( $value ) {
global $post;
$custom_field = get_post_meta( $post->ID, $value, true );
if ( !empty( $custom_field ) )
return is_array( $custom_field ) ? stripslashes_deep( $custom_field ) : stripslashes( wp_kses_decode_entities( $custom_field ) );
return false;
}
Here's my query:
$sliderArgs = array(
'posts_per_page' => -1,
'post_type' => 'slider',
);
$slider = new WP_Query($sliderArgs);
if ($slider->have_posts()) {
?>
<select name="slider" id="slider">
$selectedSlide = my_page_get_custom_field('slider');
while($slider->have_posts()){
$slider->the_post();
$slideID = get_the_ID();
?><option value="<?php echo $slideID; ?>" <?php selected($selectedSlide, $slideID, true); ?>><?php the_title(); ?></option><?php
}
wp_reset_postdata(); ?>
</select>
}
And this is my other custom field which returns empty (there is a value in database and when I try to change it works great but not displaying in input value in admin):
<input type="text" name="meta_title" id="meta_title" value="<?php echo my_page_get_custom_field('meta_title'); ?>">
OK I solved it.
I used get_posts instead of WP_Query. This helped me a lot: https://core.trac.wordpress.org/ticket/18408#comment:5
I'm making a wordpress theme where you're supposed to be able to say what categories you want to display on a specific page. To do this I figured adding a meta box would be the best bet. Only now I can't seem to get the info from the meta box. It's probably something very simple but I hope you can give me this answer because I've been struggling for hours. :p
Here is where I try to get it:
<h3><?php echo get_post_meta(get_the_id(), "meta-box-dropdown", true); ?></h3>
Here is the save function:
function save_custom_meta_box($post_id, $post, $update)
{
if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__)))
return $post_id;
if(!current_user_can("edit_post", $post_id))
return $post_id;
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
return $post_id;
$slug = "post";
if($slug != $post->post_type)
return $post_id;
$meta_box_dropdown_value = "";
if(isset($_POST["meta-box-dropdown"]))
{
$meta_box_dropdown_value = $_POST["meta-box-dropdown"];
}
update_post_meta($post_id, "meta-box-dropdown", $meta_box_dropdown_value);
}
And here is the metabox code itself:
//Register custom meta boxes
function register_custom_meta_boxes() {
//Pages dropdown function
function dropdown_pages_meta() {
wp_nonce_field(basename(__FILE__), "meta-box-nonce");
?>
<div>
<label for="meta-box-dropdown">Dropdown</label>
<select name="meta-box-dropdown">
<?php
$option_values = get_categories( array(
'order' => 'ASC',
'fields' => 'names'
));
foreach($option_values as $key => $value)
{
if($value == get_post_meta($object->ID, "meta-box-dropdown", true))
{
?>
<option selected><?php echo $value; ?></option>
<?php
}
else
{
?>
<option><?php echo $value; ?></option>
<?php
}
}
?>
</select>
</div>
<?php
}