wordpress metabox merge select + input text - wordpress

I'm going to break my brain..
I've created a new metabox for my custom post type "book".
I'm using a lot of different type of fields like input text, checkbox, select, textarea, taxonomy select and repeatable and everything work great!
But now I'd like to do a more difficult step..
Is it possible to do a repeatable field with 2 fields inside it?
I would like have a select and an input text near it.. inside the select admin can choose the shop (es. Ibs or Amazon) and in the input field he can write the url for sell the book.
This is my code:
/* META Book */
function add_mycustom_meta_box() {
add_meta_box(
'custom_meta_box',
'Info book',
'show_custom_meta_box', // $callback
'product',
'normal',
'high');
}
// Field Array
$prefix = 'custom_';
$custom_meta_fields = array(
array(
'label' => 'Link vendita',
'desc' => 'Inserisci l url dei siti esterni',
'id' => $prefix.'repeatable',
'type' => 'repeatable',
'options' => array(
'amazon' => array(
'label' => 'Amazon',
'value' => 'amazon'
),
'ibs' => array(
'label' => 'Ibs',
'value' => 'ibs'
)
)
)
);
// Callback
function show_custom_meta_box() {
global $custom_meta_fields, $post;
// Use nonce for verification
echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
// Build metabox
echo '<table class="form-table">';
foreach ($custom_meta_fields as $field) {
// get value of this field if it exists for this post
$meta = get_post_meta($post->ID, $field['id'], true);
// begin a table row with
echo '<tr>
<th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
<td>';
switch($field['type']) {
// if repeatable
case 'repeatable':
echo '<a class="repeatable-add button" href="#">+</a>
<ul id="'.$field['id'].'-repeatable" class="custom_repeatable">';
$i = 0;
if ($meta) {
foreach($meta as $row) {
echo '<li><span class="sort hndle">|||</span>';
// Select ibis or amazon
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
foreach ($field['options'] as $option) {
echo '<option', $row == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
}
echo '</select>';
// end select
echo '<input type="text" name="'.$field['id'].'['.$i.']" id="'.$field['id'].'" value="'.$row.'" size="30" data-shop="'.$option.'" />
<a class="repeatable-remove button" href="#">-</a></li>';
$i++;
}
} else {
echo '<li><span class="sort hndle">|||</span>';
// Select ibis o amazon
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
foreach ($field['options'] as $option) {
echo '<option', $row == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
}
echo '</select>';
// Fine select
echo '<input type="text" name="'.$field['id'].'['.$i.']" id="'.$field['id'].'" value="" size="30" />
<a class="repeatable-remove button" href="#">-</a></li>';
}
echo '</ul>
<span class="description">'.$field['desc'].'</span>';
break;
} //end switch
echo '</td></tr>';
} // end foreach
echo '</table>';
}
// Save the Data
function save_custom_meta($post_id) {
global $custom_meta_fields;
// verify nonce
if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__)))
return $post_id;
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
// check permissions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id))
return $post_id;
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
// loop through fields and save the data
foreach ($custom_meta_fields as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
} // end foreach
}
add_action('save_post', 'save_custom_meta');
The repeatable field generate an array and it is ok, but what I can do to store the select value also?
Hope someone can help me
Thanks

