create custom field and upload image in wordpress - wordpress

i'm trying to learn the way for uploading image file through custom field but cant get the easiest code to do it. i just done a bit here:
add_action('admin_init', 'create_image_box');
function create_image_box() {
add_meta_box( 'meta-box-id', 'Image Field', 'display_image_box', 'post', 'normal', 'high' );
}
//Display the image_box
function display_image_box() {
global $post;
$image_id = get_post_meta($post->ID,'xxxx_image', true);
echo 'Upload an image: <input type="file" name="xxxx_image" id="xxxx_image" />';
// Upload done: show it now...(as thmbnail or 60 x 50)
anybody please take me to next step and show the way to display the image in blog page too.

Lets go Stepwise here:
Create custom field Meta Box for inserting Image Url in post type => post.
Update/Save the custom field value in back end.
Display the custom field value in front end.
Seeing your code it seems that you are missing #2. Try the code below to save custom field:
function save_joe_details($post_id){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
update_post_meta($post->ID, "custom_field_image", $_POST["custom_field_image"] );
}
add_action('save_post', 'save_joe_details');
Code for #3 that displaying the custom field will be:
<?php global $post;
$custom_image = get_post_custom($post->ID); ?>
<img src="<?php echo $custom_image["custom_field_image"][0] ?>" />

you could try wrap it in wp_get_attachment_url like this:-
wp_get_attachment_url( $custom_image["custom_field_image"][0] );

Related

How create new custom fields for my Theme in Wordpress

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.
You are looking for custom meta boxes, with the add_meta_box() function:
Adds a meta box to one or more screens.
Source # https://developer.wordpress.org/reference/functions/add_meta_box/
And the add_meta_boxes action hook.
Fires after all built-in meta boxes have been added:
Source # https://developer.wordpress.org/reference/hooks/add_meta_boxes/
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
Learn more about the Custom Meta Boxes # https://developer.wordpress.org/plugins/metadata/custom-meta-boxes/

Wordpress Event posts

I Need to make a event list in wordpress, show up by: "today" - "week" - "month" and all this show just my post. Witch is the best way to do that?
The author must just add the date and time of event and its appear in the current category us well.
If you just want to add the possibility for the author to add the date of an event, use the add_meta_boxes_{$post_slug} action.
This action allows to configure and print a new metabox in any post (choosen) post screen.
add_action( 'add_meta_boxes_post', 'adding_custom_meta_boxes');
add_action('save_post', 'save_sticked_metabox');
function adding_custom_meta_boxes(){
add_meta_box(
'sticked-list',
__( 'Featured list', $this->plugin_text_domain ),
'sticked_list_Render',
'post',
'side',
'default'
);
}
function sticked_list_Render(){
global $post;
$sticked = get_post_meta($post->ID, 'sticked', true);
$checked = '';
if($sticked != '' && isset($sticked)){
$checked = 'checked="checked"';
}
?>
<input type="checkbox" name="sticked" value="true" <?php echo $checked;?> > <?php _e('Check to set as pre-defined list', $this->plugin_text_domain);?>
<?
}
function save_sticked_metabox($post_id, $post){
if(isset($_POST['sticked'])){
update_post_meta($post_id, 'sticked', 'true');
}
else{
delete_post_meta($post_id, 'sticked');
}
}
This is just an example to show how to print a new metabox in the edit-post admin screen. You'll need to change the "sticked_list_render" to print a date & time picker.

how to define a sample avatar in wordpress

I want to show last comments in my side bar in wordpress, if the person who has sent a comment has gavatar it will be shown but if he does not have , in my template there is a default picture like below :
how can I cusomize this picture ? and show my favorite avatar ?
The get_avatar() function has a $default parameter, allowing you to set a custom url to an image you specify
<?php echo get_avatar( $id_or_email, $size, $default, $alt ); ?>
https://codex.wordpress.org/Function_Reference/get_avatar
Add into function.php
if(!function_exists('custom_avatar')){
function custom_avatar($avatar_defaults){
$new_default_icon = get_bloginfo('template_directory') . '/custom/images/new-avatar.png';
$avatar_defaults[$new_default_icon] = 'My Custom Avatar';
return $avatar_defaults;
}
add_filter('avatar_defaults','custom_avatar');
}

how to save meta box value?

I've created a meta box. The code is:
// Create your custom meta box
add_action( 'add_meta_boxes', 'hotel_amenities' );
// Add a custom meta box to a post
function hotel_amenities( $post ) {
add_meta_box(
'Meta Box Amenities', // ID, should be a string
'Amenities', // Meta Box Title
'amenities_content', // Your call back function, this is where your form field will go
'post', // The post type you want this to show up on, can be post, page, or custom post type
'normal', // The placement of your meta box, can be normal or side
'high' // The priority in which this will be displayed
);
}
// Content for the custom meta box
function amenities_content( $post ) {
echo '<label>Bed room</label>';
echo '<input type="text" name="amenity_bed_room" value="" />';
}
// Save your meta box content
add_action( 'save_post', 'save_amenities' );
// save newsletter content
function save_amenities(){
global $post;
// Get our form field
if( $_POST ) :
$amenities_meta = esc_attr( $_POST['amenity_bed_room'] );
// Update post meta
update_post_meta($post->ID, '_amenities_custom_meta', $amenities_meta);
endif;
}
It shows a meta box on admin post page with a text field. but it gets blank if I save or update the post after I put some thing on the text field.
Seems function save_amenities() is not working. What I am doing wrong in this code?
Also for getting that value I use the function below. Is that correct?
//get amenities meta box values
function get_amenities_meta_box() {
global $post;
$meta_values = get_post_meta($post->ID, '_amenities_custom_meta', true);
}
There are a few things going wrong there. The final value that you want to see will be displayed by the value attribute in the amenities_content function. Right now it is just displaying an empty string (""). Try putting any value in that attribute and you should see it show up in the meta box (value="this is a test").
The save_amenities function should take $post_id as a parameter. You'll need that to update the post meta-data and give a real value for the amenities_content function to echo back to the admin screen.
The amenities_content function should really have a nonce field that should then be verified by the save_amenities function. And user input should be sanitized before it is saved (I'm doing it both when I save it and when I display it. I'm not sure if that's necessary.)
try this out for the amenities_content function:
function amenities_content( $post ) {
// This is the value that was saved in the save_amenities function
$bed_room = get_post_meta( $post->ID, '_amenity_bed_room', true );
wp_nonce_field( 'save_amenity', 'amenity_nonce' );
echo '<label>Bed room</label>';
echo '<input type="text" name="amenity_bed_room"
value="' . sanitize_text_field( $bed_room ) . '" />';
}
and this for the save_amenities function:
function save_amenities( $post_id ) {
// Check if nonce is set
if ( ! isset( $_POST['amenity_nonce'] ) ) {
return $post_id;
}
if ( ! wp_verify_nonce( $_POST['amenity_nonce'], 'save_amenity' ) ) {
return $post_id;
}
// Check that the logged in user has permission to edit this post
if ( ! current_user_can( 'edit_post' ) ) {
return $post_id;
}
$bed_room = sanitize_text_field( $_POST['amenity_bed_room'] );
update_post_meta( $post_id, '_amenity_bed_room', $bed_room );
}

How can I add/update post meta in a admin menu page?

I wanted to create a plugin to batch manage posts' custom field data. I know I can add post meta by adding a meta box in the post edit screen and using add_action('save_post', 'function_to_update_meta') to trigger add meta functions.
But I don't know how to trigger the add_post_meta function in an admin menu page (such as a custom admin menu). How to do that?
Thank you in advance!
The example given in Wordpress' codex is probably the best and most secure in the way of processing information:
Add Meta Box
Copy and paste it and then fiddle around with it to get a good idea on how to control your posts and pages.
The nice part is that you don't need to worry about checking if you need to Add vs Update a given Post Meta field. Using Update Post Meta will ensure that the proper action is taken for you, even if the field doesn't exist.
The same goes for Update Option if you want to add some global controls that your plugin/theme might use.
BREAKDOWN EXAMPLE:
add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );
add_action( 'save_post', 'myplugin_save_postdata' );
These are the action hooks. The first one is executed when meta boxes are being populated within the post editor, and the second is executed when a post is added OR updated.
function myplugin_add_custom_box()
{
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'post'
);
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'page'
);
}
This function is called by the 'add_meta_boxes' action hook. Notice the name of the function and the second argument of the action hook are exactly the same. This registers your meta boxes, which post types they're supposed to appear, and what callback is used to generate the form contained inside.
function myplugin_inner_custom_box( $post )
{
wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );
$value = get_post_meta($post->ID, 'myplugin_new_field') ? get_post_meta($post->ID, 'myplugin_new_field') : 'New Field';
echo '<label for="myplugin_new_field">';
_e("Description for this field", 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="'.$value.'" size="25" />';
}
This is the function that is called by the registered meta boxes to generate the form automatically. Notice how the function is called 'myplugin_inner_custom_box' and the 3rd argument in your meta box registration is also called 'myplugin_inner_custom_box'.
The wp_nonce_field() generates a hidden field in your form to verify that data being sent to the form actually came from Wordpress, and can also be used to end the function in case other plugins are using the 'save_post' action hook.
Notice also that the $post object is being passed in as an argument. This will allow you to use certain properties from the post object. I've taken the liberty of checking to see if there is get_post_meta() returns anything with the given post ID. If so, the field is filled with that value. If not, it is filled with 'New Field'.
function myplugin_save_postdata( $post_id )
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
return;
if ( 'page' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
$mydata = $_POST['myplugin_new_field'];
update_post_meta($post_id, 'myplugin_new_field', $mydata);
}
This is the function that is called by the 'save_post' action hook. Notice how the second argument of the second action hook and this function are both called 'myplugin_save_postdata'. First, there are a series of verifications our plugin must pass before it can actually save any data.
First, we don't want our meta boxes to update every time the given post is auto-updating. If the post is auto-updating, cancel the process.
Secondly, we want to make sure the nonce data is available and verify it. If no nonce data is available or is not verified, cancel the process.
Thirdly, we want to make sure the given user has the edit_page permission. The function first checks the post type, and then checks the appropriate permission. If the user does not have that permission, cancel the process.
Lastly, our plugin has finally been verified and we want to save the information. I took the liberty of adding in the final update_post_meta() line to show you how it all comes together.
Notice how $post_id was passed into the function as an argument. This is one of the pieces needed for the update_post_meta() function. The key was named 'myplugin_new_field' and the value of that metadata is now saved as whatever you input into that custom input field in your custom meta box.
That's about as easy as I can explain the whole process. Just study it, and get your hands dirty with code. The best way to learn is through application rather than theory.
The answer was from the same question I asked somewhere else
And I created my version of example
I added some console.log function for testing, but this is basically doning the same thing as #Chris_() answer:
Menu callback function to generate menu content (PHP):
function ajax_menu_callback() {
?>
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>Test</h2>
<br />
<form>
<input id="meta" type ="text" name="1" value="<?php echo esc_html( get_post_meta( 1, 'your_key', true) ); ?>" />
<?php submit_button(); ?>
</form>
</div>
<?php
}
Then the javascript to print on the admin side (javascript, don't forget to include a jquery library):
jQuery(document).ready(function() {
$("form").submit(function() {
console.log('Submit Function');
var postMeta = $('input[name="1"]').val();
console.log(postMeta);
var postID = 1;
var button = $('input[type="submit"]');
button.val('saving......');
$.ajax({
data: {action: "update_meta", post_id: postID, post_meta: postMeta, },
type: 'POST',
url: ajaxurl,
success: function( response ) { console.log('Well Done and got this from sever: ' + response); }
}); // end of ajax()
return false;
}); // end of document.ready
}); // end of form.submit
Then the PHP function handle update_post_meta (PHP):
add_action( 'wp_ajax_update_meta', 'my_ajax_callback' );
function my_ajax_callback() {
$post_id = $_POST['post_id'];
$post_meta = $_POST['post_meta'];
update_post_meta( $post_id, 'your_key', $post_meta );
echo 'Meta Updated';
die();
} // end of my_ajax_callback()

Resources