Why is my get_post_meta() not working? (Wordpress) - php

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
}

Related

WP Metabox not saving post meta

i am trying to implement a simple checkbox on the page, in order to dynamically add a Html chunk in case the user choses it, but i am unable to save the post_meta to perform this task, can someone help me? The value taken from this checkbox input is not been save on the post meta information.
This is what i got so far on my functions.php
function wporg_add_custom_box(){
$screens = ['page', 'wporg_cpt'];
foreach ($screens as $screen) {
add_meta_box(
'wporg_box_id', // Unique ID
'Entra in Flee Block', // Box title
'wporg_custom_box_html', // Content callback, must be of type callable
$screen, // Post type
'side'
);
}
}
add_action('add_meta_boxes', 'wporg_add_custom_box');
function wporg_custom_box_html($post){
$value = get_post_meta($post->ID, '_wporg_meta_key', true);
?>
<label for="wporg_field">Add "Entra in Flee" block to page</label>
</br>
<input type="checkbox" name="wporg_field" id="wporg_field" class="postbox">
<?php
}
function wporg_save_postdata($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_postdata');
You don't use the $value on wp_cusotm_box_html function.
I think it should be somthing like this:
function wporg_add_custom_box()
{
$screens = ['page', 'wporg_cpt'];
foreach ($screens as $screen) {
add_meta_box(
'wporg_box_id', // Unique ID
'Entra in Flee Block', // Box title
'wporg_custom_box_html', // Content callback, must be of type callable
$screen, // Post type
'side'
);
}
}
add_action('add_meta_boxes', 'wporg_add_custom_box');
function wporg_custom_box_html($post)
{
$value = get_post_meta($post->ID, '_wporg_meta_key', true) ? 'checked' : '';
?>
<label for="wporg_field">Add "Entra in Flee" block to page</label>
</br>
<input type="checkbox" name="wporg_field" id="wporg_field" class="postbox" <?php echo $value; ?>>
<?php
}
function wporg_save_postdata($post_id)
{
if (array_key_exists('wporg_field', $_POST)) {
update_post_meta(
$post_id,
'_wporg_meta_key',
$_POST['wporg_field']
);
} else {
delete_post_meta(
$post_id,
'_wporg_meta_key'
);
}
}
add_action('save_post', 'wporg_save_postdata');

How to save select drop down wordpress metaboxes

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 . '&nbsp' . $artistLastname; ?>"><?php echo $artistFirstname . '&nbsp' . $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.

Custom meta box upload file

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');
}
}
}

How to display the terms in a dropdown list in the admin option in wordpress

I have a custom post type which has a custom taxonomy called "country". I want a drop-down list in the Dashboard -> Theme Option to select the term name under this taxonomy. So I have created the following function:
function featured_country($show_count = false, $country_array = array()) {
$countries = get_terms( 'category', 'hide_empty=0&fields=all' );
foreach ($countries as $countr) {
$country_array[$countr->term_id] = $countr->name;
}
return $country_array;
}
Then I call this function as follows:
$this->admin_option('Front Page Option',
'Featured country', 'featured_country',
'select', '',
array('options'=>$this->featured_country(true, array(''=>'Select Category')),
'help'=>'Some helping text')
);
Unfortunately this drop-down list displays nothing. But when I put the parameter of get_terms() as “category” or "link_category" it works.
I can not understand where is my problem. How can I solve this? Please help me.
Try out this code
function get_terms_dropdown($taxonomies, $args){
$myterms = get_terms($taxonomies, $args);
$output ="<select name='TAXONOMY SLUG'>";
foreach($myterms as $term){
$root_url = get_bloginfo('url');
$term_taxonomy=$term->taxonomy;
$term_slug=$term->slug;
$term_name =$term->name;
$link = $term_slug;
$output .="<option value='".$link."'>".$term_name."</option>";
}
$output .="</select>";
return $output;
}
(I took it from this forum thread)
Here's the example where Custom taxonomy" is courses" & custom post type for that is "help_lessions"
/*
* Set Selectbox for Custom taxonomy "courses" in admin panel
*/
function custom_meta_box() {
remove_meta_box('tagsdiv-courses', 'help_lessions', 'side');
add_meta_box('tagsdiv-courses', 'Course', 'Courses_meta_box', 'help_lessions', 'side');
}
add_action('add_meta_boxes', 'custom_meta_box');
/* Prints the taxonomy box content */
function courses_meta_box($post) {
$tax_name = 'courses';
$taxonomy = get_taxonomy($tax_name);
?>
<div class="tagsdiv" id="<?php echo $tax_name; ?>">
<div class="jaxtag">
<?php
// Use nonce for verification
wp_nonce_field(plugin_basename(__FILE__), 'courses_noncename');
$help_ids = wp_get_object_terms($post->ID, 'courses', array('fields' => 'ids'));
wp_dropdown_categories('taxonomy=courses&hide_empty=0&orderby=name&name=courses&show_option_none=Select Course&selected=' . $help_ids[0]);
?>
<p class="howto">Select your Course</p>
</div>
</div>
<?php
}
/* When the post is saved, saves our custom taxonomy */
function courses_save_postdata($post_id) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if (( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) || wp_is_post_revision($post_id))
return;
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if (!wp_verify_nonce($_POST['courses_noncename'], plugin_basename(__FILE__)))
return;
// Check permissions
if ('help_lessions' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id))
return;
}
else {
if (!current_user_can('edit_post', $post_id))
return;
}
// Now, we need to find and save the data
$help_id = $_POST['courses'];
$help = ( $help_id > 0 ) ? get_term($help_id, 'courses')->slug : NULL;
wp_set_object_terms($post_id, $help, 'courses');
}
add_action('save_post', 'courses_save_postdata');

Image Caption with the_post_thumbnail in WordPress

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>';
}

Categories