I'm sure you can put in dynamic fields into custom Metaboxes inside the edit screen of any post type.
I build this for the Language Field Plugin into the admin page on http://wordpress.org/plugins/language-field/
I was relying on this example
http://www.mustbebuilt.co.uk/2012/07/27/adding-form-fields-dynamically-with-jquery/
Generally take these steps
Add custom Meta box with this example
http://codex.wordpress.org/Function_Reference/add_meta_box#Examples
when it comes to these lines
$mydata = sanitize_text_field( $_POST['myplugin_new_field'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_my_meta_value_key', $mydata );
loop thru the fields created with example above.

Related

Pods Custom Post types use Tags with Check Boxes like Categories

I have been using pods to create various custom post types .. I was able to find some code to do what I want for the Standard wordpress post type .. How can I modify this code to work with my pods post types ?
I wan to Change from having to type the tags to pulling in the tags with check boxes
Like this here
Here is the code `/*
* Meta Box Removal
*/
function rudr_post_tags_meta_box_remove() {
$id = 'tagsdiv-post_tag'; // you can find it in a page source code (Ctrl+U)
$post_type = 'post'; // remove only from post edit screen
$position = 'side';
remove_meta_box( $id, $post_type, $position );
}
add_action( 'admin_menu', 'rudr_post_tags_meta_box_remove');
/*
* Add
*/
function rudr_add_new_tags_metabox(){
$id = 'rudrtagsdiv-post_tag'; // it should be unique
$heading = 'Tags'; // meta box heading
$callback = 'rudr_metabox_content'; // the name of the callback function
$post_type = 'post';
$position = 'side';
$pri = 'default'; // priority, 'default' is good for us
add_meta_box( $id, $heading, $callback, $post_type, $position, $pri );
}
add_action( 'admin_menu', 'rudr_add_new_tags_metabox');
/*
* Fill
*/
function rudr_metabox_content($post) {
// get all blog post tags as an array of objects
$all_tags = get_terms( array('taxonomy' => 'post_tag', 'hide_empty' => 0) );
// get all tags assigned to a post
$all_tags_of_post = get_the_terms( $post->ID, 'post_tag' );
// create an array of post tags ids
$ids = array();
if ( $all_tags_of_post ) {
foreach ($all_tags_of_post as $tag ) {
$ids[] = $tag->term_id;
}
}
// HTML
echo '<div id="taxonomy-post_tag" class="categorydiv">';
echo '<input type="hidden" name="tax_input[post_tag][]" value="0" />';
echo '<ul>';
foreach( $all_tags as $tag ){
// unchecked by default
$checked = "";
// if an ID of a tag in the loop is in the array of assigned post tags - then check the checkbox
if ( in_array( $tag->term_id, $ids ) ) {
$checked = " checked='checked'";
}
$id = 'post_tag-' . $tag->term_id;
echo "<li id='{$id}'>";
echo "<label><input type='checkbox' name='tax_input[post_tag][]' id='in-$id'". $checked ." value='$tag->slug' /> $tag->name</label><br />";
echo "</li>";
}
echo '</ul></div>'; // end HTML
}
`

Wordpress unique checkbox

I have created a custom field "headline" in posts that is handled by a checkbox. Now I want that when the post is saved and the checkbox is checked, all "headline" checkboxes are emptied in the other posts. If this works correctly there should only be one other post with that checkbox checked.
function createHeadlineField()
{
$post_id = get_the_ID();
if (get_post_type($post_id) != 'post') {
return;
}
$value = get_post_meta($post_id, '_headline_field', true);
wp_nonce_field('headline_nonce_'.$post_id, 'headline_nonce');
?>
<div class="misc-pub-section misc-pub-section-last">
<label><input type="checkbox" value="1" <?php checked($value, true, true); ?> name="_headline_field" /><?php _e('This post is the top Story', 'pmg'); ?></label>
</div>
<?php
}
function saveHeadlineField($post_id)
{
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if (
!isset($_POST['headline_nonce']) ||
!wp_verify_nonce($_POST['headline_nonce'], 'headline_nonce_'.$post_id)
) {
return;
}
if (!current_user_can('edit_post', $post_id)) {
return;
}
if (isset($_POST['_headline_field'])) {
update_post_meta($post_id, '_headline_field', $_POST['_headline_field']);
} else {
delete_post_meta($post_id, '_headline_field');
}
}
Has anybody a clue how to do that? I guess I have to query the posts for posts with _headline_field values and delete these before updating the actual post.
thx
so if u want to query the posts with the metakey Headline u can do something like that:
$posts = array();
$query = new WP_Query(array('meta_key' => Headline, 'meta_value'=>YOURVALUE, 'posts_per_page' => LIMIT (-1 for endless)))
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$posts[] = $query->post;
}
wp_reset_postdata();
}
return $posts;
I tried to do it like that:
if (isset($_POST['_headline_field'])) {
//query posts with custom field selected
$args = array ( 'meta_key' => '_headline_field', 'meta_value' => '1', LIMIT -1 );
$headline_query = new WP_Query( $args );
if ( have_posts() ):
while ( have_posts() ) :
$headline_query->the_post();
$headline_query->delete_post_meta(get_the_ID(), '_headline_field');
endwhile;
endif;
update_post_meta($post_id, '_headline_field', $_POST['_headline_field']);
Ok, found a solution.
I just used the "delete_post_meta_by_key()" function to erase alle post meta with the key _headline_field before writing the new value into the DB.
if (isset($_POST['_headline_field'])) {
delete_post_meta_by_key( '_headline_field' );
update_post_meta($post_id, '_headline_field', $_POST['_headline_field']);
}

Multi select meta box

I have added multi select meta box to custom post-type it appears good but save only one selection . How to change the code below to save all selected options.
add_action( 'add_meta_boxes', 'add_condition_metaboxes'); function add_scondition_metaboxes() {
add_meta_box('condition', 'Информация спикеров', 'wpt_condition_author', 'condition', 'side', 'default');} function wpt_scondition_author() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="conditionmeta_noncename" id="conditionmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the author data if its already been entered
$my_dropdown = get_post_meta($post->ID, '_dappcf_i_dropdown', true);
// Echo out the field
$posts = get_posts(array('post_type'=> 'speakers', 'post_status'=> 'publish', 'suppress_filters' => false, 'posts_per_page'=>-1));
//here you add the HTML of the dropdown you add something like
echo '<p>Select the speaker: <select multiple="yes" name="_dappcf_i_dropdown" class="widefat" style="width:170px">';
foreach ($posts as $post) {
echo '<option value="', $post->ID, '">'.$post->post_title.'</option>'; }
echo '</select>'; } function wpt_save_condition_meta($post_id, $post) {
// 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['conditionmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though.
$condition_meta['_dappcf_i_dropdown'] = $_POST['_dappcf_i_dropdown'];
// Add values of $testimonial_meta as custom fields
foreach ($condition_meta as $key => $value) { // Cycle through the $testimonial_meta array!
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
} } add_action('save_post', 'wpt_save_condition_meta', 1, 2); // save the custom fields
The options are queried from other custom post-type and the number of post can be changed.

