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');
}
}
}
Related
I'm using the below script in the functions.php file to upload a PDF to a custom post type, however I am unsure of how to then retrieve the PDF URL within the WordPress Loop:
function add_custom_meta_boxes() {
add_meta_box('wp_custom_attachment', 'PDF Newsletter', 'wp_custom_attachment', 'newsletter', 'normal', 'high');
}
add_action('add_meta_boxes', 'add_custom_meta_boxes');
function wp_custom_attachment() {
wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');
$html = '<p class="description">';
$html .= 'Upload your PDF here.';
$html .= '</p>';
$html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25">';
$filearray = get_post_meta( get_the_ID(), 'wp_custom_attachment', true );
$this_file = $filearray['url'];
if($this_file != ""){
$html .= '<div>Current file:<br>"' . $this_file . '"</div>';
}
echo $html;
}
add_action('save_post', 'save_custom_meta_data');
function save_custom_meta_data($id) {
if(!empty($_FILES['wp_custom_attachment']['name'])) {
$supported_types = array('application/pdf');
$arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
$uploaded_type = $arr_file_type['type'];
if(in_array($uploaded_type, $supported_types)) {
$upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));
if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
} else {
add_post_meta($id, 'wp_custom_attachment', $upload);
update_post_meta($id, 'wp_custom_attachment', $upload);
}
}
else {
wp_die("The file type that you've uploaded is not a PDF.");
}
}
}
function update_edit_form() {
echo ' enctype="multipart/form-data"';
}
add_action('post_edit_form_tag', 'update_edit_form');
Here is the loop I am using, including my failed attempt of adding the PDF url:
<?php
$args = array( 'post_type' => 'newsletter', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="entry-content">';
the_content(); ?>
<?php
$news_pdf = get_post_meta( $post_id, 'wp_custom_attachment', true );
$news_pdf['url']
?>
<?php echo '</div>';
endwhile;
?>
Please first change $post_id to get_the_ID() within your loop.
Change $news_pdf['url'] to:
echo $news_pdf['url'];
Thanks
I would like to add a meta box to a custom post type that works like the product gallery meta box that Woocommerce uses. I actually have Woocommerce installed on this project.
I found the code that Woocommerce uses to create the product gallery meta box, and I can get the meta box to display, but the jQuery is not there to pull up the media lightbox that Wordpress uses to add images. I don't know if there is a hook I need to add or if I should enqueue a script?
Here is what I have so far (based on the WooCommerce code but altered for my use)
<?php
function add_mtg_meta_boxes() {
add_meta_box('mtg_hotel_gallery_meta_box', 'Hotel Gallery', 'setup_mtg_hotel_gallery_meta_box', 'meeting', 'side', 'low');
}
add_action('add_meta_boxes', 'add_mtg_meta_boxes');
function setup_mtg_hotel_gallery_meta_box($post) {
echo '<input type="hidden" name="mtg_hotel_gallery_meta_box_nonce" value="'. wp_create_nonce('mtg_hotel_gallery_meta_box'). '" />';
?>
<div id="product_images_container">
<ul class="product_images">
<?php
if ( metadata_exists( 'post', $post->ID, '_product_image_gallery' ) ) {
$product_image_gallery = get_post_meta( $post->ID, '_product_image_gallery', true );
} else {
// Backwards compatibility.
$attachment_ids = get_posts( 'post_parent=' . $post->ID . '&numberposts=-1&post_type=attachment&orderby=menu_order&order=ASC&post_mime_type=image&fields=ids&meta_key=_woocommerce_exclude_image&meta_value=0' );
$attachment_ids = array_diff( $attachment_ids, array( get_post_thumbnail_id() ) );
$product_image_gallery = implode( ',', $attachment_ids );
}
$attachments = array_filter( explode( ',', $product_image_gallery ) );
$update_meta = false;
$updated_gallery_ids = array();
if ( ! empty( $attachments ) ) {
foreach ( $attachments as $attachment_id ) {
$attachment = wp_get_attachment_image( $attachment_id, 'thumbnail' );
// if attachment is empty skip
if ( empty( $attachment ) ) {
$update_meta = true;
continue;
}
echo '<li class="image" data-attachment_id="' . esc_attr( $attachment_id ) . '">
' . $attachment . '
<ul class="actions">
<li>' . __( 'Delete', 'woocommerce' ) . '</li>
</ul>
</li>';
// rebuild ids to be saved
$updated_gallery_ids[] = $attachment_id;
}
// need to update product meta to set new gallery ids
if ( $update_meta ) {
update_post_meta( $post->ID, '_product_image_gallery', implode( ',', $updated_gallery_ids ) );
}
}
?>
</ul>
<input type="hidden" id="product_image_gallery" name="product_image_gallery" value="<?php echo esc_attr( $product_image_gallery ); ?>" />
</div>
<p class="add_product_images hide-if-no-js">
<?php _e( 'Add product gallery images', 'woocommerce' ); ?>
</p>
<?php
}
function save_mtg_hotel_gallery_meta_box($post_id) {
// check nonce
if (!isset($_POST['mtg_gallery_meta_box_nonce']) || !wp_verify_nonce($_POST['mtg_gallery_meta_box_nonce'], 'mtg_gallery_meta_box')) {
return $post_id;
}
// check capabilities
if ('meeting' == $_POST['post_type']) {
if (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
} elseif (!current_user_can('edit_page', $post_id)) {
return $post_id;
}
// exit on autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}
$attachment_ids = isset( $_POST['product_image_gallery'] ) ? array_filter( explode( ',', wc_clean( $_POST['product_image_gallery'] ) ) ) : array();
update_post_meta( $post_id, '_product_image_gallery', implode( ',', $attachment_ids ) );
}
add_action('save_post', 'save_mtg_hotel_gallery_meta_box');
?>
First To Enable the Wordpress Wp Media Uploader you have to enqueue the media js by using wp_enqueue_media(); inside you functions.php admin_enqueue_scripts hook,
function enqueue_media_uploader() {
wp_enqueue_media();
}
add_action( 'admin_enqueue_scripts', 'enqueue_media_uploader' );
and then you have to assign an id to your anchor which clicked media.uploader
will pop up.Like this...
<?php _e( 'Add product gallery images', 'woocommerce' ); ?>
And then to bind the onclick listener to add_product_image id add this line of code to your custom js file...
jQuery('#add_product_image').click(function(e) {
e.preventDefault();
var image = wp.media({
title: 'Upload Image',
multiple: false
}).open()
.on('select', function(e){
var uploaded_image = image.state().get('selection').first();
var image_url = uploaded_image.toJSON().url;
var image_id = uploaded_image.toJSON().id;
});
});
Here image_url var is uploaded or selected image src url and image_id var is id of the image or attachment.
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.
So, I have the following to add an image in the wordpress post:
<?php
global $current_user;
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter the content';
}
$tags = $_POST['post_tags'];
$custom_field_1 = $_POST['custom_1'];
$custom_field_2 = $_POST['custom_2'];
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => $_POST['cat'],
'tags_input' => $tags,
'post_status' => 'publish',
'post_type' => $_POST['post_type']
);
$pid = wp_insert_post($post);
add_post_meta($pid, 'rh_content', $custom_field_1, true);
add_post_meta($pid, 'rh_item', $custom_field_2, true);
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
}
wp_redirect( home_url() );
}
do_action('wp_insert_post', 'wp_insert_post');
?>
So, it allows an image to be uploaded which can be shown by get_the_post_thumbnail.
<?php if ( has_post_thumbnail() ) { ?>
<div class="rhmi_thumb">
<?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'rh_site') ?>
</div>
<?php } ?>
However, even without the image uploaded (ie. there is no thumbnail), it still shows class="rhmi_thumb". So, I am guessing that the whether an image is uploaded or not, the post thinks that there is a thumbnail.
What modification should be made in the post upload form?
Thanks
For uploading image into page/post you have to use wp_insert_attachment(). I have added the link of wordpress site from there you can get the example that how you can implement that. Thanks!
Is there a way to display the image caption where ever available when displaying the_post_thumbnail() image in WordPress on the posts in the primary loop.
Thanks! Appreciate all the help.
Here is an easier and shorter code :
<?php the_post_thumbnail();
echo get_post(get_post_thumbnail_id())->post_excerpt; ?>
As of WordPress 4.6, the function the_post_thumbnail_caption() has been added to core (/wp-includes/post-thumbnail-template.php).
Using the code posted here will cause the error:
Fatal error: Cannot redeclare the_post_thumbnail_caption()
I figured it out:
/************************************************************\
* Fetch The Post Thumbnail Caption
\************************************************************/
function the_post_thumbnail_caption() {
global $post;
$thumbnail_id = get_post_thumbnail_id($post->ID);
$thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));
if ($thumbnail_image && isset($thumbnail_image[0])) {
echo $thumbnail_image[0]->post_excerpt;
}
}
if(!function_exists('get_post_thumbnail_caption')) {
function get_post_thumbnail_caption($post_id = null) {
$post_id = ( null === $post_id ) ? get_the_ID() : $post_id;
$thumbnail_id = get_post_thumbnail_id($post_id);
if ($thumbnail = get_post($thumbnail_id))
return $thumbnail->post_excerpt;
return '';
}
}
if(!function_exists('the_post_thumbnail_caption')) {
function the_post_thumbnail_caption($post_id = null) {
echo get_post_thumbnail_caption($post_id);
}
}
if(has_post_thumbnail()) {
the_post_thumbnail();
the_post_thumbnail_caption();
$caption = get_post_thumbnail_caption(123);
if('' == $caption)
echo '<div class="caption">'.$caption.'</div>';
}