Plugin Development - wp insert post not working

I am new to plugin development for WP. I have a problem with wp_insert_post from the plugin file, tested running this plugin php file, and all the code before the wp_insert_post is fine, but once it jumps on wp_insert_post nothing happens after, stuck at 'Test15'. Tested running the insert post part of the code from test page within the theme folder and it worked. Not sure what is the problem here. Please see the code below.
function db_importer_insert_properties($properties, $category, $user_id, $post_type) {
echo 'Test9<br>';
$result = true;
echo 'Test10<br>';
if($properties) {
echo 'Test11<br>';
if(count($properties) > 0) {
echo 'Test12<br/>';
print_r($properties);
echo '<br/>';
$count = 0;
foreach($properties as $property) {
echo 'Test13<br/>';
$address =$property['address'] ; //get title
$building=$address['streetNumber'];
$street=$address['street'];
$suburb=$address['suburb'];
$state=$address['state'];
$postcode=$address['postcode'];
$title=$building. ' ' .$street.', '.$suburb.', '.$postcode.', '.strtoupper($state);
//test post
$new_post = array(
'post_title' => 'My post10 ',
'post_content' => 'This is my post10 ',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => 'uncategorized'
);
echo 'Test14<br/>';
print_r($new_post);
echo '<br/>';
echo 'Test15<br/>';
wp_insert_post($new_post);
echo 'Test16<br>';
if($post_id != 0) {
add_post_meta($post_id, "_bathrooms", esc_attr($property['features']['bathrooms']));
add_post_meta($post_id, "_bedrooms", esc_attr($property['features']['bedrooms']));
if(is_array($property['images'])) {
add_post_meta($post_id, "_images", esc_attr(implode("\n", $property['images'])));
}
else {
feedback("Post ID was 0");
}
feedback("added property $title with post_id $post_id");
$count++;
}
else {
feedback("post was failed to add");
}
}
feedback("Added $count properties");
}
else {
feedback("No properties to add.");
}
}
else {
feedback("No properties were selected");
$result = false;
}
return $result;
}
You forgot to declare your $post_id variable. Use the following:
$post_id = wp_insert_post( $new_post, true );
This will return the post ID on success or a WP error on failure.
Use print_r( $post_id ) to check the result.

Wordpress creating custom fields in custom plugins code

As per requirement, i need to create plugin with custom fields in the wordpress 3.0. I have a look at creating the plugins in wordpress. I can able to create the plugins with custom fields by hardcoded HTML fields code. Like providing input type name id etc.
But I need to create the fields like textbox, image upload, buttons using wordpress custom fields functions. Just calling the functions with type the field need to generate the fields. As like I already did in the drupal 7.
Below is the sample code for creating the text field in the drupal 7
$form['posts']['Title'] = array(
'#prefix' => '<div class="container-inline">',
'#required' => '1',
'#size' => '20',
'#type' => 'textfield',
'#title' => t('Title'),
'#suffix' => '</div>',
);
Is it possible in the wordpress?. Please guide me in the wordpress to create the custom plugins. Thanks in Advance...
Here a sample of code I've used to add custom field in my custom post type.
or you can use the plugin Advanced Custom Field to add custom field and attached them to your custom post type.
I hope this can help you !
<?php
// Metabox declaration
$prefix = 'bookmark_';
// The only way I found too pass the fields informations to the action
global $bookmark_meta_fields;
$bookmark_meta_fields = array(
array(
'label'=> 'Url',
'desc' => 'Url of the bookmark.',
'id' => $prefix.'url',
'type' => 'text'
),
array(
'label'=> 'Comments',
'desc' => 'A small comments about the bookmarks.',
'id' => $prefix.'comment',
'type' => 'textarea'
),
);
add_action('add_meta_boxes', 'vban_bookmark_metabox');
function vban_bookmark_metabox() {
add_meta_box(
'bookmark_info', // $id
'Bookmark info', // $title
'vban_bookmark_metabox_show', // $callback
'vbanBookmarks', // $page
'normal', // $context
'high'); // $priority
}
/*
* show metabox function
*/
function vban_bookmark_metabox_show() {
global $bookmark_meta_fields, $post;
// Use nonce for verification
echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
// Begin the field table and loop
echo '<table class="form-table">';
foreach ($bookmark_meta_fields as $field) {
// get value of this field if it exists for this post
$meta = get_post_meta($post->ID, $field['id'], true);
// begin a table row with
echo '<tr>
<th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
<td>';
switch($field['type']) {
case 'text':
echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="30" />
<br /><span class="description">'.$field['desc'].'</span>';
// textarea
break;
case 'textarea':
echo '<textarea name="'.$field['id'].'" id="'.$field['id'].'" cols="60" rows="4">'.$meta.'</textarea>
<br /><span class="description">'.$field['desc'].'</span>';
break;
} //end switch
echo '</td></tr>';
} // end foreach
echo '</table>'; // end table
}
/*
* SAVE metabox custom_field
*/
add_action('save_post', 'vban_bookmark_metabox_save');
// Save the Data
function vban_bookmark_metabox_save($post_id) {
global $bookmark_meta_fields;
// verify nonce
if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) {
return $post_id;
}
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
return $post_id;
}
// check permissions
if ('vbanBookmarks' == $_POST['post_type']) {
if (!current_user_can('edit_bookmark', $post_id))
return $post_id;
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
// loop through fields and save the data
foreach ($bookmark_meta_fields as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
} // end foreach
}
?>
You might also take a look at this plug-in: Advanced Custom Post Types.
"This is a framework for creating not only custom post types, roles and taxonomies in WordPress but it will also give you the ability to rapidly create custom fields (post types only)."
https://github.com/kevindees/advanced_custom_post_types

Resources