The WPAlchemy_MetaBox
PHP class can be used to create WordPress meta boxes quickly. It will give you the flexibility you need as a developer, allowing you to quickly build custom meta boxes for your themes and plugins.
- Key Features and Benefits
- Defining a Meta Box is Easy
- Install and Setup (Video)
- Meta Box Setup Options
- The Guts of the Meta Box
- How to Use It! (show class methods)
- Repeating Field Groups
- Filter Specific Templates, Categories, Tags and Posts
- Using The Meta Box Values In Your Template
- Download
- Contribute
Key Features and Benefits
- Easy to learn and integrate: good documentation and support is always important (I use the code myself and keep it up-to-date). Integration is a snap, as simple as including the class and using it.
- Easy setup code: some of the details involved in saving, retrieving and working with the meta data are abstracted to ease development.
- Flexible usage: the class acts as an aid for meta box development. By design you can use the class functions or your current development practices, which ever you feel most comfortable with for your development.
- HTML and CSS separation: the HTML and CSS for your meta boxes remain separate from the core code, you can design your meta boxes to your liking, providing you the greatest flexibility during development.
Defining a Meta Box is Easy
// include the class in your theme or plugin include_once 'WPAlchemy/MetaBox.php'; // include css to help style our custom meta boxes add_action( 'init', 'my_metabox_styles' ); function my_metabox_styles() { if ( is_admin() ) { wp_enqueue_style( 'wpalchemy-metabox', get_stylesheet_directory_uri() . '/metaboxes/meta.css' ); } } $custom_metabox = new WPAlchemy_MetaBox(array ( 'id' => '_custom_meta', 'title' => 'My Custom Meta', 'template' => STYLESHEETPATH . '/custom/meta.php' ));
That’s it! The above code shows the basic definition needed to setup a custom meta box.
Tip Use WP_PLUGIN_DIR
or WP_PLUGIN_URL
if you are embedding wpalchemy in a custom wordpress plugin.
Install and Setup (Easy)
Tip Select 720 HD mode and watch it fullscreen or click the YouTube button to watch it on YouTube.
Setup Options
The following are the different setup options that you can use in the initial class setup array:
id
'id' => '_custom_meta'
Each meta box that you create requires an ID, this is the value that is saved into the wp_postmeta
table. Starting your name with an underscore will effectively hide it from also appearing in the custom fields area.
title
'title' => 'Custom Meta'
This is the title of the meta box that appears in the WordPress UI.
template
'template' => STYLESHEETPATH . '/custom/meta.php'
You must define a template file for the contents of your meta box.
types
'types' => array('post','page')
This will default to post
and page
types, to add your meta box to custom post types you must define the types option.
context
'context' => 'normal'
The part of the page where the edit screen section should be shown (‘normal’, ‘advanced’, or ‘side’).
priority
'priority' => 'high'
The priority within the context where the meta box should show (‘high’ or ‘low’).
autosave
'autosave' => TRUE
Used to decide if meta box content should be autosaved.
mode
'mode' => WPALCHEMY_MODE_ARRAY // defaults to WPALCHEMY_MODE_ARRAY
Can be set to WPALCHEMY_MODE_ARRAY
or WPALCHEMY_MODE_EXTRACT
. Setting this option to WPALCHEMY_MODE_ARRAY
(set by default) will cause the class to store all of its values as an associative array in a single meta entry. Setting this option to WPALCHEMY_MODE_EXTRACT
will cause the class to extract all the first tier variables (fields) and create individual meta entries in the wp_postmeta
table. This article has more info on this option.
prefix
'prefix' => '_my_' // defaults to NULL
When the mode
option is set to WPALCHEMY_MODE_EXTRACT
, you have to take care to avoid name collisions with other meta entries. The easiest way to do this is to add a prefix to your variables. This article has more info on this option.
Exclude / Include Options
exclude_… and include_…
exclude_template exclude_category_id exclude_category exclude_tag_id exclude_tag exclude_post_id include_template include_category_id include_category include_tag_id include_tag include_post_id
Read more about Filtering Specific Templates, Categories, Tags and Posts
Action / Filter Options
init_action
'init_action' => 'my_init_action_func' // defaults to NULL
Callback used on the WordPress “admin_init” action, the main benefit is that this callback is executed only when the meta box is present.
output_filter
'output_filter' => 'my_output_filter_func' // defaults to NULL
Callback used to override when the meta box gets displayed, must return TRUE
or FALSE
to determine if the meta box should or should not be displayed.
save_filter
'save_filter' => 'my_save_filter_func' // defaults to NULL
Callback used to override or insert meta data before saving occurs. The callback function gets passed two parameters: $meta
(first param) meta box data array and $post_id
(second param). You can also halt saving by returning FALSE.
save_action
'save_action' => 'my_save_action_func' // defaults to NULL
Callback used to execute custom code after saving. The callback function gets passed two parameters: $meta
(first param) meta box data array and $post_id
(second param).
head_filter
'head_filter' => 'my_head_filter_func' // defaults to NULL
Callback used to insert content into the <head>
tag. Also used to override or insert <style>
or <script>
tags into the head.
head_action
'head_action' => 'my_head_action_func' // defaults to NULL
Callback used to insert content into the <head>
tag.
foot_filter
'foot_filter' => 'my_foot_filter_func' // defaults to NULL
Callback used to insert content into the footer. Also used to override or insert <script>
tags into the footer.
foot_action
'foot_action' => 'my_foot_action_func' // defaults to NULL
Callback used to insert content into the footer.
Display Options
hide_editor
'hide_editor' => TRUE // defaults to NULL
Used to hide the default content editor in a page or post.
hide_title
'hide_title' => TRUE // defaults to NULL
Used to hide the meta box title.
lock
'lock' => WPALCHEMY_LOCK_TOP // defaults to NULL
Used to lock a meta box in place, possible values are: “top”, “bottom”, “before_post_title”, “after_post_title”, it is recommened that you use the following constants to set the value of this option: WPALCHEMY_LOCK_TOP
, WPALCHEMY_LOCK_BOTTOM
, WPALCHEMY_LOCK_BEFORE_POST_TITLE
, WPALCHEMY_LOCK_AFTER_POST_TITLE
.
Using WPALCHEMY_LOCK_BEFORE_POST_TITLE
or WPALCHEMY_LOCK_AFTER_POST_TITLE
allows you to prevent other meta boxes from being dragged and dropped above or below your custom meta box. This is really useful when you are not using the editor (e.g. its hidden) and you want to have your own custom fields always at the top.
view
'view' => WPALCHEMY_VIEW_ALWAYS_OPENED // defaults to NULL
Used to set the initial view state of the meta box, possible values are: “opened”, “closed”, “always_opened”, it is recommended that you use the follwing constants to set the value of this option: WPALCHEMY_VIEW_START_OPENED
, WPALCHEMY_VIEW_START_CLOSED
, WPALCHEMY_VIEW_ALWAYS_OPENED
.
hide_screen_option
'hide_screen_option' => TRUE // defaults to NULL
Used to hide the show/hide checkbox option from the screen options area.
The Guts of the Meta Box
You probably noticed that the actual contents of the meta box come from the meta.php
file. I’ve decided to leave the meta box content definition up to you vs having the class create form fields (this should give a you more freedom to manipulate the meta box contents to your liking).
Lets review the different parts to this solution, first off the meta.php
:
How to Use It!
All of the functions in this class are very WordPress friendly. If you are familiar with the WordPress Loop, you should have no problem using this class.
When working on your meta box template file (meta.php
) there are a few variables available to you:
$post; // this is the current post, use $post->ID for the current post ID $metabox; // this is the meta box helper object $mb; // same as $metabox, a shortcut instead of writing out $metabox $meta; // this is the meta data
Lets go over the different functions available in the class and how to use them. Important: you should refer to the meta.php
HTML example above by using the line numbers given below. This should help you see the code in action.
the_field($name)
Use this function to set the current working field:
<?php $metabox->the_field('description');
the_name([$name])
This function will print the form field name. If you’ve set the current working field with the_field($name)
then you can simply do the following:
$metabox->the_name();
If you have not set the current working field prior to calling this function, you can manually pass in a field’s name:
$metabox->the_name('name');
get_the_name([$name])
Same as the_name([$name])
except that it returns a value instead of printing out the value.
the_value([$name])
Use this function to get the current value of the field.
$metabox->the_value();
If you have not set the current working field prior to calling this function, you can manually pass in a field’s name:
$metabox->the_value('name');
get_the_value([$name])
Same as the_value([$name])
except that it returns a value instead of printing out the value.
if ($metabox->get_the_value() == '_self') echo $selected;
the_index()
Used inside have_fields()
and have_fields_and_multi()
to print the current index number.
get_the_index()
Same as the_index()
except that it returns a value instead of printing out the value.
is_first()
Used inside have_fields()
and have_fields_and_multi()
to check if the field group is the first field group. When using the_group_open()
and the_group_close()
, the first HTML element will automatically have a css class of first
.
is_last()
Used inside have_fields()
and have_fields_and_multi()
to check if the field group is the last field group. When using the_group_open()
and the_group_close()
, the last HTML element will automatically have a css class of last
.
is_value([$value])
Uses to check the existence of a value.
<input type="radio" name="<?php $mb->the_name(); ?>" value="admin"<?php echo $mb->is_value('admin')?' checked="checked"':''; ?>/> Admin
The above would be equivalent to:
<input type="radio" name="<?php $mb->the_name(); ?>" value="admin"<?php echo ($mb->get_the_value() == 'admin')?' checked="checked"':''; ?>/> Admin
have_fields($name,$length)
This function is used during a loop. It helps you create multiple instances of a field or group of fields.
while($metabox->have_fields('authors',3))
Inside of the loop you can use the_name()
and the_value()
to help you define your form fields.
<?php while($metabox->have_fields('authors',3)): ?> <p> <input type="text" name="<?php $metabox->the_name(); ?>" value="<?php $metabox->the_value(); ?>"/> </p> <?php endwhile; ?>
The above is equivalent to writing:
<p> <input type="text" name="_custom_meta[authors][0]" value="<?php if(!empty($meta['authors'][0])) echo $meta['authors'][0]; ?>"/> </p> <p> <input type="text" name="_custom_meta[authors][1]" value="<?php if(!empty($meta['authors'][1])) echo $meta['authors'][1]; ?>"/> </p> <p> <input type="text" name="_custom_meta[authors][2]" value="<?php if(!empty($meta['authors'][2])) echo $meta['authors'][2]; ?>"/> </p>
Another really cool thing you can do with have_fields($name,$length)
, is to define field groups like the following representation:
_custom_meta[links][0][title] _custom_meta[links][0][url] _custom_meta[links][0][nofollow] _custom_meta[links][0][target]
<?php while($metabox->have_fields('links',5)): ?> <p> <?php $metabox->the_field('title'); ?> <input type="text" name="<?php $metabox->the_name(); ?>" value="<?php $metabox->the_value(); ?>"/> <input type="text" name="<?php $metabox->the_name('url'); ?>" value="<?php $metabox->the_value('url'); ?>"/> <br/><?php $metabox->the_field('nofollow'); ?> <input type="checkbox" name="<?php $metabox->the_name(); ?>" value="1"<?php if ($metabox->get_the_value()) echo ' checked="checked"'; ?>/> Use <code>nofollow</code> <?php $selected = ' selected="selected"'; ?> <br/><?php $metabox->the_field('target'); ?> <select name="<?php $metabox->the_name(); ?>"> <option value=""></option> <option value="_self"<?php if ($metabox->get_the_value() == '_self') echo $selected; ?>>_self</option> <option value="_blank"<?php if ($metabox->get_the_value() == '_blank') echo $selected; ?>>_blank</option> <option value="_parent"<?php if ($metabox->get_the_value() == '_parent') echo $selected; ?>>_parent</option> <option value="_top"<?php if ($metabox->get_the_value() == '_top') echo $selected; ?>>_top</option> </select> </p> <?php endwhile; ?>
have_fields_and_multi($name[, $options])
This function is similar to have_fields($name,$length)
. You will notice that it does not use the $length
parameter. But it provides additional functionality. It allows you to setup a custom “add” HTML element that can be used to create unlimited copies of your field or field group.
The $options
param is an associative array which can contain the following values (each being optional).
$options = array('length' => 3, 'limit' => 10);
length: is the number of field groups to display initially (a minimum of sorts).
limit: is the hard limit at which point the “add new link” will stop working.
A simple example would be a meta box for adding a list of links: you may have two fields, one for a title and the other for a URL, using the features of the class you can easily setup an “add new link” button which would automatically spawn new instances of the field group you defined. Basically, clicking the “add new link” button again would spawn another field group, and so on.
The following is an example of using this function:
<h4>Documents</h4> <a style="float:right; margin:0 10px;" href="#" class="dodelete-docs button">Remove All</a> <p>Add documents to the library by entering in a title, URL and selecting a level of access. Upload new documents using the "Add Media" box.</p> <?php while($mb->have_fields_and_multi('docs')): ?> <?php $mb->the_group_open(); ?> <?php $mb->the_field('title'); ?> <label>Title and URL</label> <p><input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>"/></p> <?php $mb->the_field('link'); ?> <p><input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>"/></p> <?php $mb->the_field('access'); ?> <p><strong>Access:</strong> <input type="radio" name="<?php $mb->the_name(); ?>" value="admin"<?php echo $mb->is_value('admin')?' checked="checked"':''; ?>/> Admin <input type="radio" name="<?php $mb->the_name(); ?>" value="editor"<?php echo $mb->is_value('editor')?' checked="checked"':''; ?>/> Editor <input type="radio" name="<?php $mb->the_name(); ?>" value="subscriber"<?php echo $mb->is_value('subscriber')?' checked="checked"':''; ?>/> Subscriber <a href="#" class="button" style="margin-left:10px;" onclick="jQuery(this).siblings().removeAttr('checked'); return false;">Remove Access</a> <a href="#" class="dodelete button">Remove Document</a> </p> <?php $mb->the_group_close(); ?> <?php endwhile; ?> <p style="margin-bottom:15px; padding-top:5px;"><a href="#" class="docopy-docs button">Add Document</a></p>
the_group_open([$tag])
This function is used to create a container element around your fields, by default the HTML tag used is a DIV. The HTML element will be printed out.
<?php $mb->the_group_open(); ?>
get_the_group_open([$tag])
Same as the_group_open([$tag])
except that it returns a value instead of printing out the value.
the_group_close()
This function is used to close the container element around your fields. The HTML element will be printed out.
<?php $mb->the_group_close(); ?>
get_the_group_close()
Same as the_group_close()
except that it returns a value instead of printing out the value.
Creating an “Add” Button
This button is used to create new instances of your field or field group. Adding a docopy-GROUPNAME
css class to an HTML element will make it clickable. GROUPNAME is the name you used in the have_fields_and_multi($name)
function.
<p><a href="#" class="docopy-docs button">Add Document</a></p>
Creating a “Delete” Button
This button is used to remove and instance of your field or field group. Adding a dodelete
css class to an HTML element will make it clickable. This button has to be between the_group_open()
and the_group_close()
.
<a href="#" class="dodelete button">Remove Document</a>
Creating a “Delete All” Button
This button is used to remove all instances of your field or field group. Adding a dodelete-GROUPNAME
css class to an HTML element will make it clickable. This button does NOT have to be between the_group_open()
and the_group_close()
. GROUPNAME is the name you used in the have_fields_and_multi($name)
function.
<a href="#" class="dodelete-docs button">Remove All</a>
The “remove” and “remove all” buttons are optional. You can still delete fields by simply deleting their values and clicking the post “Update” button. Important: Adding and removing elements will always require you to click the post “Update” button.
Filter Specific Templates, Categories, Tags and Posts
I often find myself creating meta boxes which apply to a specific template or post. With this class, you to filter your meta boxes a few different ways: by template file, category_id, category name/slug, tag_id, tag name/slug and post_id.
When creating a new WPAlchemy_MetaBox
instance the following options are available:
exclude_template exclude_category_id exclude_category exclude_tag_id exclude_tag exclude_post_id include_template include_category_id include_category include_tag_id include_tag include_post_id
When assigning values to these options you can assign a value as a single value, an array, or a comma separated list. You will see usage examples below.
You can use as many options to achieve the results you want. Use the exclude options exclusively or the include options exclusively or combine them both for more advanced filtering.
It might be helpful to keep the following in mind: the excluding and including will be processed in the order listed above, excludes are processed first and then includes are processed, additionally templates come before categories which come before tags which come before posts.
Using Exclude Options
The exclude options allow you to exclude a template, category, tag, or post from displaying the meta box.
The following example excludes the “product” template from displaying the meta box, however all other templates will display the meta box.
new WPAlchemy_MetaBox(array ( 'id' => '_custom_meta', 'title' => 'My Custom Meta', 'template' => STYLESHEETPATH . '/custom/meta.php', 'exclude_template' => 'product.php' ));
Using Include Options
The include options allow you to only include a template, category, tag, or post to display the meta box.
This is different from the exclude option, as only the item that you specify will display the meta box, everything else would be excluded.
In the following example, pages that use the “product” and “press” templates will be the only pages that display the meta box, all other templates would not display the meta box.
new WPAlchemy_MetaBox(array ( 'id' => '_custom_meta', 'title' => 'My Custom Meta', 'template' => STYLESHEETPATH . '/custom/meta.php', 'include_template' => array('product.php','press.php') // use an array for multiple items // 'include_template' => 'product.php,press.php' // comma separated lists work too ));
Using Both Exclude and Include Options
For the most part you will do fine using exclude and include options separately from each other.
When you use exclude and include options together the include option will override any exclude options. Knowing this you can do some advanced filtering.
The following example will exclude all pages that use the “product” template except for a specific product page.
new WPAlchemy_MetaBox(array ( 'id' => '_custom_meta', 'title' => 'My Custom Meta', 'template' => STYLESHEETPATH . '/custom/meta.php', 'exclude_template' => array('product.php'), 'include_post_id' => 85 ));
More Exclude and Include Examples
The following filters your meta box to posts which have the “download” tag or is post_id 97
new WPAlchemy_MetaBox(array ( 'id' => '_custom_meta', 'title' => 'My Custom Meta', 'template' => STYLESHEETPATH . '/custom/meta.php', 'include_tag' => 'download', 'include_post_id' => 97 ));
The following filters your meta box by excluding it from several specific posts, unless those posts have a the “download” tag
new WPAlchemy_MetaBox(array ( 'id' => '_custom_meta', 'title' => 'My Custom Meta', 'template' => STYLESHEETPATH . '/custom/meta.php', 'exclude_post_id' => array(45,48,56,57,88,91,92,93) 'include_tag' => 'download' ));
The following filters your meta box to posts that belong to the “WordPress” category
new WPAlchemy_MetaBox(array ( 'id' => '_custom_meta', 'title' => 'My Custom Meta', 'template' => STYLESHEETPATH . '/custom/meta.php', 'exclude_category' => 'WordPress', // 'exclude_category_id' => 12 // using category IDs also work ));
Using The Meta Box Values In Your Template
Using meta box values in your templates is just as straight forward, in your template file you would do something like the following:
// usually needed global $custom_metabox; // get the meta data for the current post $custom_metabox->the_meta(); // set current field, then get value $custom_metabox->the_field('name'); $custom_metabox->the_value(); // get value directly $custom_metabox->the_value('description'); // loop a set of fields while($custom_metabox->have_fields('authors')) { $custom_metabox->the_value(); } // loop a set of field groups while($custom_metabox->have_fields('links')) { $custom_metabox->the_value('title'); $custom_metabox->the_value('url'); if ($custom_metabox->get_the_value('nofollow')) echo 'is-nofollow'; $custom_metabox->the_value('target'); }
In the code above, $custom_metabox
is the object variable you created in functions.php
when you used new WPAlchemy_MetaBox
.
Again, you are not limited to having to use the class functions, you can use the default WordPress function get_post_meta()
as such:
// instead of using helper functions, you can also use ... $meta = get_post_meta(get_the_ID(), $custom_metabox->get_the_id(), TRUE); // or ... (same as above) // $meta = $custom_metabox->the_meta(); echo $meta['name']; echo $meta['description']; foreach ($meta['authors'] as $author) { echo $author; } foreach ($meta['links'] as $link) { echo $link['title']; echo $link['url']; if ($link['nofollow']) echo 'is-nofollow'; echo $link['target']; }
Download
WPAlchemy MetaBox Class, this project is on github
Contribute
Are you using this class? If so, become a contributor to it’s growth and stability. If you have problems using it, definitely let me know (I like to write and use stable code). Equally, if you have ideas to make it even better, I want to hear that too.
First of all… Amazing explanation, this is going to solve a great deal of issues we have been having in simplifying the deployment of these metaboxes.
I have a few questions though which I am hoping you would be able to address or assist in resolving.
1) A problem we always run into even with wordpress 3.0 is the ability to show a metabox which allows you to show all the images and file attachments associated with a post. If you could somehow extend your plugin which would allow one to include and style the display of images it would be very very helpful (possibly using timthum to show the thumbnails of such images all with the same size). I am assuming this is probable a very simple addition (when dealing with images) but what would be excellent is if it would automatically also separate out any other files which might have been uploaded (again with the ability to style these). On the front end we have use the plugin attachment xtender which I remember worked fairly well.
2) As a separate point but expanding on the above request, I feel it would be highly valuable if the media upload capabilities could be somehow simplified while still using the word press media upload database structure. I personally find the default uploaded to be far to complicated for many users I have shown it to. My suggestion is a simple upload button one can add to a metabox with an optional URL input field… Clicking on the upload button would bring up your file browser where you can select one/more file and click save, this would then automatically upload each one through ajax with a progress bar online with the page, present a thumbnail and if defined in the metabox the applicable wordpress mediafields associated with that image. Now, if someone wants to modify an image such as cropping he can click the image or edit link which would bring up the standard wordpress media for that image. My logic here is that in nearly every situation this would be the absolute best way of doing things and your code here for meta boxes would allow so many individuals customize it to meet their needs.
3) These next few items fall outside the scope of your code a bit but I am hoping you have a solution for me and others as I have spent hours trying to resolve them.
A- I have been trying to find a way to directly influence the location of post meta boxes. What We have been looking for is a way to force the position of a meta box into a default location other than just priority of high. Additionally, if we were able to disable moving a meta box would be very helpful and being able to tell wordpress to reset the location of a meta box if it was moved by a user. On the same level I don’t know of a way to place a custom meta box above or directly below the default wordpress title.
B- do you know of a way to directly order (or reorder) the wordpress default menu items. Example- Through post types you can of course create a new admin menu but what I am unable to do is place such a menu item above the dashboard or for that matter change the location of the dashboard. There are plugins which allow this but I am hoping there is some simple code I can include in the functions file.
B-
First off, thank you! This PHP class helper is awesome, and greatly makes custom field creation easy! So thank you!
I do have a question concerning child themes. What can be done so that the required files/folders for WPAlchemy could be placed inside the child theme rather than the parent?
For instance I’m using Hybrid and if I want to use WPAlchemy I have to place the files in the Hybrid parent folder. I can still edit the functions.php file within the child to “activate” WPAlchemy. Though the meta files are in the parent theme folder.
Any ideas?
Scott, the WPAlchemy folder can be placed anywhere you would like, you just have to use the correct path to include the class file as well as the meta template file.
Great idea, thank you!
I decided to swap out TEMPLATEPATH with STYLESHEETPATH since I’m dealing with child themes.
Thanks again for the quick response.
Chris, thank you very much for your comments, your comment is a perfect example of the feedback that I am looking for.
preface: My ultimate goal for WPAlchemy is to make it a small and nimble framework built on top of WordPress, specifically designed for plugin and theme authors (and developers). Currently … the MetaBox class is just the first class in a group of classes that will comprise the framework.
#3A: this one I think actually falls within the scope of the code as it is functionality that directly relates to meta boxes and its general purpose.
#3B: I think this is a valid need and may be a new component all on its own WPAlchemy_AdminMenu(s) … I will give this one further consideration.
#1: I think this functionality actually falls outside of the scope of the class as it seems like a niche case to me, however I want to design the class with enough flexibility that anyone can include any additional libraries to use however they would like within their meta boxes.
Overly simplified solution: To do what you are describing within a meta box, I believe would not be too difficult, you would first need to get a list of images/attachements associated with the post, if these images are in the post content, you might have to parse the content and look for img tags, then you would use the timthumb lib and list out the images that were found. I have not yet explored the media uploader and its functionality enough to know how it stores is data and what data is available.
#2: I think this one also falls outside of the scope of the class, but I do agree with you that the media/file manager can be simplified, and perhaps this can become a specific component within the framework.
Overly simplified solution: again what you have described is totally doable, you would just have to include the needed libraries and simply create your own upload form field and handle the uploaded file (note: the class still needs a revision, something like a hook to allow developers to tap into the save routine of the class, in this case writing custom upload handler)
Hopefully this is the last question you’ll get from me. 🙂
Still concering child themes. Since the power of child themes lies in not touching the parent theme files. How do I go about calling field values from within the child themes functions.php? While true I could create a page.php in the child directory and call the value (ex. $custom_metabox->the_value(‘description’);) from there. But the child page.php would overwrite the parent’s page.php, which in my opinion defeats the purpose of a child themes.
All that to say, I’m trying to use an action hook to call the values directly from the child’s functions.php and I’m getting the following errer: Fatal error: Call to a member function the_value() on a non-object
Never mind, I’m an idiot. I was calling the value too soon. Like before the Loop too soon.
Also, if you are using theexample, you will have to access it globally doing something like the following:
$custom_metabox
inside of a function, per yourThank you very much for your quick reply.
I greatly appreciate your suggestions on these topics.
Given your interest in additional features that might be needed here are some others which I have noticed although again they might not be related to this exact meta box functionality.
1) An issue which I recently ran into was that I wanted to create a custom taxonomy/meta box for “article source”. My objective was to essentially have a custom taxonomy were the items within it were essentially entries for different source publications (ie – The Washington Post). I goal was essentially very basic… just giving the editor the ability to pick from a drop down list of source publications so he could define the source. As I am assuming you are aware this is totally possible… the problem I ran into was that it seems I am unable to assign a meta box or additional custom field to a taxonomy. The goal here was to be able to assign additional fields for each taxonomy entry so I could for example add an image to each article source and have the site admin manage such sources all from one location. Do you think you can somehow modify your plugin to allow for this to happen? (Possibly remove the taxonomy description field and essentially have meta box values stores in there to use the default database structure)?
2) One area I got confused about related to the new exact and array storage functions you described. Recently I ran into an issue in which I wanted to use wordpress for a real estate site. The problems came into play when I was using custom fields to store property related attributes and then tried to create a public search which would query such entries. The problem was that it took very long to query the system ( I am assuming because the meta keys/values are not indexed individually)… So, my question here is does your solution somehow resolve this problem? If so, what are the side effects of your new storage system or when would it make sense to use your way?).
3) This is a big one: I find it is very difficult for users to develop custom meta boxes which include things such as data/time pickers. I feel it would be VERY VERY helpful to develop some type of example class for all different types of select/input meta box types. A key problem relates to how jquery or motools libraries are added without messing up other elements. In my example all I wanted to do is create an event calendar and found it very difficult to create the date/time calendar using motools as the date/time selections (to ensure fields are entered correctly).
—
Regarding your previous comments, would you potentially be willing to assist me on the development of such a media upload meta box if I could contribute some funds towards your developments? Please contact me by email when you have a moment.
Hi dimas.
I’have created a custom post type “A” with a custom meta “A-meta”.
I have a pb:
I want to display the list of all “A-meta” values but not especially in the specific custom” post type A page ” .
Here’s the error :Call to a member function the_meta() on a non-object in on line
It’s works good on ” post type A page ”
is their a way to do it.I’ve tryed with a function but it don’t work here.
I am not quite sure where you are trying to display the meta values?
Depending where you are trying to use the
$custom_metabox
object (or similar) you might have to do:ok thanks!
it’s works with:
Thank you Dimas! It worked brilliantly.
first of all: super cool idea!
but i think i’ve found a bug: try your meta.php and check some checkboxes there, you’ll find that on relaod they are differently checked.
i’ve made a very simple example:
project-meta.php:
let’s say i have 2 clients there, if you check the second and reload the admin-page, the first gets checked, not the second.
if you check both, both stay checked.
Micha, good catch … this gotcha stems from the internal
clean()
function within the class (basically, cleaning and removing empty values).For example out of 3 check boxes if the last two are selected, the array would look like:
array('b','c')
and NOT likearray(NULL,'b','c')
. Because of this, there is not a one-to-one correlation with each of the check boxes in the loop.I will try to come up with some solution…
You can use the following, meanwhile:
#1: I haven’t used custom taxonomies in a while, I played with them and I think I know where you are going with this suggestion. Similar to “links” in WordPress, it would be nice to be able to add an additional meta box to be able to extend its functionality (I don’t know if this is possible or not).
Possible Solution If this is NOT possible for taxonomies, a plugin can definitely be written as a helper to extend the data for taxonomies. It would have its own admin page (one location) where you could add extra data to each taxonomy.
#2: The storage selection in the case is NOT a new storage solution, in fact it still uses the default WordPress storage. By default the class will store a single value as an array, the “extract” mode will do the opposite (natively what WordPress does by default) which is to store each form field value as a single custom field entry.
This becomes useful when using functions like
query_posts()
where you can interact with meta values. So if you are having problems with the speed and indexing of thewp_postmeta
table, the modes this class introduces will not solve your issues.#3: Let me preface this by saying: I’ve seen meta box classes available which allows you to programatically create form fields, these classes work well, but fail when the developer needs to do something more custom. Personally I like to have as much control as possible when it comes to look, feel and functionality, essentially this is the reason that I went with a template based solution (role your own) vs programatic creation.
WordPress provides the
enqueue_script()
function which work well for using third party solutions like jQuery and MooTools. I think what might be needed in this area is guidance, a tutorial to explain how to set some of this stuff up.$clients[$mb->get_the_index()]; ?>
that gives an ugly 500 😉 i now use
get_the_index()]->post_title; ?>
which is sub-optimal too but at least it works for testing purposes …
ok i worked around that, but have found another small bug:
i’m currently fiddling around with multiple-fields in this case phone-numbers.
i copied the have_fields_and_multi() part and do have now:
have_fields_and_multi('phones')): ?>
the_group_open(); ?>
phone get_the_index()+1); ?>
<input type="text" name="the_name(); ?>" value="the_value(); ?>"/>
get_the_index() > 0 ) : ?>
delete
the_group_close(); ?>
new phone
delete all
but after deleteing all phone-numbers the array count doesn’t get reset, i still have for example 4 as the_index.
it’s just a small glitch no big deal.
I was reading about how you can include specific meta boxes based on the category in which the post resides… However, my question is this:
Will the filters run on the meta box(es) as soon as the user clicks the checkbox for a particular category, or only after the user saves the post in that category?
Josh, currently it will update when the user clicks the update button, I will look into it, as having it immediately appear is definitely more intuitive.
Additionally give me your thoughts on the following: 1) I am thinking functionality, it might be that I have to have the meta box already present in the page (but hidden), when the use clicks the category then it gets displayed (not sure I really like this solution) … 2) also what if on click of the category a notice appeared, something like “new functionality present, please update post” …
thanks for your feedback!
Thanks, that’s kinda what I figured… I suppose I could just let the client know that they’ll need to click “Update/Publish” after choosing the appropriate category in order to see what sorts of custom options are available for that particular post.
I’m not sure I like the 1st idea either really… The less markup (visible or hidden), the better. (at least in my book)
As for your second idea, I really like that one. I know me personally, when I write a post in WordPress I don’t normally select the category and/or tags until AFTER I’ve already written the post, added the excerpt, given it a title, etc…
So if other people do the same, then it might be a very useful idea to display an alert letting them know that there are more options now available for them to fill out.
I just took a look at the “Select Category” section in the WordPress write page, and it looks like each of the checkboxes are given unique id’s like so: in-category-X where X = the category ID…
So I’d imagine it wouldn’t be too terribly hard to run a foreach loop and get all available category ID’s, then enqueue a JS file which has onclick events to run the filters.
Josh, thank you for your insights, I tend to operate similar to you, saving categories and tags for the end. I will work on a revision to this before the week is out (or this weekend).
This will also give me an opportunity to conceptualize and develop a way to give the developer access and to change the custom javascript and text messages that will be used within the class (most likely using wordpress’ filter and hooks functionality, possibly generic callback concepts, or maybe have developer extend the class).
I have an idea for a feature, but it might be a bit outside the scope of what you’re doing with the class.
Anyway, I think it’d be awesome if there were a shortcode available that could be inserted into the post editor which would then pull all values from a specific metabox and list them in the post itself.
See, I’m working on a site right now which does a lot of sports stats, and as it stands now I’m having to add the stats into tables for the guys who own the site because they know zilch about HTML.
So I thought it’d be awesome if I could create a “stats” metabox which would allow them to enter the name of the field like say “AVG”, and then the value of that field, like say “.398”.
They could fill the metabox with all sorts of stats, then by adding the shortcode into the post editor, it would then organize them all into a nice clean table.
Probably far outside the scope though.
Hi Dimas — For the past 6 hours i have been attempting to do various customizations to custom post types with the use of your meta box class. Bottom line is that your plugin in huge and I can see it being very useful for me.
I am running into a few issues which I just can’t seem to be able to solve and I hope you might be able to quickly help me out here.
1) One of the post_types I a creating is aimed at creating an event database. Everything here is going well except that I just can’t figure out exactly how to integrate a custom jquery script which allows for the selection of a date instead of having to enter it manually.
The code I am trying to integrate it this one:
http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/
I have attempted various integrations using the wp_enqueue_script element but things are just not showing up for me. Would you mind briefly trying to apply the mentioned jquery plugin to a form field and let me know what code you used in your functions file and meta.php file to enable it?
2) The second problem I was having related to creating a meta box for hobbies. What I was attempting to do is use your example code to essentially create just one meta and upon clicking the button, create a new blank form field. This is all working as expected and it essentially would allow me to have each hobby in its own form field. The problem I ran into was on the initial display as my goal was to provide an initial set of 5 blank form fields and if the editor needed more he would click the “add more” button which just add a single blank form field. How would I go about doing this?
3) Next problem I ran into was when I attempted to call a meta value from an entered form field using your script into the backend admin “post list” display. I am not sure if I am doing this correctly or not but after lots of hacking around I was finally able to get it to display using code like this:
add_action(‘manage_posts_custom_column’, ‘manage_events_columns’, 10, 2);
function manage_events_columns($column_name, $id) {
global $wpdb;
switch ($column_name) {
case ‘event_starts’:
global $custom_metabox_event_details;
$meta = $custom_metabox_event_details->the_meta();
echo $meta[‘event_location_address1’];
break;
case ‘event_types’:
$custom = get_post_custom();
echo get_the_term_list($post->ID, ‘event_types’, ”, ‘, ‘,”);
break;
default: break;
}
}
While the above code does work I am not sure if this is the correct way to call the value. Please let me know.
I was however not able to get a custom field value to show up when I used your class to create a custom field which can be duplicated. Please let me know how this should be done.
4) Here is a strange one which I am sure is a simple solution but I have been beating my head against the wall trying to get my meta.php file to including something as simple as get_post_thumbnail();
What is the correct method of being able to pull in information like this or for that matter any data or plugin which you would regularly be able to include with a public website template?
5) Finally, I have gone through your site and have managed to reposition the wysiwyg editor using your code but what I can’t figure out is how to essentially enable a regular form field dialog box with such a wysiwyg editor. The goal being to be able to use more than one dialog wysiwyg editor box. Please let me know how we can achieve this.
Thank you VERY much for your help in advance.
Eu estou usando assim:
get_template_part( ‘lib/WPAlchemy/MetaBox’, ‘index’ );
porque se tiver em meu template, ele vai carregar, e se tiver no meu tema, ele também irá carregar; nesta ordem.
Hello!
I’m using MAMP to develop and test my wordpress theme but for some reason whenever I add the metaBoxes to the functions.php I’m faced with a blank page when I test the results. It’s fine when I’m using it ‘live’, I just have dramas in MAMP!!!!
Louisa
+1 on #5 . How to add WYSIWYG to meta box, and/or HTML/Visual mode toggle.
Josh, I too think this would be a great feature. Have you had any luck coming up with a workaround?
Chris, I apologize for not getting back to you sooner, I’ve got an answer for #1:
This is how i set everything up:
functions.php
meta.php
custom.js
(custom js file I use to add all my custom js)The above was not working for me at first, the key is to avoid using “$” in the global space, I believe WordPress uses the
jQuery.noConflict()
option.With that said, the above works, but the below will NOT:
#2 consider using
have_fields_and_multi($name)
, in the initial download I have a good working example. There is also a function calledhave_fields_and_one()
(which is depreciated), it always adds an extra field at the end (after each update).I have to go for now, but will follow up with you on your other questions this weekend.
Louisa, make sure you you have error reporting ON in your local environment.
You can make INI adjustments or try using the following inline in your code:
Scott, no I’ve not been able to work up a solution/workaround just yet… I’m still trying to get the project finished, so I haven’t had time to try and find a way to accomplish this…
It was just an idea I had while adding other metaboxes for static info, so I thought I’d post it here to get Dimas’ thoughts on the idea.
I do think it may be outside the scope of the class, but your idea has got me thinking of a debug method for printing out all the values of a metabox.
Hey Dimas… I don’t want to sound like a complete idiot, but it seems i’ve somehow managed to create an infinite loop using your class and the “multi” option.
I’m adding a metabox which will allow the owners to add “Email Groups” to their sidebar. Each “Group” would contain multiple email addresses, which the owner could add by clicking one of the buttons. Each email address is 2 fields: 1 for email, 1 for name of owner…
However, as I said, it’s somehow creating an infinite loop that just killed my server. 🙁 haha
Here’s my code, can you see if you can tell what the heck I did wrong?
Sorry, disregard the code I posted above… That’s after I already removed one of the loops so I could stop the server from dying.
Here’s the invalid code that creates an infinite loop… I know which section creates the infinite loop, I just don’t know why it doesn’t work as I had expected.
Josh, a current unfortunate short coming of the Meta Box class is that it only tracks a single level when using any of the loop functions … so having an inner loop is currently not possible.
However, the Meta Box loop functions basically are used to write proper form field names and get values … these tasks can be done manually using regular PHP loops and functions … you may not be able to use all of the classes helper functions when doing things manually.
You’ve displayed a very good working example of the need for inner loops. I’ve added it to the list. I will try to make it possible to track unlimited amount of loops, but if that becomes too complex I may scale down up to 3 levels.
Ok, I was afraid I had actually done something stupid which caused it.
Do you happen to have any ideas how I could still achieve the same effect manually?
I just want to be able to let them add “Email Groups” by clicking a button, and each of those groups would contain multiple “Email Addresses” which they could add by clicking a button as well…
Think it’s gonna be too complex?
Josh, it will be a little complex, if you decide to move forward, this should help get you started:
Your form field names will need to look similar to this (you’ll have to use your own PHP to generate these names using your own PHP loop):
The Meta Box class will still assist you with it’s built in javascript for duplicating the fields. You will have to setup your HTML as such:
Note: you will need to generate a blank group (hidden) at the end of a group loop, also the .tocopy class needs to be on the last instance of the generated group.
On line #443 in
MetaBox.php
you will have to change:to…
Also, I think you may have some troubles with inner loop duplication, so you will probably have to do some additional modifications to the javascript in the MetaBox.php file line #427 to #457 … i’ll revise the code also when I have some additional time … todo: this code needs to be revised so that when a button is pressed “add” it is context sensitive (delete button) works like this already, “add” should check which group its in, look for the .tocopy class and duplicate it…
This should get you started…
Ping me via email and we can talk further about this…
Wow, that does seem like it’s going to be pretty complex! haha
I think I’ll just hardcode it for now into the theme’s contact page, and then maybe later if you add the functionality to the class, then I may go back and revise it.
Thanks Dimas!!!!
Hi Dimas,
Firstly, great work with the Metabox Class.
I created a metabox textarea thats going with a post and I am trying to run shortcode in but does not seem to be rendering, its just spitting out the raw shortcode tag.
I was wondering if you allowed for shortcode to be processed in the metaboxes and if not, what needs to be added to make it possible for shortcodes to work
Another question I have is how would you include a metabox outside the loop, I am currently doing it like so and want to make sure its fine.
Thanks & Regards
Said
Said, in terms of processing shortcodes, the Meta Box class will not do that for you, you will have to call
do_shortcode($content)
on the content you want processed for shortcodes.In the loop or outside of the loop you can do what you are doing or you can do the following:
Hi Dimas,
your wpalchemy plugin is very useful. Since I started using it, wordpress administration is much easier for the clients. Thanks for that.
Since making custom metabox-es is very useful, I was thinking what else would we need to have a better and easier wordpress administration. In my opinion, it would be nice to have an easy way to create a theme options page. Here we could store some general setting that are not related to each post/page like metaboxes.
What do you think, is this a good candidate for a class/plugin similar to WPAlchemy ? I am a designer so I can’t do this myself, but I wanted to share this idea with you.
Thanks
Hi Dimas — Thank you very much for your response in regards to the date range picker.
I have followed your instructions exactly as mentioned and have tested various different ways and things that might be the issue including disabling other plugins all without luck though…. it just won’t show up. Everything loads fine but when I go to click on the box which should pull up the date picker nothing happens.
I have verified that the page is indeed calling the correct scripts (which are being included) and I have even integrated it without any modification to the point where I just had the one box show up… still nothing tough.
Could you maybe review this once again to ensure there are no difference in your working code?
Also, do you happen to know how I can change the functions.php file code you included above so that it would only load the applicable code on the actual custom post type of events and nowhere else? I think this is important to avoid possible other conflicts with other plugins and just cleaner to ensure extra stuff is not being loaded.
Also, I would greatly appreciate if you might be able to review the other points/questions stated in the above comment and hopefully elaborate a point #2 that you began to address above. Thanks you very much in advance!
Horia, I very much appreciate your comments and hope that you will continue to use WPAlchemy as it grows. Similar to your thoughts, I want WPAlchemy to be a lightweight helper framework on top of WordPress. The key goal being: to help designers/developers setup custom admin UIs with minimal effort. I’ve got two development threads going on right now in regards to WPAlchemy … 1) a plugin creation/helper class to help plugin developers create and standardize plugins … 2) a class to assist custom admin menu creation … once I have these to a good working state I will release a preview release.
#1 try doing it on a fresh wordpress install…
#2 I’ve made a revision to the WPAlchemy MetaBox class which should help you out, grab the latest development release … if you are already using
have_fields_and_multi()
you can simply add a length parameter to it:#3 Your code looks good … if you want to use the class methods you can do the following:
To loop through duplicated fields see the template example above.
Note: the
$meta
is a raw dump of the meta values, to see how things are stored do:print_r($meta);
.#4 try:
see the codex for more info.
Note: when a meta box template is included, it is included inside a function, this means that global variables are not available and you must explicitly use
global $VARIABLE
to use a global variable. As a convenience, the class will auto callglobal $post
making the$post
var available.#5 I haven’t had a need for this yet, however I have tried to play around with it a while back, WordPress has filters for tapping into TinyMCE (you might be able to use those). I would recommend that you try to find a plugin which adds multiple TinyMCE boxes and either use the plugin OR look at the plugin code to see how it is being done.
cool — this “$mb->have_fields_and_multi(‘docs’,5)” works exactly as I was hoping it would which is great.
Now, if there is just some way (when you get a free moment of course) to confirm with me the correct inclusion of that jquery date picker so gets correctly loaded for only a specific custom post type then I think I finally can get this custom metabox done.
BTW – I looked at echo get_the_post_thumbnail($post->ID); and that did work… I did not know it understand the $post query. I hope this now lets me include other data in here correctly to get this metabox in place.
Looking forward to your response!
Dimas,
First off, your WPAlchemy Meta Box class is great! It is by far the best code I’ve come across when dealing with custom meta boxes. With that said, I have a couple questions that I was hoping you could help me out on (I skimmed the comments above, so hopefully you haven’t touched on either of these subjects)
1. I have integrated the “Add” button with the group feature and I was wondering if there was any way to set a limit to the number of instances created. (I want individuals to add a max of 3 additional instances)
2. I am using the UI Datepicker function in my admin and it works for the initial instance, but once I press the Add button the Datepicker neglects to pop up. The class must not be carrying down to the next instance for that is what initiates the Datepicker function. (Note: if i add a second instance and “Update” it, the Datepicker will work)
Thanks so much and any guidance is greatly appreciated!
Tyler
Tyler, I like your idea for #1 very much, I will definitely implement this.
As for #2, this is what I think is happening: the first element gets initiated with the date picker, but because the next element is dynamically duplicated it does not get initiated. This is currently a shortcoming which I will also address in the next release. What you can do meanwhile is edit, the javascript portion of the code and when the element gets cloned, you can initialize the cloned date picker at that time.
Tyler, about your #2 problem, if I understood correctly, the Datepicker is not showing for the elements added dynamically because they are added after the .bind() or .click() call.
If that is the case you could try to use the .live() jquery function to set the click events.
$(‘.clickme’).live(‘click’, function() {
// Live handler called.
});
Hope it helps.
Dimas,
Thanks for the quick response. I have one more inquiry that I’m sure you could help me out with. When I use the group function with the “Add” button is it possible to grab a particular value out of that grouped array. If this were possible it seems like you’d do something like $meta[‘docs’][0][‘title’], but this doesn’t work. Once again thanks a lot!
Tyler
Hi
I keep getting this error message:
Fatal error: Call to a member function the_meta() on a non-object in /nfs/c01/h06/mnt/13626……
Whilst using this code in my template:
the_meta();
echo $meta['name'];
echo $meta['age'];
?>
Here is the page: http://frozengrape.co.uk/184/test/
Could any tell me what is wrong with my template code?
Many thanks
Ben
Horia,
Thanks for the reply. I tried implementing your technique and it didn’t seem to work. I appreciate the help though!
Tyler
Ben, see the Using The Meta Box Values In Your Template section of the documentation. You basically want to do something like this:
Depending on where you are using
$custom_metabox
, you may need to useglobal
.Hi Dimas — First of all… I got almost everything working over here based on your suggestions so thank you very much!
I did run into two additional issues though which I am having difficultly with both still relate to this event calendar.
A) on the public website templates what I am trying to do here is essentially run a wordpress query on this event post type and now I want to sort these posts by a specific meta value. What I seem t have noticed is that I can’t just use the standard meta key which was assigned to the custom field I created for “event_start_date”. As such… how are we supposed to define that applicable meta key field within the post query string?
Here is what I am using:
query_posts(‘post_type=events&meta_key=event_start_date&orderby=meta_value&posts_per_page=-1&order=ASC’);
B) I finally did end up getting the jquery meta box to show up (it was actually a stupid problem on my end)… what I however seem to be unable to achieve is making this custom event post type allow for more than one event to be inserted.
More specifically, I created three custom fields:
* event_start_date
* event_start_time
* event_end_time
I have “event_start_date” associated with the jquery datepicker which is working fine.
Now I want to create a “add new” button to essentially how the editor to enter all the applicable dates and the from-to times a specific event will be taking place.
As mentioned in a different post by someone this is creating problems. Would you mind reviewing this please and possibly providing the correct code so that such groups can be duplicated?
C) Assuming the above would not work… the very inconvenient way the editor would have to go about things would be to create a new post for every single event individually. While I guess this would be better than nothing (as mentioned above) what I am really trying to achieve here is allowing that editor to create one “event” and then just add the applicable dates and times that event will take place.
The problem with this situation is that I don’t have any clue based on your code on how I would run a query_posts command which NOT ONLY spits out every single event post but essentially “for each” event post it would need to extract/print all the applicable event dates/times and then sort all of the results by one of the meta key values.
Something tell me that you have already though about this and have this built in but I am confused on how to actually do this… Can you provide some help here?
D) I believe I did find an issue with the recent code modification you made related to: $mb->have_fields_and_multi(‘docs’,5)
What I noticed is that if (as mentioned above) you set a value of 5 lines to print, then fill out each of these 5, then go ahead and click the “add” meta box and enter a 6 entry, then save… when the page refreshes and/or when you access it again later there will only be 5 entries and the 6th one can’t be seen or modified.
As usual, I think you in advance for your assistance!
Chris, for A take a look at this and see if it resolves your issues. Additionally for D I have a development release which solves this issue.
Hi Dimas — Boy, I have having some troubles just getting these posts to display and order themselfs corrctly.
I look at the code suggestion which it seems its not working as I am always getting a blank page.
I have included the code I have used for all elements below. Please do take a look to see if you notice anything I might be doing wrong.
First of all – from you last comments here is what I have done to query the posts based off the meta .
Here is the full code I am using for the public website template were I am listing all of the events and attempting to have them sorted by date:
Here is the code I am using for the “event_dates” metabox
And here is the code I am using for the “event_details” metabox on the same page.
I should point out that everything seems to be working perfectly when entering new events (one events per post) but I can’t seem to use the query_posts function to get those posts on the public site.
The other problem I just can’t seem to resolve is when I try to add more than one event start date/start time and end time to an individual post and then have the public site show a list of posts where all entries are shown for all posts and then sorted by the start date.
I believe I have totally confused myself here… ahhhh
I’m struggling with creating a conditional statement to check whether or not a custom write panel has been filled, and then providing that value or not depending. Thanks in advance!
Could you please show me a quick way how I could have a meta box automatically populate a list of existing “term” taxonomies. I am attempting to essentially utilize your code to create my own drop down list so that an editor can only select a single taxonomy term from such a drop down list? Thanks!!
@Ross, when you say write panel are you talking about a simple textarea? If so you can probably use some js to detect text entry… post a little bit of relevant code so I can help further.
@Binarybit, I think what you are looking for is the get_terms() function, I think this will return an array of terms which you then can create a dropdown from.
Hi Dimas,
I return with another question.
I am trying to use have_fields_and_multi in two places in the same metabox. It is not working right now because if I click add on the second “have_fields_and_multi” it will add to the first collection.
Any idea how to make it work in multiple instances ? I mean, this is not two nested have_fields_and_multi, so I think it’s only a JS problem.
Am I right ?
I will look into it, but let me know if you have any idea how to do this.
Horia, be sure to give your second add button the proper class name:
First: thanks for the powerful tool 🙂
I tried to find a way to use the class with
query_posts(” metakey=’my_meta’&meta_value=’my_value’ “) but i can’t find the right way to access the value as it is kindof serialized in db.
regards,
John.
John, take a look at: WPAlchemy MetaBox: Data Storage Modes, there is an example on how to use
query_posts()
Dimas, that is perfect, I don’t know how I missed that.
Thank you !
@Dimas: This is EXACTLY what i was looking for! Sorry for not digging more into your blog! This is brilliant 😉
Hi Dimas,
First of all thanks for sharing this class, it is very useful.
I want to report a little issue found when using have_fields_and_multi: it doesn’t work properly when the name given has dashes (-). I fixed it changing in line 431 \w for [a-zA-Z0-9_-].
Hope you want to add it in your next release.
Thanks!
Suso, thx for the tip. I’ve updated the current development version and the next tagged release will include this fix.
Dimas,
WPAlchemy seems to conflict with WordPress 3’s featured image meta box. Do you know the reasoning for this?
Thanks,
Tyler
Dimas,
Just getting started with your code and I’m loving it, but then I’ve only just renamed meta.php and included it unmodified with my custom post type.
I agree with others that knowing how to do WYSIWYG and Media Library stuff is critical to having usable systems. It also doesn’t make sense to include it in your class, so since I need both, I’ll try to document it once I’m done and comment with the URL of the post…. If I remember.
But that’s not why I’m calling.
I discovered a (minor) bug in your code. I think its your JavaScript and I think its relatively easy to fix.
Load a new page with you meta.php metabox and go and remove all the documents.
Now first of all, this is meaningless since we don’t have any documents, so some checking in the JavaScript to see if it even makes sense to enable the button seems like a good idea.
In the dialog box that shows when you try to remove all, if you choose cancel, a new row appears. Unexpected to say the least. Not sure if this happens always, but certainly when you have no documents it happened for me (FF, OSX). Haven’t dug into it more, sorry.
@Tyler, can you explain what conflicting symptoms you are having with WP3 featured image meta box and WPAlchemy MetaBox? I will try to reproduce if I can?
@Adam, thx for the tip, I removed the auto “add” after a remove all so that things are a bit consistent … clicking “remove all” or clicking the last “remove item” button only leaves the “add item” button, however updating the page will cause a blank new item to reappear (I think this is expectable).
Dimas,
I figured it out. Of course the problem was on my end. Thanks for your time though.
Tyler
Hi,
thank you for that great piece of code & the detailed information.
I’d like to put a metabox right below the title (it will be the subtitle of the post).
It’s just the last piece to make it perfect for me. I didn’t find out how to use the $context property (i guess it has to be “advanced”) that way…
thanks a lot & keep the good work going on
Basti
from Munich
Hey Dimas, I found a MASSIVE error: in this post, for the “Using Include Options” example, you use an exclude option 🙂
Suso, thx for the tip, I’ve update the page!
Hi Dimas,
I just finished a development where I used your class, it was great, thanks again for sharing it.
I have a feature suggestion for the next release: adding taxonomy/term to the filters, besides post category and post tag. For my project I did a quick and dirty fix where I added a include_taxonomy option, and replaced wp_get_post_tags for wp_get_post_terms. I’m sure you can easily add the include/exclude taxonomy feature, and I think is a great addition to your class.
Thanks!
Also I found a problem. It doesn’t work making the query to the post with the meta fields in the header.php or footer.php, nor if is a template from get_template_part(). If I replace that code there inside a page it works. I guess is a problem with how you get the current post…
forgot to mention, what doesn’t work is the get_the_value() function.
Suso, there are situations which you may need to use
global $custom_metabox
to get proper access to the object …I may add a helper function such as
wpalchemy_get_instance('name')
to help in these types of situations. There are parts of WordPress that run locally outside of the global scope, I am assumingget_template_part()
is one of those situations.Yes! that fixed it, thanks for your help!
Simply amazing plugin!
I really hate to ask what feels like a stupid question… but when i try to use the sample template meta.php …. my meta box only shows the first text input and label. then it cuts off and doesn’t show any of the rest.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Cras orci lorem, bibendum in pharetra ac, luctus ut mauris.
Name
actually now i see the member_function() on a non-object error that was mentioned in the comments.
the line that is causing the choking:
<input type="text" name="the_name('name'); ?>" value="the_value('name'); ?>"/>
however, Scott’s statement that his error was coming from referencing $metabox outside the loop doesn’t help me solve it. the meta template isn’t in the loop at all is it? I did try to add global $metabox to the meta.php but that didn’t help.
perhaps it is just midnight and i am in a cake coma, but hopefully someone knows what’s up.
on another note i know you mentioned leaving the meta.php templates in our hands, but i had something a while back where the fields were defined in the $metabox array and it referenced a switch function by input type. then all i had to do was add this to the new metabox declaration array. i thought that was significantly easier and save repetitive coding (esp if you have multiple metaboxes), but maybe that is b/c I just can’t get this method to work yet.
'fields' => array(
array(
'name' => 'Headline',
'desc' => 'Enter the heading you\'d like to appear before the video',
'id' => $prefix . 'heading1',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Textarea',
'desc' => 'Enter big text here',
'id' => $prefix . 'textarea',
'type' => 'textarea',
'std' => 'Default value 2'
) */
)
you can take a look if you want:
http://pastebin.com/91cQKKyq
thanks for sharing so much of your work!
So it was definitely the cake coma… for anyone else running into the member_function() on a non-object error problem check 2 things: first, that you are requiring the MetaBox.php file in the same place you are defining the $custom_metabox. for some reason you need this w/ classes. second, double check that you are using file paths for $custom_metabox’s template.
Now, to crank up some metaboxes. Thank you Dimas!
Hey Dimas,
I’ve run into a snag when trying to sort posts using the custom field data created by your class… I was wondering if you might be able to shed a little light on the subject?
I’ve created a question on the new WP stack exchange site here: http://wordpress.stackexchange.com/questions/1014/sorting-wordpress-posts-via-custom-field-values
It seems that for some reason, the query isn’t recognizing _events_meta[event_date] as a valid custom field key, but as you’ll see in the screenshot in that question, it’s stored in the database exactly like that.
Any ideas?
Hi Dimas – its Chris…
I was hoping that you could please review the comment post I made here on “August 9, 2010 at 8:37 pm” above… I don’t mean to sound impatient or ungrateful for all your help up to this point for me and other but I could really use your expert advice and I am stuck here… Thanks in advance!
This kicks ass..
You should throw up a donation box. I’d throw some cash your way.
Chris, I really apologize for not getting back to you. Can you email me your meta box template file, and your meta box definition (functions.php) so I can take a look?
Hey Dimas,
This is very helpful. Thanks!
I have one question you might be able to help me on. I would like to have a few checkboxes for the client to click which would display an icon (or a handful of icons – representing services they offer) on each post. Any help would be much appreciated.
Mike, take a look at the example code above for the meta box content (use the show/hide links), see line 106-108 for an example of setting up radio buttons, should be the same for check boxes. Remember to have the “value” parameter set to what ever identifier you need as a reference (for you icons, it could even be the filename or something).
Thanks Dimas, I was able to get everything working correctly except for the checkboxes which are always checked even after unselected and published. When I refresh they are all checked again. Here is my meta.php. Thanks in advance for any help.
Thank you for your wonderful metabox class! I’ve been able to pull off some rather nifty things thanks to WPAlchemy MetaBox.
However, now I’ve run into a problem that seems impossible to solve (for me, that is), and I wonder if you might take pity on my pain. 🙂
I have a custom post type called “performers”, where the posts are bios of various stage performers – where I’ve used WPAlchemy MetaBox for the performers’ contact info etc. Everything works perfect here.
Now, I’ve also made a custom post type called “showprogram”, and here I’m trying to make a meta box (“Appearing this week”) that have a dropdown select box with the names of all the performers from the “performers” post type – as well as an “add artist” button that can duplicate the select box.
But I’m quite stuck. I’ve managed to populate the select box with the performers’ names, but nothing gets saved. I think my whole approach is wrong, but can’t think of another way.
Any thoughts or wise sage advise?
Hey Dimas,
I know you’re probably getting tired of me poking around and asking question after question… but I’ve got yet another one for you! lol
I’m trying to use your class to include a group of checkboxes (much like Mike above) and I’ve figured out how to take the data from WPAlchemy (which is already stored as an array) and add another array within it…
Like so:
However, when trying to tell if the checkbox should be checked or not, that’s when I run into a problem…
I tried using the example you gave for radio buttons with “is_value()”, but since the “value” is also an array of values, I’ve not yet been able to figure out how to check each value[value] to see if a checkbox should be checked or not…
Any ideas?
Ok, so with a little more digging I’ve found that the $mb object is being stored as so:
So this means that the “services” item is being stored as an array within the original array… So why am I not able to access it’s data no matter what configuration of $mb->is_value() I use?
@Mike, @Tom, @Josh,
I’ve just released v1.3 with lots of new/cool goodies. When you download the latest release, take a look in the
custom
folder and view the SELECT, CHECKBOX, and RADIO examples … these should help sort out any issues you are having.I will be updating this page with the latest documentation in the next day or so, but you can take a sneak peak by reviewing the documentation in the code!
You sir, are a Godsend! hahaha
I was actually JUST hacking together something that worked… but booooy was it nasty and messy! lol
I’m glad you’re listening to our issues and actually taking action. There are so many developers on the web who release things and never work to implement their users’ ideas… They could stand to learn a thing or two from you.
Thanks!
Sweet!
Got it working by using:
@Josh, slight alteration … just so you are aware of how you can use
the_field()
…Great, thanks for the tip!
Ok, I don’t know if I’ve stumbled onto the first bug with your latest release or not… but something strange is happening.
Normally, when accessing the custom data in the theme, there’s no issue at all (with earlier versions)… However, now it seems that when I try to use something like
$userdata_metabox->get_the_value('phone')
it’s actually just repeating one value over and over and over all throughout the loop of posts.I’ve checked, double checked, and triple-checked to try to make sure I haven’t done anything to screw it up, but I can’t find anything erroneous on my end.
Here’s an example bit of code:
The above bit of code returns the following:
Notice that the phone number, user ID, and email address stay the same no matter which post is referenced in the loop. The “name” given is actually each post title, and you can tell by the name and the post ID, that the loop is running correctly.
It’s just not pulling the correct post meta from the wp alchemy class for some reason. I’ve also double checked the database to ensure the data is stored correctly, and it is. Each post has it’s own unique set of “user data” stored under _userdata_meta
Strange…
Josh, I’ve made a fix … v1.3.2
w00t! Thanks dude… I know you’re probably getting tired of my incessant nagging by now, eh? hahaha
Ok, so I know I’m a loser with no life… but I’ve run into something else that’s a bit curious…
I have a group setup, and it all works well as it should. However, if I run an if() statement on have_fields() to check to see if it does in fact have any information stored, then the while() loop only shows a couple of the available informations…
Example:
That shows the first 2 “testimonials stored in that group… but there’s actually 3… If I remove the if() statement though, then it displays all 3 as it should…
I just need to be able to check for the existence first so that I don’t show the heading that says “Testimonials” if there’s none filled out for that particular user.
Any ideas?
Josh, I don’t consider your feedback as nagging, in fact you are giving me valuable intel on real world usage of WPAlchemy, I very much appreciate it.
I want to revamp the have_fields… section of WPAlchemy, it can definitely be more robust and powerful. For now try:
Hmm… I tried using
$location_mb->have_value()
and that gave me: “Fatal error: Call to a member function have_value() on a non-object”However, oddly enough… After changing it back to what it was previously… The testimonials display now… All of them. ???????
The code now is exactly the same as it was before the error… Why did it start working? hahahahaha
Hi Guys,
Great tutorial, but having a small problem. I am trying to do something a little more advanced (in my eyes) than this tutorial covers. I am hoping someone can help me.
I am using the data from a custom metabox in a random loop. However as the metabox isn’t always filled in it outputs an empty container.
What I would like to do is to only display meta box info where data exists and just ignore posts where the meta is empty.
Anyone have any ideas that could help me? It would be greatly appreciated.
Hmm I don’t seem to be able to paste my code without it stripping bits out even using the code tag. How did others do it?
Gavin, if you are using the query_posts() function, then the following will be useful to know (storage modes).
Additionally you can use the
have_value()
to check for values before you output.Tip: Using
<pre>
is best, and replacing all instances of<
with<
helps. I still need to figure out my comment/code issue…Josh, i think I copied and pasted one of my meta box examples, hence if you used
$location_mb
it gave you the error…It would seem to me that it would make a lot of sense to be able to use your class in styling meta boxes for custom taxonomies.
Case in point: I’m in the middle of developing a real-estate theme and in the past I would have just created a number of custom fields to hold the data and your class would be perfect.
But now that WordPress is moving forward with the addition of custom taxonomies it makes a lot of sense to move things that were previously custom fields to be taxonomies. There are a number of native functions and options available to taxonomies that are not to custom fields.
So that said I would love to see your class be able to incorporate custom taxonomies – not just pull in the data from get_terms but actually save it out to the proper table.
I ran across this tutorial which will allow you to do this but it doesn’t have the elegance or ease of your meta box class.
http://shibashake.com/wordpress-theme/wordpress-custom-taxonomy-input-panels
Thanks.
Dimas,
Is there anyway to make a text field’s onChange function work while enclosed in the group tags for multi fields? My onChange function seems to work great when not treated as a group, but i want to be able to “Add” fields. Thanks a lot for your help!
Is there a (correct) way to create a textarea with the WordPress WYSIWYG Editor? I was using the secondary_content HTML plugin (http://www.cmurrayconsulting.com/software/wordpress-secondary-html-content/) which is excellent, and by-default loads the WYSIWYG editor.
But just now I discovered WP Alchamey, and I’m immediately converted. Wow – what a weapon to add to anybody’s WordPress toolbox! Very impressive and professional Dimas.
So I was wondering if someone can advise on the mce editor addition.
Josh B, I like the idea, but I think it goes a little beyond the scope of the class, however, there is a feature which you can take advantage of. The class now supports certain filters and actions, you could use a
save_filter
to get the meta data during a save and preprocess it, allowing you to make data changes and also use default wordpress functions to save selected taxonomy terms.You’ll want to grab the latest branch dev release
Tim, I’d have to see your onchange code to understand how it might be conflicting (consider using gist.github to post your code) …
Cracks, I haven’t totally dived into the WYSIWYG subject aside from the following article I posted, the discussion there is also very useful, be sure to read it!
Josh B, here is a more specific example:
In your meta box content template, you would list your taxonomy terms … you would then use a save_action to get the selected terms and adjust the post’s taxonomy on save. Setup would look like:
Awesome. This would be huge to get this working.
So, here is what I have for my custom meta box.
This code is getting the terms for the custom taxonomy just fine. And your class saves my selection but it does not translate to the actual taxonomy. I suspect I’m missing something from the save action.
What (if anything) do I need to add to the save action? I’ve replaced the ‘category’ placeholder with ‘property-location’
Thanks.
One thing I forgot to add is that the first time I saved from the custom select box it removed what was selected in the actual taxonomy box.
And now even if I check off something in the actual taxonomy box it does not get saved. (but what is selected in the custom select box gets saved)
Josh B, when testing with
wp_set_post_terms
, be sure to use the term ID vs a slug or name, I found that only the ID works.I’m using the term ID now and the regular taxonomy saves as expected but there is no change to the custom meta select box.
I can’t get the code to post correctly for my custom meta box so here is a link:
http://snipplr.com/view/40439/select-box-for-wp-alchemytaxonomy/
This is my custom save function:
Josh B, here is some code for your select box (note the soon-to-be documented function
the_select_state()
):You will probably have to change your action function:
array(3)
should list the term IDs, and you need to make sure you specify the taxonomy to which to save to. Your function call mighty look like this:If you haven’t already, visit the documentation for
wp_set_post_terms()
…Hi Dimas – I noticed something today while diagnosing a wordpress issue…. It seems that your metabox-function file is including a BUNCH of javascript code into the head and footer of every page of the admin side. I noticed this when viewing the source of various admin pages which were not the post-edit edit page. The files I am referring to related to the copy/delete actions above the and there is also a bunch of code being loads into the footer div which is duplicated for every metabox created in the system.
Would there be a way to modify your functions file so the code is only included on the post-edit screen. I used the following code below to only include a specific css file the admin page being loaded was the post.php, post-new.php or edit.php pages. I believe for the code in question it only needs to be loaded on the post.php and post-new.php page as your class does not effect any other admin pages.
Here is the code I am using which might be of help:
Chris, thanks for the heads up, should be a simple fix, this will be updated in the dev branch and in the next 1.3.4 release
Just thought of something which I don’t think your class took into account. While I personally don’t need this ability but I am assuming other as well as myself might in the near future.
So, in your class, when you create/define a new metabox through the functions.php file and want this metabox to become available on two separate post types you one would use:
types’ => array(‘news’,’articles’)
So, far so good – but lets say you define some specific additional variables such as the priority, lock, view, or other variables… Now, let’s assume that I only want these additional settings set for one of those two post types like “news” and for the other post type (articles) I want to set different variables. Can this easily be done? If not, maybe it would make sense to be able to override these “variable display settings” on a per post type basis. Also, now that I am writing this maybe the same type of override should exist for your include/exclude options so individual settings could be coded/defined depending on the needs of the developer. Just a thought…
Good thought, I will ponder this some more … but my initial thinking is that you can define a second meta box object, with specific settings for it and use the same meta box template file.
Hey Dimas,
Thanks for the help – unfortunately I have not been able to get it work.
Short of asking someone to do it for me, I don’t think I will figure it out at this point – my coding skills are being stretched to new heights 🙂
If I do figure it out I’ll be sure to post back here so others can know as well – just didn’t want to leave the issue hanging.
Your class fails when used in child theme as TEMPLATEPATH points to the parent theme. Use of STYLESHEETPATH may solve the problem.
Anyway it’s a wonderful work that you have done. Thanks
Thanks for the tip, I’ll confirm that I am not using TEMPLATEPATH within the class itself, any paths outside of it are up to the developer to set.
That would be great… Thanks again for your wonderful contribution.
Can custom taxonomy be filtered using similar technique… I mean show a custom taxonomy only for certain category?
@Josh – Hey Josh… I was working with Dimas on this issue as I needed a solution as well and wanted to share with you how this can be accomplished which works like this:
Utilizing his WPAlchemey Class I added a save_action var into the area of my functions.php file where I am defining the metabox – This code looks like this: (NOTE: I am using the taxonomy “category” which of course you can change to whatever your custom taxonomy might be):
I then add the following function for this save action like this:
An my metabox code which displays the dropdown list of taxonomies looks like this:
Hope this help you and others!
I just noticed a potential problem with this code which I have not been able to resolve. The code I have pasted above seem to only work when the taxonomy is setup with ‘hierarchical’ => true. If you set this value to false then for some reason it creates a new term based on the term ID of the one you selected. Does anyone happen to know what the save_action function need to be changed to if the hierarchical?
Has anyone figured out a way to resolve this?
Hi Dimas,
I’ve got an error, why I can’t call the method ?
Fatal error : Call to a member function the_name().
This class is proving completely invaluable in a charity website project I’m working on – thank you for all your work on it, Dimas.
I have a question about the have_fields_and_one feature. I love the principle of it, and I’m using it to enable my client to add any number of links to be displayed on certain pages of their site. However, as I’m wrapping the output in a series of tags, the unfortunate effect of the and_one is a final empty , which is showing up styled like a normal list item, but (obviously) empty. Is there any way around this?
This is the code I’m using in my template to output the links:
Thank you!
…and, hmm, my code didn’t output right there at all, but hopefully you’ll get the idea – I have link tags wrapped around each link that’s output by the metabox using have_fields_and_one.
@Matt, you issue typically can be solved by using
global $custom_metabox;
, this is the variable used when defining the metabox.@Faye, the
have_fields_and_one()
function is depreciated, you should really be usinghave_fields_and_multi()
… additionally, these functions should only be used inside your meta box content template and not in your theme template … in your theme template you should use:also see: Using The Meta Box Values In Your Template
I might have missed this above, but do you know how one would set a radio button to be checked by default? It doesn’t look like this is an option that is built into your class. Thanks so much for sharing this code!
Sorry if this has been answered already. In my template there’s seems to be a problem when I run other custom loops with get_posts before executing my meta box values. Even if I declare global $my_metabox; somehow a conflict exists and my meta values won’t output.
Ross, make sure you have the latest version 1.3.5 (there was a recent fix which was related to
the_meta()
) … when inside a loopthe_meta()
will pull the last global$post
var, you can be explicit and use$my_mb->the_meta($post_id)
if needed …Downloaded lastest version. But not sure I explained my issue properly. Maybe I’m simply using the class wrong. Trying to write a conditional like so:
get_the_value(‘link’)) { ?>
// do something
I’m also running get_posts loops on the page and they don’t let the above function execute. No errors, just no output.
Version 1.3.5 broke the metaboxes. Old posts, already saved, shows – but on new posts, the metaboxes are nowhere to be seen.
After reverting to version 1.3.4, everything is fine again.
Dimas, could you look into the taxonomy problem listed above… Strange situation happening there which requires the tax to be hierarchical for it to work.
@Tom, 1.3.6 fixes your issue, thanks for the heads up!
@Chris, I’ll investigate sometime this weekend or so…
@Ross, email me your code and I’ll take a look.
Dimas, this is an excellent WP resource. Thank you.
I would like to create a metabox that relates a post to other posts. The website is for a bicycle racing series. The metabox would appear in a post about a particular race. I want to be able to use a multiple select field to assign sponsors to that race. Each sponsor is an entry in a custom post type.
Thus, inspired by the discussion on here regarding using a select field to assign taxonomy terms, I was able to successfully create a multiple select field in a metabox that queries the “sponsor” custom post type.
But when I make selections and click “update” in the post editor, I get a white screen full of code. I’m presuming that the problem is that the selections aren’t properly saving. I’m a newbie to some of these coding techniques, so I’m wondering if I need to create a “save_action” like you did in the taxonomy example? I tried the following custom save_action:
This reduced the amount of code that appears after trying to unsuccessfully update the post to this:
I’m sure there is something simple that makes what I’m trying to do possible, but I’m not aware of it in my ignorance. Hopefully, this clearly presents the spirit of what I’m trying to accomplish and you may quickly point me in the right direction. I appreciate your help. Perhaps there are others that want to do something like this and this comment will help them too.
Nice lib!!! i like it really!
Do you have a discussion group?
Hi Dimas,
I was wondering if there was a way to include/exclude meta boxes based on post types? For instance, if I want a metabox to appear on every page? I know this is part of the wp code, but I don’t see it in your docs for include/exclude.
Cheers,
-kathy
Kathy, see the
types
option which you can use to limit the meta box by post type: “post”, “page” or a custom post type … additionally if you need to do something more custom you can use theoutput_filter
option to decide when to display a meta box, like such:awesome! i feel like a moron for missing that. thank you dimas for a super, complete php class.
Hi Dimas – I have conducted various tests and my records are showing that your class is creating multiple PHP errors related to a specific line on the MetaBox.php file. My logs shows multiple entries for the following:
PHP Warning: Invalid argument supplied for foreach()
More specifically, each entries is referencing line 1973 of your MetaBox.php file (which I renamed and relocated btw).
When reviewing line number 1973 within your code it related to this:
foreach ($new_data as $k => $v)
Note – I am using the newest dev version 1.3.8 in case that helps. What can we do to resolve this or what might this be related to?
Chris, I’ve updated the dev branch to 1.3.10 give that a try if you will. Thanks for the heads up. fyi: I’ll look into your taxonomy issue this weekend (I haven’t forgotten).
Hi Dimas,
Thanks for this great plugin!
I just run into one thing I can’t figure out. I want to use a checkbox to let the user indicate if they need a “print friendly” option for the page (so check to add the “print this page” link). I use the WP-Print plugin for this. In my template I would like to add the code to get the checked/unchecked value for the link and if checked display the link.
This is what I came up with in my template file:
the_meta();
if ($meta['print']) echo do_shortcode('[print_link]');
?>
I used your example for the no-follow checkbox to make the metabox, that works fine. But how to make the link appear? Also if I put some word instead of the do_shortcode thing, nothing appears. What am I doing wrong?
If you have any idea, that would be greatly appreciated!
Thanks,
Maggie
Sorry to have troubled you, have figured it out already by using the
and a tweak in the wp-print plugin. Turns out it doesn’t work out-of-the-box when using custom post types.
Thanks!
Maggie
Really lost and struggling here…
I have 2 custom post types (ABC and DEF).
ABC was set up with $custom_metabox and DEF setup with $custom_metabox2.
The admins work perfectly, add/edit/save all quite lovely!
On the front, I am using custom page templates to show a table of posts, and then a click to show details.
for ABC, this worked great, got the values I need into the table by field.
for DEF ( $custom_metabox2), it’s not working – the issue is, for content that is not required (say an optional field) if post 1 has the value, but post 2 does NOT (empty), it’s pulling the value from post 1 until a new post has a new value.
In the loop, I can see the post ID is changing (did an echo).
It’s like the loop is holding on to a value, so empty fields are returning the value.
BTW, I tried to use the lastest MetaBox from git, and that broke my ABC working version. So I went back to the ver I have (a few months old, I can’t tell how to figure out version).
Really lost, and client is breathing on my neck.
Please help!
Every time I update the page a new blank field set is created below the existent ones. Shouldn’t that only happen if there are no fields at all? After a few edits to a post you end up with a box littered with empty fields.
That is, using `have_fields_and_multi`.
It seems like .wpa_group.tocopy is sticking around on publish, so it comes in on the next page load. I’m removing it on clicking #publish as a fix.
@Mike, are you using
$mb->the_meta()
before you start getting/using values? You can also set the post ID to use via$mb->the_meta([id])
, test this with your current version as well as the latest version.@Ricardo, I have noticed this issue before, but as far as I am aware it has been resolved make sure you are using the latest version from github.
Part solved:
For the working table page, that ‘broke’ with latest release, it worked again when I put:
global $custom_metabox;
$custom_metabox->the_meta(get_the_ID());
in the loop.
I tried this for the totally non working version, and I still got repeated values when a field was optional.
My workaround was to go with this:
get_post_meta(get_the_ID(),$custom_metabox2->get_the_name(‘fleet-golfbags’)
which would show empty if a field had no value for that record, or the new value when the field changed.
What it seems is that the loop is not clearing out the values in the meta-box custom object. Going oldschool, to the metal (so to speak) bypasses the custom object and gets the value (or non-value) directly.
Is there something I am not doing right? Or perhaps, just perhaps, the custom meta object needs a cleanout on each loop?
Mike, I will try to reproduce the problem so i can figure it all out … If you are interested, the part that gets/clears the values is the
_meta()
internal function in the class … there are some special conditions going on here which I am trying to take into account so if you do play around with it you may want to test your solution again.The easiest solution I think would be to comment out line #1345 (the if statement which returns an old version of the meta data).
I’ll get it sorted out, thanks again for your comments.
Dimas,
I can’t figure this out for the life of me and haven’t seen anyone else run into this yet.
I have a custom loop inside of my metabox display file so that I can link a “article” post to another custom post by using a dropdown. The problem I’ve run into is that when I go to edit an “article” or create a new one, it seems as though the query from the metabox is running and taking over because the new or one I’m trying to edit displays data from metabox loop.
As soon as I take out that custom loop everything works just fine again. Is there some reason this custom query would be carried over onto another screen?
There’s nothing strange about the query and I’ve confirmed that if I take out the while loop everything starts working fine again.
Justin, the Loop can be tricky sometimes, just like wordpress depends on certain globals so does the WPAlchemy_MetaBox object. Try the following an see if this works for you:
1) Instead of using
$wp_query
(this is a global variable that is used in WordPress) try creating your custom Loop with a different variable name,$my_query
for instance.2) When
$my_query->the_post();
gets called it will create/overwrite the global$post
variable, this will confuse certain calls to the$metabox
object, you should store the values that you need to use in a variable before you begin your custom Loop. So for instance, before your while loop you would do the following:and then in your custom loop you would do:
3) After the your loop you will need to return things to normal, meaning you will need to set the global
$post
variable to what it was before you started your loop, I believe you can do this with a call tothe_post();
immediately following the close of your while loop.Give those things a try and let me know if they work or not.
Got it working by just storing the global $post variable in a temp variable and then restoring it after the loop. Thanks for the help.
Would it be possible to use this class to for Theme Developers to create a theme options page? It may be out of the scope of the class.
It would be great if under the Appearance Menu, a “Theme Options” menu item would show. It would be there that the custom metaboxes would be available. This may be a different class in and of it self but, essentially, seems to have the same functionality.
It may be possible to incorporate an “options” type for the WPAlchemy_MetaBox array (e.g. page, post, event).
Currently I have theme options, located under the Appearance menu. Everything works great. However, it would be supra awesome if there was a class like this one to easily be able to add options and pull theme into the theme.
Luke, the main goal of WPAlchemy is to provide a thin framework for WordPress developers:
1) for those who work with wordpress to create client websites and must customize the UI
2) for theme and plugin developers to use as a library in their projects to ease and at the same time standardize development.
WPAlchemy is be no means close to that goal yet, the MetaBox class is just one class in a few which will provide simplified setups.
I am currently working on another class, part of WPAlchemy called AdminMenu which will simplify the creation and use cases of admin menus.
Dimas,
I’m hoping you can help me as I am at a loss. I’ve got the script setup and working very nicely. I am using an example from your full_meta.php where you have the adding and removing documents example.
I can add, remove all, and or remove single “groups”, in my it’s case links. The problem I am having is each time I Update the page or post, it’s adding another instance. Before updated screenshot and After update screenshot.
When I use your “docs” group code, I don’t have any problems. I must be missing something small. Here is what I have so far.
Ofcourse, after I spend hours and finally submit my plea for help, I figure it out!
Turns out the group was duplicating because of the select box not having an empty option first in the list
. I initially took it out so the link would always have a value upon being saved. It didn’t matter what the value was, it would duplicate unless there was an empty option first in the list.
I can’t wait for your AdminMenu script! By the way, you need a donate link for all of the script goodness.
I have one feature idea and two issues regarding the
while ( $custom_metabox->have_fields_and_multi('links')
loop.First, the
while ( $custom_metabox->have_fields_and_multi('links')
loop:I have a “Hello World” post with two “links” groups. One link is to Google and one to Yahoo (screenshot). Using the
while ( $custom_metabox->have_fields_and_multi('links')
loop i get the results, however, two odd things are happening.1) I get both the Google and Yahoo results PLUS an empty result at the end (screenshot).
2) The meta data of one post is showing up on each subsequent posts, that do/do not have any custom_metabox values assigned to them. Example: Hello World (with meta data assigned) and Another Post (w/o meta data assigned). You can see the values of “Hello World” post are being carried over (the Google and Yahoo info). Here are each posts setup screenshots – Hello World and Another Post.
Here is an example of my post loop.
Feature Idea: As great as this script is, I think it would be an added value if drag n drop was included in the
have_fields_and_multi
functionality. It would be nice to arrange the order of the groups. As it stands, you can create and remove groups, and display them in that order. It would be even more dynamic if the possibility was there to arrange those items. Say I have a list of 6 groups, and for some reason, needed the 6th one to be first. I would have to remove all groups, then add the info back in the order I would like. Nothing big as the script is a lifesaver in and of itself, this would just be double bonus for me.Luke, I’ll investigate #1, for number #2 try using
$custom_metabox->the_meta()
immediately afterthe_post()
. This is kinda of an issue, there are some internal implications which forces the developer to have to usethe_meta()
, I am trying to do away with the use ofthe_meta()
and have the class automatically figure it out.I do like your idea of drag and drop, I have also ran into ordering situations in my own production work, so this is a feature I am considering (will either be drag and drop or simple field to provide order number).
Thanks, Dimas!
For #2, your suggest worked however, it appears that #1 gets worse by adding an additional (now 2) empty results on posts without an values assigned (screenshot 1). This is what the source code is showing:
For what it’s worth, say I call the
$custom_metabox->have_fields_and_multi('links');
anytime before thewhile($custom_metabox->have_fields_and_multi('links'))
loop, one of the empty results goes away (screenshot 2). And for whatever reason I call it again (a third time, now), another goes away (screenshot 3).If it helps to replicate what I have, here is my custom metabox code.
By the way, a ordering groups by number would be just as awesome as drag n’ drop.
Which version of the class are you using? also try changing the following line to
$arr = NULL;
, see if that makes any difference.I was using version 1.3.7, just downloaded yesterday or the day before from here. I’ve updated to 1.3.11 and made the change as suggest. No difference either way.
Luke, just made a dev update, try getting the latest dev release v1.3.12, this should clear up the loop issue you are having.
I’ll explain it a bit: The have_fields_and_… functions act like iterators, but they behave differently in different contexts, such as in the meta box content template and in a theme template.
In the meta box content template the
have_fields_and_multi()
will output an extra value which is hidden and gets used in the repeating field functionality.In the theme template, this behavior is undesirable, in v1.3.12, the loop will not output an extra value.
Dimas, it works beautifully! I’m especially grateful.
Dimas, I was curious if you had a way to Save/update the post via a button. I noticed the save_action and save_filter callbacks. Basically, I am looking for a way to insert the default blue “Update” or “Publish” button to do just that. Some plugins I use, use this functionality. Sometimes, it’s nice to not have to scroll back to the top to save/update. Is this built in?
Luke, try something like:
Excellent! Thanks.
Dimas, I’m back with another (similar) issue with the
have_fields_and_multi()
this time in the admin section.Similar to the issue before of an unwanted extra NULL value being added to the page, this time it is being added to the metabox. However, this extra value does not show up, which seems like everything is working fine. This may be why the extra value was showing up on the page before as well?
I found this because I was using the
is_last()
call to check and see if the group was the last group. If it was, I was going to have it show a button to add another group. When it wasn’t working, I looked at the source code and found the extra group (which then echoed my is_last test).I thought I would share as it may shine some light onto the other issue, although you did fix it.
Luke, are you using
the_group_open()
andthe_group_close()?
Dimas, I am using
the_group_open()
andthe_group_close()
. Here is a link to my code snippet.Dimas – how about starting a forum? This comments list is getting looooooong. And then we can all help each other. 🙂
Hey Dimas – have you looked into using the built in wordpress export tools and then reimporting the file into a fresh wordpress install (same version) with the theme preactivated? I am not sure why but it seems things did not get associated correctly after the import because everything imported correctly except for any data created by your metabox….
Please also do look into those two issue I mentioned to you by email as I still have not been able to resolve it.
Hi Dimas, what a great plugin you’ve coded! b^^d
I have a question, is there a way to save value of a meta when ‘context’ is set to ‘side’?
Hi, sorry. I just used the same field name as metabox id so I can’t save them. Now it’s different, and can be saved.
Unlimited Thanks! 🙂
+1 for Ross’s idea. I would definitely be willing to help out.
Hi Dimas!
Thanks heaps for your class! It’s brilliant and great pleasure to use!
I found a minor bug though:
Say we have a metabox in WPALCHEMY_MODE_ARRAY mode with a textfield. Now, we:
1) insert some value to the textfield and save
2) delete the value so the textfield is empty and save
3) insert some value again and save
After that the new value WOULDN’T BE SAVED!
here are the critical lines in the code (lines 2018 – 2028 in version 1.3.11):
and here is the solution:
Actually if i think about it, using empty() is not the perfect solution either (see php docs of empty()), because we need to consider as empty only:
1) null
2) “” (empty string)
3) empty array
so that 0 and “0” are not considered as empty… so the best would probably be to write our own function my_empty() and use it.
Lukas, good catch … the current dev release on github addresses this issue, see v1.3.13 … I will push it to the master branch sometime today.
Lines 1960-1963 addresses the issue.
Thanks for the code, I always do appreciate when someone takes the time to investigate the code on their own and make suggestions/fixes.
Great, thanks for the new version!
As I said, it’s pleasure working with your code.
Hey Dimas,
I think I found another little bug:
When you use multiple fields, it’s in the javascript function for adding new ones – starts on line 1288 in version 1.3.13. The problem is that if you use code like this:
And you start adding new fields, the javascript wouldn’t increase the index in the ‘id’ and ‘for’ attributes – only in ‘name’ ones, which results in improper behaviour of labels when you click on them to gain focus on the textfields they’re attached to. moreover it causes duplicate ids.
Here’s a quick fix, I’ve done – don’t have enough big picture to fix this issue properly but at least it gives you an idea what i mean. And so far it works properly – even when you use elements without ids.
Excellent work here; I’ll just be throwing out the meta_box functions in all the themes I modify and using yours from here on out.
Could you help me troubleshoot something? I’m pretty much following your example exactly for an endlessly repeating field, but the “Add” button isn’t actually replicating the field.
Here is how I create the meta_box instance:
$sidebar_images_metabox = new WPAlchemy_MetaBox(array
(
'id' => '_sidebar_images_meta',
'title' => 'Sidebar Images',
'template' => TEMPLATEPATH . '/custom/sidebar_images_meta.php',
'types' => array('page'),
'exclude_template' => 'index.php',
'priority' => 'high'
));
Here is my template:
Again, just can’t get the field to replicate when clicking “Add Another Image.” Any ideas?
Hi Dimas,
First of all thanks so much for this Class! It’s helped massively so far.
However I am having an issue. I’m trying to output some meta box content and a wrapper div only if the meta box content exists, this is what I’m having but it’s throwing back a fatal error:
Any tips on what I’m doing wrong? I’ve read previous comments above and some of your other articles but I’m not having any luck.
hmm that didn’t work, let me try again:
I had to remove all the opening php tags.
@J Fishwick – I’ve been using this same thing recently with great luck. I’ve tested your code and I got it to work (screenshot). I am using version 1.3.12 of the class, what version are you using? I would suggest down loading the current version.
Also, I noticed you had an extra closing
/div
tag above yourthe_group_close(); ?>
call. That may be causing some troubles too.@Ryan – try using a
while
statement instead of anif
Thanks for the suggestion Luke, though I’m still getting an error:
Fatal error: Call to a member function have_fields() on a non-object in /Users/………/wp-content/themes/sbb/page.php on line 22
Line 22 is:
while($secondaryContentmb->have_fields('description')) :
@Luke
Haha, of course it was just bad markup on my part… Thanks! FYI, your thread here has been invaluable, thanks for the good questions, code samples et al.
Dimas,
I’m applying the helper class to a custom post type, it seems to be storing the data appropriately (it’s there when I look at the database), but when I return to a custom post that has data saved on it, it doesn’t appear on the form and if I re-enter data, the old data is overwritten.
I’m using while($mb->have_fields_and_multi(‘songs’)): to create the n-number-of-fields meta template…
Am I missing something?
…as a followup:
I’m still having issues, but I *have* discovered that $mb->current_post_id seems to be 8, though the post in question is 9.
I’m not 100% that this is not-as-designed, but it seemed odd to me and seems like it might cause the behavior I’m seeing.
Thoughts?
…. (Part III)
Ok, I’ve found a solution. It seems that a separate query for some other custom fields was interfering with the $post’s context, thereby making the metabox use the wrong post for its data. I solved it by tossing the following code into the class (right at the top of the _meta function):
function _meta($post_id = NULL, $internal = FALSE)
{
if ( ! is_numeric($post_id))
{
if ($internal AND $this->current_post_id)
{
$post_id = $this->current_post_id;
}
else
{
global $post;
$p_post_id = isset($_POST['post_ID']) ? $_POST['post_ID'] : '' ;
$g_post_id = isset($_GET['post']) ? $_GET['post'] : '' ;
$post_id = $g_post_id ? $g_post_id : $p_post_id ;
$post = get_post($post_id);
$post_id = $post->ID;
}
}
// this allows multiple internal calls to _meta() without having to fetch data everytime
Basically, it goes back to the get/post data to determine what the source post is… this may not cover 100% of the use cases, so I’m not suggesting that this solution become part of the codebase, but it solved my particular issue.
Firstly, thanks Dimas. This is very cool 🙂
I am having a small issue which I hope can be easily rectified (I’m pretty new to this so my php knowledge is somewhat lacking!).
I’m using
have_fields_and_multi('))
for links and link text but when I loop through it in my theme it never displays the first link/linktext entered. Here is my metabox code:Remove All
Add links to external sites
Important - you must add the full url (example: http://www.yourdomain.com)
have_fields_and_multi('links')): ?>
the_group_open(); ?>
the_field('title'); ?>
Link Text:<input type="text" name="the_name(); ?>" value="the_value(); ?>"/>
the_field('url'); ?>
Link URL:<input type="text" name="the_name(); ?>" value="the_value(); ?>"/>
Remove Release
the_group_close(); ?>
Add Another Release
and here is the code in my template file:
have_fields('links')) : ?>
Artist Links
have_fields('links')) : ?>
<a href=the_value('url'); ?> >the_value('title'); ?>
Your helps much appreciated!
@Bryan, can you use gist to post some of your code so that I may review, specifically your meta box content template and your meta box definition.
@Luke, thank you for your assistance!
@Bryan, I didn’t see your latest comment. I’ve had similar problems with this section, I’ll review your code and see where I can improve this overall section in the codebase. I hope you got what you need squared away.
@Wesley, can you post you code using gist, then simply post the gist urls here … makes it easier for me to review the code in its entirety (sometimes wordpress will garble comment code).
Dimas,
I just sent a pull request on github so you could have some context on what I did to fix the issue.
Dimas
Yeah sorry about that, it does look out of whack. Here is the post again as suggested:
I am having a small issue which I hope can be easily rectified (I’m pretty new to this so my php knowledge is somewhat lacking!).
I’m using ‘have_fields_and_multi(‘))’ for links and link text but when I loop through it in my theme it never displays the first link/linktext entered. Here is my code:
https://gist.github.com/664345
Thanks in advance
Thanks for creating this man! This is such a lifesafer…
@Bryan, thanks for the pull request, I’ll add and make some adjustments, I’ll have to write some unit tests to test different situations/contexts.
@Wesley, I’ve made an update to your code with some comments, see what you get … https://gist.github.com/664539
Dimas
I’ve tried the code but you suggested but it still doesn’t work. When I uncomment the print_r line it outputs ‘Array’ to the page. Other than that it is still acting the same.
Any further ideas?
Wesley,
Change your if statement to
if($cm_links->get_the_value(('links'))
.This will check if there is a value (
get_the_value()
), if so, then the while loop will run, if not, it will pass.Hi Luke
Thanks for the suggestion.
That seems to crash the page and I just get a blank window. All the data entered in the admin is saved into the database, i’ve checked. It just seems the loop ignores the first set of data entered into the links meta box. The second link url/link text entered prints out as you’d expect. It’s weird!
Wesley, Luke, and Dimas,
Is it possible that Wesley is seeing the same thing that I was? It’s the same symptom at least. One of the first things that led me to my solution was that I did a print_r of $mb and saw that it was actually pulling the meta data from the wrong post.
Wesley, do you have any other custom functions on the page that may be hijacking the current post context?
Hi Dimas, any update about the javascript issue I wrote about in my last post, please?
@Wesley
Here is the code snippet I used to test which works perfect.
Here is a screenshot of it working on the first post, that has two links added (link 1, link 2) via WPAlechemy MetaBox
have_fields_and_multi()
. Artist title shows and both custom links are accounted for.Here is a screenshot of the next post in line that does not have links added. As you can see, the Artist Links title does not show nor do any custom links.
I’ve been using the
have_fields_and_multi()
religiously in the latest theme I’m building. I did come across this situation before with the same result you had running the if statement with a while loop on thehave_fields_and_multi()
. It will produce the same result if you were to call$cm_links->the_meta()
twice as well on the same page. I’m not sure why, just trial and error stuff I’ve concluded.Sorry, used same link for second screenshot. Here it is without links showing.
Bryan, I am having a hard time recreating the circumstances in which you were having issues. I am doing the following:
functions.php … https://gist.github.com/665620
repeating_fields_meta.php … https://gist.github.com/665621
I have created an “event” post type and added a few field groups and I am able to save/remove the data just fine.
Dimas,
The trick is that there was a non-metabox set of custom fields directly above the metabox that was querying ANOTHER custom post type and thus changing the context of the ‘current post.’
Does that make sense?
@Bryan, I think so … Justin Myers had a similar issue above … would you characterize your issue as similar?
@Lukas, I’ve updated the issue with the javascript updating “id” and the “for” attributes, see version 1.3.15 (dev branch), you can review the changes here. Give that a try and let me know if that works for you.
Dimas, that looks like the exact same problem. Seems like I missed it in searching the comment list.
The taxonomies of wordpress will be more and more important.
I missed an easy way to show and use these in the current code. Especially the checklist (hierachial) lists.
Please find below an easy to use piece of code to display an taxonomy (with selected options) as an checklist:
'probleem');
$taxonomy = array_pop(get_taxonomies( $args, 'objects'));
?>
labels->name; ?><!--(optional)-->
name, 'orderby=name&hide_empty=0');
$post_terms = wp_get_post_terms( $mb->current_post_id, $taxonomy->name);
$mb->the_field($taxonomy->name);
?>
<li class="popular-category" id="name;?>">
<input type="checkbox" name="the_name(); ?>" value="term_id; ?>"term_id, $post_terms); ?>>
name; ?>
<!--<select name="the_name(); ?>">
<option value="term_id; ?>"the_select_state($term->term_id); ?>
' . $term->name; ?>
-->
Selecteer alle labels->name; ?>
You would only have to adjust the first line of PHP code to get another taxonomy.
Now I am trying to find an way to add an new taxonomy on the fly. Question: Is there an hook which I can use to custom save an added field?
Thanks in advance for your sweet plugin– hope you can focus on Taxonomies a little bit ;).
The above post has been mangled a little bit. My apologies– maybe the host can adjust it a little bit.
As an addition I would like to rephrase my next question: Is there an good solution to add an new taxonomy on the fly with the Metabox class?
Looking forward to implementing that final piece of the puzzle.
Any tips for using a meta box value to sort a query?
I’m trying to use
orderby=meta_value
ororderby=meta_value_num
in conjunction with an “Order” custom meta box. It is simply:Not having much luck though.
@rZr, try using the
save_filter
so that you can modify the$meta
data before it gets saved into wp_postmeta, see my previous comments on the subject.Do me a favor and repost your code above using https://gist.github.com/ … save your code and post the link, ill merge all your comments into one, thx.
@J Fishwick, depends on how you are trying to use it … if you are trying to use meta data with the
query_posts()
function, see this post for more details on the matter.@luke
That’s fantastic, your code worked a treat.
Thanks so much,
Wesley
And here is the code again: https://gist.github.com/666732
Somehow the $mb tag was giving problems as an global so I passed it to the function (lame but it works for now) ;).
Usage: checkbox_taxonomy(‘taxonomy’, $mb);
Just type you taxonomy in the string field and the code will build an checkbox layout for you. The add button functionality is still not working. Saving it for later x).
Hi Dimas, thanks a lot for the fix. It doesn’t work properly yet though. I don’t know javascript very well so i’m not sure i understand well what’s going on there but it seems like the code works only when the found elements have all the attributes (id, name, for) specified. if that’s not the case, it creates error that
the_match
isnull
.So i added a check on undefined for the_match as well (v 1.3.15, from line 1301):
and it works perfectly!
Sorry, something went wrong with the previous code?
https://gist.github.com/667683
I feel like I am pushing here. But I would love to hear your expectation of implementing Taxonomies ;). Even though the current code is sufficient for my needs now, it would be good for future users and myself to have it supported out of the box by the Metabox class.
Hello,
I’m still stuck on this fatal error problem. Basically what I want to do is only show metabox content if it contains data, if the user has left the metabox blank then don’t show anything on the live page:
https://gist.github.com/667689
Nevermind, I’ve used:
if(!empty($secondaryContentmb['title'])) { ?>
Thanks for the amazing class!
I have been thinking about it. And I would like to help implement the Taxonomies in your plugin (first basic functionality) if you wish.
The experience and enthosiasm is here and so is the time ;). Would it be possible for you to contact me on my hotmail?
I would love to show you my current backend of my custom posts with your plugin and custom metaboxes to explain where I am going.
I have managed to create the custom metabox which I wanted. Its fully functional and would like to share the screengrab of the Admin panel with you:
http://imgur.com/agvNI.jpg
@all: Let me know if you have any interest in the code or functionality.
@dimas: Now the proof of concept has been finished this particular piece of code can be introduced in your plugin fairly easy. If you would like me to send you the access to the admin panel or something else, please let me know.
rZr, contact me via email and we can talk further about integrating your code.
My line of thought will probably lean towards a separate class “WPAlchemy_Taxonomies” which not only can integrate with WPAlchemy_MetaBox (modular), but can also aid users in easier taxonomy creation/manipulation in general.
I do not want to make functionality too specialized, I favor hooks/filters over built in functionality, this allows the end developer to use the toolkit how they like.
I can only agree with your points. Looking forward on working together on tackling Taxonomies in an easy to customize plugin.
Note that I have tried all taxonomy managers out there so far. And I can tell that having the control by code is much more preferred. So I would like to focus on the metabox as of now.
@rZr I like the screenshot with the columns of custom taxonomies and check boxes. I’m really interested in this for my project.
Are you for hire?
I’ve been using the class to great success on a demo version of a site. Today I am launching the site, and I migrated my WordPress site to the new domain. I ran some SQL statements to update URLS for images and such, as well as installing a database manager plug-in for the client.
I then noticed that none of the meta data for my WPAlchemy boxes was in any of my posts or pages. What’s worse is that no new data I enter is saved. Everything was working perfectly before the migration. Anyone have any clues to why this is happening?!
@J Fishwick, I am aware of the issue, but need to investigate and test further. I should have a fix/solution in the next day or so.
It has something to do with storing meta data in” wp_postmeta” as an array and during export/import it get double serialized.
Did you do a straight DB copy or did you go through the import/export options in wordpress?
So, I had the site I’m working on in a subdomain, and now I’ve moved it to the root of the domain. I just moved the files, and I’m actually using the same database. What I’ve done since then is:
1) Import a couple blog entries via import/export
2) Ran these SQL statements:
UPDATE wp_options SET option_value = replace(option_value, ‘http://subdomain.domain.com’, ‘http://www.domain.com’) WHERE option_name = ‘home’ OR option_name = ‘siteurl’;
UPDATE wp_posts SET guid = replace(guid, ‘http://subdomain.domain.com’,’http://www.domain.com’);
UPDATE wp_posts SET post_content = replace(post_content, ‘http://subdomain.domain.com’, ‘http://www.domain.com’);
3) Installed the WP-DBManager plugin.
Is there a way I can confirm or deny your hypothesis?
BTW Dimas, I’m fine with nuking the old data, I just need a way to be able to save again.
@J, grab the latest dev release (v1.3.16).
If you are using the default “wordpress-importer” plugin (which most people are) I’ve made some changes to ensure that the data does not get double serialized on import, should also take care of your saving problem (which is related).
Please do the import again and let me know if it works in your case.
Thanks Dimas.
I was able to properly serialize my the table holding my post metadata and all is well.
Hi Dimas, thanks for all your hard work on this code, it’s really made my recent batch of wordpress projects really sing.
I’m doing something a little more knotty with it now though and having some trouble trying to handle query_posts. I have a meta box with a have_fields_and_multi. I want to filter query_posts by one of the multi-field values and I can’t work out how to do it.
So a post may have multiple dates assigned to it and I want to be able filter the query against a particular date. So let’s say that the field within the multi in question is called event_date and on the current post it has 3 date entries, others might have 1 and some may have 6-8.
event_date:
0 -> 1290470400,
1 -> 1292198400,
2 -> 1292371200
I want to be able to run a query to check if posts appear on a single date. Is there a way to do it? Cheers for your assistance.
@Benj, glad you are having success with wpalchemy. Your predicament is an interesting one, but i think i might have a solution.
Even WPALCHEMY_MODE_EXTRACT will not work in this situation because the repeating fields use an array to store the values (the values are stored as a serialized array).
What I think you will have to do is use the “save_action” callback functionality and read in the values that were saved and store extra values in a compatible way with
query_posts()
.I think the trick will be to loop over your values and save them out again using
add_post_meta()
with the “unique” parameter set toFALSE
(using a new meta name). See the documentation on this function.You could then use the new meta name in your
query_posts()
function which should be compatible, and the other benefit is that, in your “save_action” you can also account for changing values (i.e. deleting all new meta name values before adding the current values).Most of the above is abstract, let me know if you have any questions.
Dimas, once again, thank you for the wonderful work you have done and for the support you have generously given.
I was able to get the taxonomy issue worked out with the post from NetConstructor and it is functioning like a champ.
I have one issue that has come up that I was hoping you could help with.
I have a need for users to import posts from a csv file. I’m using the CSV Importer plugin. When the csv data is imported the custom field data is imported and is displayed in custom fields UI, but the meta boxes I created using your class are not populated with the custom field data.
When I create a post manually and input the data in the custom meta box fields it also populates the default custom fields ui.
Is this possible for the import to also populate the custom meta fields?
@Josh B, which importer plugin are you using? (WordPress Easy CSV Importer by Ryan Bayne)
How can I recreate the issue? Is it just a matter of setting up a meta box, adding a few values, exporting to CSV and then importing it in?
I’ve just tackled an import/export issue with the default XML importer so I wouldn’t mind having a look, but I need to be able to recreate.
Thanks Dimas,
Understood completely, your a genius. Got it working this morning and it works a treat. Now I can do queries based on groups of entries like event dates, etc.
For anyone else that wants to search by a group (array) of meta data this is how I did it, based on your advice:
So to make query safe arrays from metabox groups:
1. Add the following line to your custom meta box and make a nice name for your custom save function:
‘save_filter’ => ‘my_save_filter_func’
e.g. :
2. Make a function to duplicate your existing meta box data into a query safe version:
Note: If you have additional data (in
$meta
) that needs to be saved by wpalchemy, yourmy_save_filter_func()
should end withreturn $meta;
.3. Have fun making queries that target a specific meta value:
Dimas,
I used the WordPress CSV Importer.
http://wordpress.org/extend/plugins/csv-importer/
To replicate, yes I would set up normal fields and then try and import data into them via custom fields.
I’m using 6 meta boxes in my custom post type but the code below is my typical set-up.
@Benj, great example, thanks for sharing it. I’ve modified your comment to add a note about using
return $meta;
after the sample code on #2.Let me explain. There are two callbacks “save_filter” and “save_action”.
The “save_filter” is executed before data is saved, it acts like a pass-through, data goes in and data must come out. Filters, as you probably already know, are used to manipulate data. Returning nothing would cause nothing to be saved (via wpalchemy). This may be your intent as it is useful to be able to do this. But, if you have additional values in your meta box that need to be saved, then
return $meta;
would need to be used.The “save_action” on the other hand is executed after the data is saved and acts more like an event notification.
@Josh B, I’ll take a look at the csv importer and see what I can come up with.
I just wanted to show you guys that I finished my file uploader which uses the WP lightbox media library and retrieves the file from it.
screenshot
Dimas,
I seem to be having trouble actually fetching the data from the database and display in both the backend and frontend. It was actually working for me, but I have tried to migrate over to a new server and suddenly the data is not being displayed. Any idea why this is? Do you think there are certain server-related settings I have to set in order for it to work?
The function is initializing because the meta boxes are being displayed in the backend. But once it actually tries to fetch the data it is giving an invalid argument supplied error.
Help please? 🙂
Figures that I would manage to solve this after 5 minutes of posting the comment haha! It was actually a really silly mistake on my part when declaring the ID in funcations.php file. Strange that my own server was not complaining and it worked fine even with the mistake!!
Thanks heaps for this, I love using this custom class 🙂
Howdy. First off, I love this thing. Very impressive indeed. I’ve got it working great on single pages but when I try to display some data in a custom loop on a non-single page, I have no luck. I’m using query_post in coordination with some info from your Storage Modes post.
query_posts( array( 'post_type' => 'client_horses', 'order' => 'asc', 'post__in' => $horse_var, 'meta_key' => $client_horse_news_metabox->get_the_name('client-horse-news') ) );
I get nothing when using this, which works on the single page:
$client_horse_news_metabox->the_value('news-date');
I’ve also tried various other approaches including:
echo get_post_meta(get_the_ID(),$client_horse_news_metabox->get_the_value('news-date'),TRUE);
This last approach spits out the word “Array” and when I var_dump that array, it has all of the correct data so it’s there but it’s not wanting to show itself for me using anything I’ve tried.
Any thoughts? Thanks
Actually, I’ve made a bit of progress (like the poster above, 5 minutes after I posted!) I toyed with the prefix setting a bit and it started working.
I now get the values within the loop using:
while($client_horse_news_metabox->have_fields('client-horse-news')) { ?>
the_value('_my_news-date'); ?> - the_value('_my_news-info'); ?>
The issue now is that the WP loop is only grabbing the meta data from the first post in the loop. So if there’s 4 posts (not meta entries), it displays the custom meta from the first post 4 times. The WP loop correctly grabs the 4 different post titles but not the correct custom meta data. Is there a reset function that I missed perhaps?
Thanks
Dimas,
Any possibility of an include/exclude option for post parent IDs?
-Ross
Hi Dimas, have you tested this with any of the WordPress 3.1 beta builds? I just installed 3.1 to get a look at the custom post type archives feature and now none of my previously functioning boxes will save their data. Also- I wanted to echo what another poster said, you should put up a tip jar.
Sorry, everyone, I’ve been a little busy lately …
@shag, I will look into your issue shortly.
@Ross, good to hear from you again, I think this would be a good addition, I’ll add it and post a release shortly.
@Kathy, I will look into this right away to prevent any breakage.
Can someone share the code that must be added to allow image uploading with this script?
@Kathy, did you do a export/import? If so grab the latest dev release as this issue has been resolved. I will release a production release soon.
If not, let me know the process you when through when testing/upgrading to 3.1 so that I can recreate.
My initial tests with 3.1-beta1-16732 are working just fine.
@hank:
I have finished my file uploader just recently, which incorporates the WP media uploader. Check out the screenshot somewhere in this thread.
We hope to have an tutorial on this blog shortly.
No import/export. Right now I couldn’t tell you what happened and it didn’t seem consistently broken- 3.1 locally worked, but 3.1 live didn’t? It was really random and the type of useless “it doesn’t work” message that I hate getting from my family when stuff goes wrong. 🙂 I’ve been totally swamped lately, but was going to eventually try to isolate the problem. Glad to hear it is working for you and I will upgrade to the newest version and let you know.
sidenote- is there a way to add your metaboxes to a category page? Not a post in a specific category, but rather the category info/description page? like this:
http://www.strangework.com/2010/07/01/how-to-save-taxonomy-meta-data-as-an-options-array-in-wordpress/
@rzr – I can’t wait to see the uploader! Sounds awesome.
I read some of the comments on saving safe query data and I thought I’d post how I did it in regular mode.
here is a screenshot of what I made:
http://www.flickr.com/photos/29025521@N02/5249101836/
and here is all 3 parts of the code, the metabox definition, the html, and the modification to the query
http://pastebin.com/3fq42bjg
I’d love to move this to a more graphical/intuitive setup, as right now it works but I think only established WP users/developers would feel comfortable with manually entering the query params.
Kathy, WPAlchemy_Taxonomy will provide similar functionality to WPAlchemy_Metabox (but, its not finished yet), there is an initial setup on github with basic usage example at the bottom of the file. I would like it to have all the similar features as the metabox class.
sounds like it will be great Dimas! I look forward to using it.
@rZr
I can’t wait to see file uploader! It must be cool!
Wondering if any progress had been made on limiting the number of adds for group elements. I am using your class to build out a backend where a client can upload logos – to work in the template, I’d like to limit that to 5.
Basically the same question that “Tyler” asked on August 3, 2010 at 2:53 pm…
Thank you for your help and for this fantastic class.
Hank, I will see what I can do about integrating it into the class so that it’s an easy setup. I’ll give it a go tonight.
@Dimas – that would be fantastic…thank you!
I am trying to change the values in the columns for my custom post type. The code i am using is below, I keep getting the following error message Fatal error: Call to a member function the_meta() on a non-object in – anyone know how to solve this?
This is all being called from my functions.php file i am including MetaBox.php at the beginning of it.
Thanks in advance for your help.
i ended up solving my own “issue” – hope this helps someone else out.
@Dimas any progress on limiting the number of new fields you can add?
Hank, sorry for the delay, you can grab the latest on the dev branch (v1.4). To setup your limiting you would do something like the following:
The latest version has extra javascript to auto hide/show the add button based on the limit.
You can also add the ‘length’ array key which is used to show a set limit of initial fields. For instance, you want to show 3 fields to start, but want to limit it at 6.
@Dimas – thank you for this – heading over to git so i can start implementing this now.
@Dimas – the new ‘length’ parameter seems to work just fine – but the limit parameter doesn’t ever seem to shut the ‘add more’ button off…
I made an update to the dev branch v1.4.1, if you were testing in IE, a
console.log()
might have been tripping it up.I’ll have to add documentation for this feature, but remember:
“length” sets how many fields you want visible (initially displayed)
“limit” sets when the “add” button should be hidden
@Hank, if you want you can post your code and I can take a look. Use https://gist.github.com/ or other …
Is it possible to pull all data from the metaboxes from every post/page?
For example let’s say you had metabox data on every post but you wanted to pull all the data from every metabox from every post and display it on the homepage, is that possible?
I know you can pull all the custom-field data with something like this;
post->ID;
echo get_post_meta($postid, 'customField', true);
?>
But i’m not sure how you would do it with the custom metaboxes?
Thanks.
Matt, in a similar fashion to the code you are using above, you would do the same to get all the data. Instead you would use the “id” value you defined for the meta box. For the examples above you would use:
To get all the posts, you will have to do a query and get the posts that you want, see The Loop documentation for more information.
Remember,
$meta
will be an array of values.Thanks.
So to get the values I would do something like this?
global $custom_metabox, $post;
$myQuery = new WP_Query('category_name=featuerd');
while ($myQuery->have_posts())
{
$myQuery->the_post();
$meta = get_post_meta($post->ID, '_custom_meta', true);
// print "
\n";
}
while ($custom_metabox->have_fields_and_multi('docs')):
// echo out values.
endwhile;
or am I way off track here?
WPAlchemy has been very helpful and I appreciate all the work you’ve put into it! I’ve used it successfully so far to add some select menus for custom taxonomies.
My last stop is a checkbox list for a custom taxonomy, allowing multiple selections. I’ve followed the thread above and I’ve gotten close. At one point, I broke off and tried to apply the WP Taxonomy class referenced above, in development on Github. While my PHP ability is increasing fast, it’s not quite there yet :).
The problem I’ve run into is saving. The closest I got was a list of custom taxonomies, iterating out with checkboxes (this was before I attempted the WP Taxonomy class). When I would check two or more, only one would save.
Any updates on best practice or a reference to a working example? Any ideas or suggestions are appreciated. Thank you!
For reference, here’s the code I’m using to call the box and then the code I’m using to display the template:
https://gist.github.com/752300
It displays the list of “presenters” and, when you check multiple and update, it makes the update, but for only one.
@Jonathan, take a look at the checkbox_meta.php file, it comes with the download and may help you get started with using checkboxes.
@Matt, your pretty much there, does the
print_r
return you any values?Yeah, got it working.
Thanks Dimas.
One other thing actually. How would I go about making the $custom_metabox type array accept some variables from a function?
For example;
Thanks
One quick question. I didn’t see this feature anywhere so I may be blind, but is there a way to have a default value with a field?
This way if the field is not already populated it will show up with a default value for the user. I added some code to the class to do this and basically I envisioned it as:
$metabox->the_value('var', 'defaultValue');
Does this already exist in WPAlchemy and if not are you planning on adding it?
Justin, thats a good idea.
The
the_value()
can be used in both the context of defining the meta box content and in the page template. Defining a default value in both places would be awkward.Ideally it would be best to define it once somewhere, and if there is no value present, return the default that was set. I’ll see about including something like this in the next releases.
Hi
Thanks for this class, it’s awesome. I do have a question though, I tried creating a new metabox in a function that gets called on a admin_init hook but that won’t work.
It only works when put directly in the functions.php file and I’ve been reading that’s not best practice.
Does anyone know what im doing wrong here?
Thanks
Roy, you are not doing anything wrong, when using WPAlchemy, the class will wrap its own methods/functions with WordPress hooks/actions. I will see if i can modify so as to accommodate different development styles.
Hi all,
I am following your conversation for a while now after installing gorgeous WPAlchemy. Thanks, Dimas, for all your work and sharing! I helped my a lot on my current work and I got really inspired of how I could use it in further projects.
@rzr: Do you have news about your image/file uploader? This seems interesting..
Cheers
Hi Dimas,
First thank you so much for the fantastic code! I feel *so close* to getting it working but I’m not there yet. 🙂
I’m running this on localhost, if that makes a difference, running WP 3.1 RC2, and I’m getting this error when trying to load my edit-page page to see the meta boxes:
Fatal error: Call to undefined function add_action() in C:\xampp\htdocs\texaspbs\wp\wp-content\themes\texaspbs-toolbox\WPAlchemy\MetaBox.php on line 16
Fatal error: Class 'WPAlchemy_MetaBox' not found in C:\xampp\htdocs\texaspbs\wp\wp-content\themes\texaspbs-toolbox\functions.php on line 260
My meta.php is copied directly from your example code above. Here is what I have in my Functions.php:
Any ideas on what I’m doing wrong? Thanks so much for your help!!
Michelle
Hi Michelle, at first glance looks like a include/path issue …
get_template_directory_uri()
returns a URL such as:http://wpalchemy.dev/dev/wp-content/themes/twentyten_custom
When including the CSS this is fine, since you need a web path (relative or absolute). However when including the class file you need a file system path (relative or absolute), something like:
C:/path/to/the/class/file/WPAlchemy/MetaBox.php
Hooray! Thank you Dimas! That was indeed it. I needed to update the paths for both the class and the template. Here’s the updated, functional code – hope it helps someone:
In case it helps anyone, here’s how to add an ‘image upload’ metabox to this script. I found and modified the code from this page (and others – it was yesterday so I can’t remember them all but if you helped, thank you!): http://www.webmaster-source.com/2010/01/08/using-the-wordpress-uploader-in-your-plugin-or-theme/
I’m having trouble getting the code to display correctly in these comments so I’ve put it all in pastebin.
Copy this into a new file called img-upload.js and save it in your theme’s /custom/ folder:
http://pastebin.com/iS4KpAPW
Add this to your functions.php: http://pastebin.com/H3sN3RfS
Add this to your template file (meta.php or whatever you’re using):
http://pastebin.com/QrUE4grc
And to display the image, use this in your theme template files:
http://pastebin.com/heELkcez
Hope this helps someone!
Michelle
@rZr
Can you share your media upload code extension. That would be great. Thank you.
@Leland, and others: thanks for the cry outs, I really want to share it asap. I have expanded on its functionality and it will blow you away.
Now to find some time to write the tutorial on the WPAlchemy blog. I will try to free some time this weekend because I am swamped. 🙁
Also wrote an WP 3.1 extension for choosing post IDs by using the WP core. Sweet stuff!
@rzr
Any chance you could pastbin or email your code with basic instructions so I could at least give it a try and provide feedback? I am getting ready to release a new theme that would greatly benefit from this feature. I am relatively savvy with this stuff just not with media upload. Thank you.
@leland: I have just made an small simple example archive for Dimas (author of WPAlchemy) for review. After feedback I will contact you (if Dimas can be so kind to forward your email :).
@rzr: count me in on that code… I am very interested in how this might be accomplished in a clean way.
@rzr
Me Three! 🙂
Hi, really dumb question here… how do I include the meta boxes I’ve created using WPAlchemy in a custom post type? I have read up in the codex on how to register a post type, but I can’t figure out where in that function I call in WPAlchemy. (Or am I coming at this from the wrong direction altogether?)
I won’t bother repasting the code I have now as it’s copied directly from http://codex.wordpress.org/Function_Reference/register_post_type 🙂
Thanks so much for your help!
@michelle- i asked that question a bunch of comments up and here was Dimas’ answer. you don’t enable WPAlchemy in the declaration of the post type. you enable it when you define your meta box.
http://farinspace.com/wpalchemy-metabox/#comment-4682
@rzr- can’t wait to see what you’ve done w/ the media uploader!
@kathy, thank you! I think I’ve got it – I had tried that but my box wasn’t showing up due to also using include_template. Took that off and the boxes appear on my custom post just fine.
Hi and thanks (again!) in advance for any help. 🙂
I have everything working for a set of metaboxes which only appear when a page is set to use an “Agreements” page template. One of the metaboxes contains a list of “offices” checkboxes. Each item in the list is actually a link with a title, display name, and URL.
What I’d like to do is allow the end-users to add to that list of checkboxes and have their additions be available to other users on other pages using the “Agreements” template.
So, I set up a new instance of WPAlchemy and a new meta/page template called “Offices”. Now users can edit the Page called “Offices” and add new offices, designating their display name, title, and URL.
What I’m having trouble with is pulling those values into the “Agreements” meta template.
Hope that made some kind of sense!
Here’s how I’ve declared my two WPAlchemy instances:
Here’s my meta-office.php (linking off because I can’t figure out how to show php+html in these comments, sorry):
http://friendly.pastebin.com/1FHVuJ4R
Here’s my meta-agreements.php – see lines 11-18:
http://friendly.pastebin.com/QbQcf52v
Did I go about this entirely the wrong way? Thanks so much for your help!!
Small correction to meta-agreements.php (I’d renamed the fields and forgot to update everywhere): http://friendly.pastebin.com/gNq6cUxu
Small correction to meta-agreements.php (I’d renamed some fields and forgot to update them everywhere): http://friendly.pastebin.com/gNq6cUxu
Michelle, In your “Agreements” meta/posts you would need to use the
$custom_office_metabox
var. The values of specific meta boxes are not shared with one another. So for instance “offices_group” are unique in each meta box definition.To use
$custom_office_metabox
… you would some something like:Another way of doing this, which might be a bit more complex … is to create a custom post type of “office”, then define a meta box specific to the post type. This would give a simple interface to add/remove/view “offices”.
Then in your “Agreements” posts or any where really. You could use default wordpress functions to get all posts of post type “office”.
The nice thing about this method is that you are using default wordpress functionality, for adding “items” and combining it with wpalchemy, for customizing the UI (even hiding the default editor).
Thanks so much, Dimas!!
I like the second suggestion, but for this site I think I have to use the first. (Each “Agreement” may have several ‘offices’ associated with it, and I have to display the list of Agreements and associated Offices in a huge table. There will likely be under 20 offices total; I just prefer not to hard-code the arrays of office data in the templates in case my clients ever want to add more.)
I’m trying to get the first suggestion to work and here’s where I’m at – It displays the office data great in the Agreements metabox, but the checkboxes aren’t saving when I update the page. Here’s what I have in my meta-agreements.php – I didn’t change anything else:
http://friendly.pastebin.com/fGS1n8Lk
Any suggestions? Thanks again for your help and your FANTASTIC code!!
@Dimas
Any updates with the RZR media upload extension? Thank you.
@rzr
I’m as well interested in the implementation of the media upload feature for WPAlchemy. I would like to have a look at your source code for my inspiration. I’m currently customizing a metabox for a university project. The custom_field_template isn’t a nice alternative.
Thanks a lot!
der/dot\herr/dot\c/at\googlemail/dot\com
I am getting the following error when trying to access the meta values from loop-tag.php
Fatal error: Call to a member function the_meta() on a non-object
Any help on this would be much appreciated. Thanks!
@Elaine, you may need to do the following before using the
$custom_metabox
object.@Leland, RZR is currently hard at work on writing a tutorial on how to setup custom communication between the WordPress Media Manager and fields in a meta box.
@Michelle, checkboxes can be tricky sometimes, have a look at the “checkbox_meta.php” file which is included in the source files.
Hello,
I was wondering the same thing as Ross above. How to write some conditional logic for a field.
In English:
Get the field
Check if it’s empty
If not, display the the value
else echo “field not specified”
Really, really nice work you have here ^__^ Thanks!
@Andy H
Are you looking for something like the following?
Claudio, I’ve updated you example above with
$custom_metabox->get_the_value()
…Something seems to be wrong with it.
It does not like the get_the_value() on this line:
if(!empty($custom_metabox->get_the_value()))
Big thank you!
@Dimas,
I mentioned awhile back about possibly having the ability to sort have_fields_and_multi() items. I’ve gotten this working with the drag and drop action applied if your interested. I’m not sure about the best/easiest way of implementing it into your class though.
Luke, please send me what you have … I will implement and release a new version, it’s one of those features currently on the to-do list.
Dimas,
Excellent work here–the class has saved me a lot of time and added valuable functionality to many of my clients’ sites.
I also have a question regarding using WP Alchemy in WordPress posts. I have used metaboxes many many times in pages, but now I am trying to use them in posts and I am having trouble. I have a metabox set up as follows:
When I try to reference the data using
the_value('test')
in the loop.php file, the page breaks at that point (no further output). I have tested the same reference on a page and it works just fine. I am a beginner at PHP, so I’m sure I’m just missing something obvious here…I’d really appreciate your help!
Philip
@Phillip, have you tried adding
global $postType_metabox;
to your loop.php page?@Luke, your fast!
Philip you may also want to try to add the following, this will ensure that you see any errors that are output.
I’m have a set of checkboxes in my metabox and I am trying to pull in the values of the checkboxes into my template. When I do, all I’m getting is the first character of the checked boxes value.
For example, if I had check boxes checked for “Web”, “Print”, and “Logo”, I would only be getting “W”, “P”, and “L” to show on my page.
@Luke,
Thanks! It works! But…why does it work? Was loop.php trying to reference the data before the object was created in the function.php file?
@Luke, see if checkbox_meta.php in the WPAlchemy download can help answer your question on checkbox usage.
@Dimas, I may not have explained my problem correctly. I have the metabox working fine. It’s when I try pulling the values into my page template, for example
page.php
. It’s only displaying the first character of the checked boxes.Example Screenshot
Maybe I’m overlooking something in the
checkbox_meta.php
you suggested?@Luke, try the following:
If you call out
echo $custom_metabox->the_value('services');
, it’s like echoing an Array, PHP printing first letters are usually a tell-tale sign of dealing with an Array.When you use
have_fields('services')
, the field will automatically get defined, allowing you to target the individual values of the Array withthe_value();
calls (with in the loop).@Philip, the basic reason why one would use
global $var
is to access a global var in a local scope. Typically the local scope is within a function call. What I think is happening is that WordPress is including “loop.php” with in an internal function call. Because of this, the contents of “loop.php” are subject to the same scope as the function. Using theglobal
keyword with in “loop.php” (essentially within the function call) allows you to access the global var as defined in the global scope.I am thinking of adding a helper function for this, and using it as a standard convention, something like:
What do you think, if it becomes a standard convention then users really wouldn’t need to worry about calling
global
.Hi Dimas,
I’ve tried every combo of code I could think of using meta_checkboxes as a template, but I can’t seem to get the checkboxes populating and then the values saved into a different array no matter what I try. See my original comment and code from http://farinspace.com/wpalchemy-metabox/#comment-8513.
I have one metabox group, “Offices”, where users can add Office Name, URL, etc.
In the Agreements metabox, the Offices users added are displayed in a checkbox list, so users can check off the offices that pertain to that Agreement.
The code above displays the Office list fine in the Agreement metabox, but the checkmarks aren’t saving on Update.
Thank you so much for your help!!!
Michelle
@Dimas, worked great. Seemed to easy… I should have probably been able to figure that one out 😉 Thanks!
… any news concerning the Media Upload feature? Need it these days.
+1 on media upload as well as drag and drop (sortable) fields and field groups 😀
The “Attachments” plugin offers drag and drop capability in case a code example is welcome. It’s the same code that was used for the “Simple Fields” plugin (per the “Simple Fields” change log).
@Dimas – I’ve been watching WPAlchemy progress since last September… very impressive work and your efforts are MUCH appreciated!
@Everyone else – your participation on this thread has been fanatastic and I appreciate your efforts as well!
@Dimas,
+1 on the upload
+1 drag and drop ordering of meta boxes or groups
Any updates?
Dimas,
Turns out calling the global variable doesn’t solve what I am trying to do–only one value is stored, meaning that even if I have different values held in each different post on the page (referenced via
$postType_metabox->the_value('type');
, for instance), the last metabox value will show up in each case…which makes sense since they are all being called with the same reference.Any idea how to get around this?
Figured it out! Just stored the post id in a variable and changed the reference on the front and back ends to:
$postType_metabox->the_value("type$thisID")
@rzr
Saw in your screenshot you are a dutchie. Where do you live so I can come give you a hug when that Media Uploader thing is available. 🙂
Hello,
I have trouble to get two set of fields working. I try to do it the way mentioned here http://farinspace.com/wordpress-meta-box-next-level/
This is the code:
The problem is that I can’t pull the values from the second set of fields. If I put the
$custom_metabox
also in the front of the second set, I can pull the values, but then the first set breaks down. I’m running 3.1 RC3.Help is much appreciated 🙂
Andy H, when creating the
WPAlchemy_MetaBox
object you should assign unique variables for each. So in your instance, I would use$custom_meta
and$custom_meta_artists
variables.I’ll adjust the tutorial so that its more clear.
Hi guys
This class is great. Very helpful.
I was having problems with the_select_state() in my code. It was rendering the selected=”selected” part outside of my option tags.
So I changed line 1784 of the MetaBox.php file to read ‘return’ instead of ‘echo’. And this seemed to work.
I’m not entirely sure it’s a bug, because it might be my code that’s causing this workaround, but I thought I’d raise it.
Cheers
Chris
Chris, one key concept to understand about WordPress and also a concept used in the WPAlchemy class is the “get_the_x” and “the_x” functions … they come in pairs.
Use “get_the_x” functions to get a result, a string, number, etc.
Use “the_x” functions to print a result, a string, number, etc.
just echoing leland on the media uploader and drag and drop sorting. also, how is the taxonomy class coming along?
i posted this issue at github, but perhaps one of the other users has come across it when using the have_fields_and_multi function. i’m using the latest dev version (i also tried the 1.4.1 tagged version) and get the following error:
Uncaught TypeError: Cannot read property ‘1’ of null
which applies to the var the_limit declaration in the checkLoopLimit function
function checkLoopLimit(name)
{
var elem = $('.docopy-' + name);
var the_limit = $('.wpa_loop-' + name).attr('class').match(/wpa_loop_limit-([0-9]*)/i)[1];
if ($('.wpa_group-' + name).not('.wpa_group.tocopy').length >= the_limit)
{
elem.hide();
}
else
{
elem.show();
}
}
seems to be looking for a class wpa_loop_limit that isn’t in the markup, so the_limit is coming back undefined and breaking stuff.
also regardless of how i set the limit $this->_loop_data->limit seems to come back as unset.
tried both:
$mb->have_fields_and_multi(‘docs’,5)
and
$mb->have_fields_and_multi(‘docs’,array(‘length’=>5))
if there is no limit, then it seems like it shouldn’t call the checkLoopLimit function. and if there is a limit then it doesn’t seem to be picking it up.
Not having the clearest of days so hopefully I am just missing something obvious.
Kathy, thanks for the heads-up, I will get this issue fixed today. Use the previous version for now if you can.
I am trying to WP Query custom posts to use inside of a dropdown/select box using WP Alchemy, does anyone have any tips?
I would like for the options to display the postname, but their value be the Post ID.
Any clues?
thanks Dimas! In the end I adjusted how I was going to proceed and took a different route. Coming back to the multi groups again, but I don’t need the limit for the moment. But pertaining to multis with radios (and radios in general), is there a way to set a ‘default’ value? seems to me that radios are supposed to have something selected at all times. i’ve sort of managed this:
$mb->the_field('r_ex3_r');
if ( (NULL == $mb->get_the_value()) && ($i=='x')){ $default = ' checked="checked"';} ?>
and then echoing the $default variable in the input i wish to designate as default.
<input type="radio" name="the_name(); ?>" value="x"the_radio_state('x'); echo $default;?>/> x
the code tags aren’t preserving my code right (switching php on/off) but I hope you get my point. however, I think it would be more elegant if the default could be a second parameter in the_field, like this maybe?
$mb->the_field('r_ex3_r','x');
or maybe better still as a parameter in the_radio_state. just marking the default value with a second parameter of true
$mb->the_radio_state('x',true);
Got everything working perfectly, thanks to the help of some of you here!
Luke, i’m interested in your sorting concept- as I’ve applied this: http://quasipartikel.at/multiselect_next/
to a multiple select box and need for the saved selections to sort by the order they were dragged.
@Dimas
Any idea when you will have time to implement the uploader and drag/drop sorting of fields or groups? I would be happy to make a donation for this dev to speed things up if that would help. Or assist in this coding? Thanks – these two features are the final missing features to make your framework a leader on the web. After Attending WordCamp Phoenix AZ 2011 I can say most devs have no idea how to manage these features in themes. Good work.
ok alchemists- i’ve been one of the ones clamoring for the media uploader and had been holding off on doing it myself. it may not be as elegant as what is coming down the pipe from @rxr but if you need it now, try this out:
to see what we’re going to attempt:
http://img43.imageshack.us/img43/2867/metabox.png
it is a repeating group that should hold an image, a text input and a text area.
this is the bit that defines the boxes in my functions.php :
http://pastebin.com/bMtLC0Rj
this is the template for the metabox – new_featured_meta.php :
http://pastebin.com/w0EeTwNi
you should note that in my functions file i identify the template as:
'template' => FUNCTIONS_PATH .'WPAlchemy/new_featured_meta.php',
so i have the template in a folder called WPAlchemy inside a folder called functions
my setup looks like this
functions/WPAlchemy/new_featured_meta.php
functions/WPAlchemy/MetaBox.php
functions/WPAlchemy/meta.css
functions.php
and finally a bit o’ style- meta.css :
http://pastebin.com/uBMaL4VS
i spent the last day on it and so I hope that helps someone else. i’d also love to hear thoughts on using the WP uploader versus an script like Ajaxupload.
@Leland, I very much appreciate your thoughts. Having insights like you do from an actual dev conference is very very useful.
@Everyone,
Here are my current goals: I will be implementing drag/drop/sorting and a built in way to incorporate @Robbert (rzr) media box -to- field connection for the 1.4.x branch (and then bug fixes + updates).
I have started a new 2.0 branch which will be a total revamp of WPAlchemy. Code will be cleaner, better naming conventions, structured parts: WPAlchemy_Form, WPAlchemy_Meta_Box, WPAlchemy_Taxonomy, WPAlchemy_Admin_Menu. I want things to be less confusing and also bundle it as plugin with the ability to have child-plugins (so that people can share their, meta-box creations, admin-menu, creations).
What I’d like to hear from all of you who are using the code in your projects is the “What sucks” part, What sucks about using it, What sucks about how it works, etc. Please contact me and send me your thoughts.
@Kathy, awesome job! When I begin to implement, I will be taking parts from both your’s and @Robbert’s (rzr) solution.
Do you prefer, having your own upload button, vs using the default wordpress media uploader?
@Dimas
If possible hooking into the WP media uploader would allow users to grab files that have already been uploaded or from other activated galleries such as the nextgen gallery (which loads in that window) that a TON of people use for multimedia management.
The WP uploader isnt the best but it would make sure not to duplicate uploads etc
Just my two cents,
Thanks
Thanks Dimas. What was funny was that today as I was googling around for help on the solution to dealing w/ the media uploader i actually uncovered my own question on stackoverflow from 5 months ago. I guess i never figured it out then as I realized my old solution was flawed, but it seems clearer now, so i hope that it works as expected.
Regarding WP Upload versus my own upload, Well I was thinking something similar to @Leland.
The upside of hooking into the WP uploader is that is 1. familiar, and 2. lets the user select images that have already been uploaded somewhere.
The downside is that it is 1. clunky, 2. presents an extra step and presents the possibility of the user inserting a thumbnail when you need the full version. I supposed that last part could be solved w/ some preg matching in a save filter? Haven’t gotten that far into it yet. Spent some time today with regex and still believe it is voodoo. Ended up not using it.
I am using AjaxUpload in my theme options for a logo and background image, and it is definitely easier, but there is no way to access previously uploaded stuff.
I can’t wait to see these other parts of WP_Alchemy!
With the WP Media Uploader option everyone is talking about, will it be possible to replicate WordPress’s “The Post Thumbnail” for images that are uploaded?
Having the thumbnail that is clickable to show the larger version?
Hello,
Very good job Dimas, thank you for this great Classe.
I’m just waiting for the Media Uploader now, i think it could be useful for everybody (me included)
@rzr if you hear us 😉
I’ve been trying to find a way to create a dropdown of pages similiar to
wp_dropdown_pages()
, but inside of ahave_fields_and_multi()
loop. The problem I’m running into is each time I update the page, another group is added to thehave_fields_and_multi()
set.Here is an example of the code in use. This involves a
foreach
loop inside the while loop. My guess is this is not “allowed”, but it seems like I’m close.Thanks, in advance for any ideas!
@Dimas,
Any idea about when you will have a chance to finish the 1.4 branch? Just so we stop pestering your comment board 🙂
Thanks
Hi Dimas,
Awesome code, I’m starting to implement it in a big project I’m just starting…
One question I still couldn’t solve… How do you search within the newly created metaboxes?
Can you perform a search only within a specified field?
I’m trying a different approach on the TinyMCE implementation and when I get it working right I’ll post it here, so far it’s great with visual/html and image upload, etc… but has a little bug I’m trying to solve 🙂
Also, I used a different aproach for conditionally displaying a field within a theme-template’s loop:
Well, thanks loads anyway, your class is awesome!
t.
Just another thank you to Dimas. Your class has been a great inspiration for me as well as incredibly useful.
@Luke: The problem you are having is that the NONE state of the wp_dropdown_pages, wp_dropdown_categories is -1. And WPAlchemy_MetaBox only seems to be checking for NULL when deciding when to save and when to delete no longer used options. Since -1 is not NULL it is being saved as a new option regardless. I have been writing an abstraction to use WPAlchemy_MetaBox with automated form creation and the have_fields_and_multi() drove me crazy because of the very problem you are experiencing until I figured out why it is happening. I have only given a glance at the problem and had hoped to be able to send Dimas a pull request with a fix but haven’t had any time to attempt it yet.
Until that is resolved it doesn’t seem possible to use wp_dropdown_pages or wp_dropdown_categories without creating a new entry every time the post/page is updated.
Hope that helps. 🙂
Hello,
First off, like everyone here, I just have to say thank you. Your work here is amazing and has helped me immensely.
To be honest, I just learnt about meta boxes and custom taxonomies two days ago, but I have managed due to your tutorials and a couple of others to get my project close to completion.
I have created a metabox for adding ingredients to a site, however i want them to be stored as a non-heirarchal custom taxonomy I have also created.
The code for the metabox is below
Is it possible to have the name field stored as taxonomy tags.
@zoe, the
have_fields_and_multi()
function, the whole class handling the looping is something I might do away with in version 2.0 and simply simplify things.@Luke, give me a link to your code again so that I c an take a look. I am going to be finishing off the 1.4.x branch.
Dimas, looks like the link didn’t work before, which would be helpful… here it is again. Thanks for the look. http://snipplr.com/view/48388/wpalchemy–trying-to-get-pages/
Hi everyone, I thought I would post this here first before creating a dedicated post for it. @Luke turned me on to Screenr so I thought I’ve give it a go.
Creating sortable repeating fields is quite easy, and as I was working with it I really don’t think it needs to be added into WPAlchemy at the moment.
Making WordPress Meta Box repeating fields sortable
http://screenr.com/Dsf
Making WordPress Meta Box repeating fields sortable #2 (follow-up)
http://screenr.com/csf
Hope this helps folks! Also, grab the latest version on github.
@Luke, here is a working version. Things to note first:
$pages
is outside of the loop, no need to call it every iterationthe SELECT html now starts with a blank item (important) starting with a value causes the adding of the additional field … I will look into this further.
WPAlchemy has a
the_select_state()
function, you’ll notice its use here. It needs documentation above.https://gist.github.com/822101
@Dimas – awesome job with the screencasts! Will be using that right away. Thanks!
@tcherokee, can you do me a favor and post your code using gist.github.com … so it comes through ok and I can simply copy and paste it for review in its current state.
Earnestly I want to give heartfelt thank you for your work on MetaBox. Your work is helping so many people up the quality of their work significantly, me especially. And thanks for the tip and screencast on the sortables. I will be implementing that shortly. Humorously enough I was thinking today while working on a client project about what happens when the client wants to reorder the content. And like your psychic, lo, an answer appears. Keep up the amazing work.
Regarding have_fields_and_multi() I am not sure if you mean you are going to get rid of the entire functionality or modify how the…oh, you mean WPAlchemy_MetaBox::_loop(). Huh. I’ll keep an eye out and post through github so I don’t clutter up your comments anymore 😉
Hi there,
I was just wondering when the image/file uploader tutorial will be posted?
Thanks,
Matt.
Hi Dimas,
I have added both the metabox code and the taxonomy code to Gist.Github
What I want to accomplish is when the metabox is saved, the value(s) in ingredients gets saved in the Ingredients taxonomy as well.
Thanks for your help 🙂
T.
@matt – i posted my code for using the uploader at:
http://farinspace.com/wpalchemy-metabox/#comment-9163
it likely isn’t as elegant or as powerful as when rxr and Dimas are cooking up, but it does work in the interim.
@kathy
Hi Kathy,
Thanks for getting back to me. I tried to use your method but when you used the default media uploader to add an image to the main text box it just added the image to custom meta box instead. Is this just a bug I’m experiencing or is that the way the meta box is intended to work?
Matt.
@kathy
Hi Again, I was looking at the wrong comment, I was looking at one much further up the page… my bad.
ps love the domain name!
@matt- yeah i remember that bug, but was pretty sure i squashed it. thanks for the compliment on my domain… one day i might even have my portfolio site go there. eventually
howdy. I’m having some issues with get_index(). The index seems to work for any existing groups and if you add just one more group but not for any subsequent groups added before saving the page.
In other words. If I have 5 entries that already exist when I come to my edit page, The indexes are all correct (0-4). If I add ONE group (or entry) using a docopy- button, The index on that group is correct (5). However any groups added after that first one have the same index (5), rather than incrementing (to 6, 7, 8 etc.).
Is this a bug or is there an error in the way I’m doing things.
If that is expected functionality, How can I create (and save) an incremented index for each new group (entry)? I will potentially have the need to add several entries before saving the page and other scripts on the page require a unique ID on certain elements.
Thanks, Shag.
it is relatively easy enough to make a select list with all your wordpress pages, but i really like the layout/look of the wp_dropdown_pages list, so i worked a little string and preg_replace voodoo to make it work with WP alchemy. the form element in your metabox template:
$mb->the_field('page_id');
$dropdown = wp_dropdown_pages(array('show_option_none'=>'Custom', 'echo'=>FALSE));
$dropdown = str_replace(array('name="page_id"','id="page_id"'),array('name="'.$mb->get_the_name().'"','class="page_id"'),$dropdown);
$dropdown = preg_replace_callback('|value\=\"[0-9]+\"|','wp_alchify_dropdown',$dropdown );
echo $dropdown;
and the callback function.. supposedly you can use an unnamed function IN the preg_replace_callback so you don’t pollute the ‘namespace’ but i could never get that to work. note that i had to declare the object name of the metabox i was working with (so it isn’t perfect) as the callback only passes the $matches and you can’t send it the $mb variable.
function wp_alchify_dropdown($matches){
global $featured_metabox; //this is the object name of the metabox i am using the dropdown list in
preg_match('|[0-9]+|', $matches[0], $int_matches);
return $matches[0] . " " . $featured_metabox->get_the_select_state($int_matches[0]);
}
@Dimas,
Any dev version of the 1.4 branch ready for testing?
Leland, checkout my screencasts on sorting:
Making WordPress Meta Box repeating fields sortable
http://screenr.com/Dsf
Making WordPress Meta Box repeating fields sortable #2 (follow-up)
http://screenr.com/csf
I just have the media box integration part which I will tackle shortly. Dev is still going for v2.0 (little slower than what I hoped, but coming along).
@Dimas
This is looking amazing. The only big piece I badly need is the multiple media upload feature. Very cool drag and drop stuff. Do you have the 1.4 branch publicly accessible via github? Or are you holding off on publishing the new feature code until 2.0
The latest github release has all that is required. I’ll put together a tutorial on media uploads as well.
Sorting now available with Media Upload coming? Sweet! 😀
@Dimas
This is fantastic. I will download the lastest push and give it a try. Keep me updated as to when you would like that extra PR. You are the kind of developer we need speaking at Wordcamps….hint hint WC Vancouver…
These developers tools are unlike any other tools available for theme development.
@Kathy
Does your slideshow metabox code use the latest 1.4.4 version of WPalchemy with drag/drop and uploaders?
http://img43.imageshack.us/img43/2867/metabox.png
I would love to see that posted if it does.
Hello,
I use WPAlchemy_Metabox in a WP page “A”. When i want to display the data of this page on the front-end, no problem, my title, content and metabox data appear in my template.
But if i want to display the data (title, content, metabox) of page “A” in my homepage with the function “get_template_part()” the title and content display but not the metabox data (and below the rest of the page is blank).
If i use get_template_part() in my homepage but copy/past the code wich display just the metabox data from my page “A” to my homepage, it’s work.
Is it possible to code the loop and the metabox code in the same WP page and call all these data with the “get_template_part()” in my homepage (WP 3.+) ?
This is the code in my WP page “A”
(it’s work if i call the page directly but not if i call the page by my homepage with get_template_part(‘pageA’); ) :
$pagename='services';
$args = array(
'post_type' => 'page',
'pagename' => $pagename
);
$the_query = new WP_Query( $args );
while ($the_query->have_posts()) : $the_query->the_post();
// page data
the_title();
the_content();
// metabox data
$custom_metabox_services->the_meta();
while($custom_metabox_services->have_fields('docs'))
{
$custom_metabox_services->the_value('title');
$custom_metabox_services->the_value('link');
}
...
php endwhile;
And i want to call this page “A” in my homepage like this :
...
get_template_part('pageA');
...
Any idea ?
Oh sorry !
I see (to late) in the comment above that the problem has already been treated.
It’s work well with : global $custom_metabox_services->the_meta();
Hi Dimas,
“bug” report: If you didn’t specify the $arg “title”, then the meta box simply won’t appear. I saw that you added a notice on die(); for other stuff. Maybe you want to add a notice for this one too.
Btw: Thanks for Wp Alchemy, it absolutely rocks!
@Dimas
Great, looking forward to your upload screenr.
@Leland,
Yes, I believe the code I posted uses 1.4.4. if it doesn’t have the drag/drop fields, i merely just added the code from Dimas’ screencast, so there is nothing extravagent there. I’d check and post again, but my internet access is really spotty of late.
@Kathy
Okay awesome – I just want to make sure I’m using the latest version with wp uploader and drag/drop stuff. I’m hoping to build a nice custom post type with these custom meta box features. Thanks again.
Almost 400 comments here.
This is making it really hard to follow the development.
( It’s confusing to figure out which issue is already been fixed, or which request is on – or not on – the list. )
Would it be better to keep this page only for documentation, and open another page or for discussions ?
Anyway, Thank you for sharing this scripts ( by far, the best, the most promising – actually looks like it’s already, the promised land of custom meta box implementation ! )
Paul, thanks for your comments … other have expressed similar thoughts about the length of this page. In the next week or so I will try to move this project to a forum type system.
If folks know of any good forum software please let me know. Ideally I’d like to avoid bigger packages (such as phpbb), I am thinking of something a little bit more minimalist and simple.
I could suggest bbPress (http://bbpress.org/). Easy to install with WP.
Justin Tadlock use this forum on his website ans it seems to be great : http://themehybrid.com/support/
Even better as a forum solution is Vanilla:
http://vanillaforums.org/
Afaik, The Pods plugin (podscms.org) has got an easy to setup & manage add on for this. Scott K. Clark wrote it about a year ago, so i guess it’s pretty mature now and would fit perfectly (in context) to your meta box class.
Forgot: Demo -> http://scottkclark.com/forums/ and download under http://podscms.org > Packages > bbForum
Hi all,
I’ve been using WPAlchemy metaboxes to build a quite complex website, BRAVO Dimas for bringing it to us!!
I’ve been strugling with one thing I can’t solve and that is allowing users to SEARCH the Custom Field Values.
I’m using the class with the mode WPALCHEMY_MODE_EXTRACT so I get the values on normal custom fields but I can’t get a reliable solution for search.
I’ve tried plugins for custom field searching but they don’t play nice with the latest versions of WP.
Do any of you have a nice solution for searching through the custom fields?
Thanks loads!
t.
I think you could take a look on this trac ticket – http://core.trac.wordpress.org/ticket/15066 and maybe propose the include of your amazing class to WordPress Core.
Please take a look.
Theo Ribeiro: eu costumo usar o Relevanssi, muito melhor que o search do wp e está atualizado. É definitivamente o melhor plugin de busca.
Translated: Theo Ribeiro: I usually use Relevanssi, much better than wp and the search is updated. It’s definitely the best search plugin.
Hello Dimas,
First, thanks for the amazing work you’ve done here, not just in the initial development but in the continued support. I can only imagine how much time it has taken.
I’ve been able to use WP Alchemy pretty well while building out a new site. But I’ve run into some problems when entering shortcodes in my metaboxes, and was hoping you might be able to help. I got the shortcodes to work fine with a single metabox text field. But when I use have_fields_and_multi, it keeps showing the raw shortcode text on my webpage. I tried the advice you gave @Said. I’ve also tried suggestions I found elsewhere for using apply_filters(‘the_content’) to get shortcodes to work from metaboxes, but nothing seems to work with the have_fields_and_multi code. Any suggestions?
@All, thank you for the forum suggestions.
@Heather, when you output your content into your view/template, use the
do_shortcode()
function, this should output any short codes you’ve entered.Obrigado @Victor Teixeira, ontem depois de muitas horas de busca e insistência eu cheguei justamente no Relevanssi e agora estou usando ele feliz e contente! Realmente a melhor opção!
obrigado
Translated: @Victor Teixeira, yesterday after many many hours of searching for a better solution I eventually stumbled upon Relevanssi itself. Now I’m happily using it and it is indeed a great search plugin.
Dimas,
Thank you, thank you! It finally works! It’s just so beautiful! 😀
Hey so I had a previous question about how do I actually display the custom meta in my templates or posts and I was wondering if you can simply show me the basic code for say.. a single post?
I’ve created a “$custom_metabox” with various fields like firstname, lastname, email, phonenumber, location…etc.
Then I created a custom template page and called it “single-resume.php”. I think I only have a loop in the temple and nothing else. Here is my code..
Do you mind showing me how do I set this up for my custom meta to show up with those fields I gave you? (firstname, lastname, email, phonenumber, location)
This is my function.php code..
This is my user_profiles.php..
Thank you and I really appreciate your help. School projects are getting more hard and hard..eh.
Thanks.
Vadim.
Ok the user_profile.php didn’t really show up as i have it in the code. The tags are missing..
I just have it how it is in the documentations..
@Dimas
Any word on a screencast for the updated wp upload meta box?
Thanks.
ok…some progress.
I have been able to pull the data from my custom metabox and save it in a taxonomy using the following function
I have not been able to pull the specific value i need and it is the full array that gets pasted in my custom taxonomy
I was wondering can i pull the value from the “wpv_recipe_ingredients” which should be “test”
Tolumi,
If the “wpv_recipe_quantity” is part of your meta box values it should be part of the
$meta
variable … You do not neeed to get the$meta
var again.try the following so you can see what you are working with:
Vadim, sorry for the late reply, hopefully you’ve figured it all out …
Using the meta box values in your template is pretty straightforward. Have you seen the Using The Meta Box Values In Your Template section?
Dimas, yeah I followed those instructions and inserted the code into my template file but no meta box data shows up when page loads. I was just wondering if I’m dropping in the code correctly or into the right place?
Hi Dimas,
I was attempting something similar to the standard WP loop that tests if there are any items in the WPA group before going through the while loop. I thought it might be good to have an if/else situation and an error message if there was no content.
so i tried
if($featured_metabox->have_fields('slides')){
while($featured_metabox->have_fields('slides')){
if($featured_metabox->is_first()){ echo '1st bacon';}
if($featured_metabox->is_last()){ echo 'last bacon'; }
}
} else { echo "you borked it"; }
but when there is content, something about that first if statement seems to invalidate the is_first() function and it never triggers.
is there a way to do this or might it be considered for a future release? cheers!
Kathy, try using:
the
have_fields ...
functions are meant to be used in a while loop, theis_first()
likely does not fire, because the internal index tracking gets screwed up with the initialif
statement.@dimas – awesome! that was it. i noticed (now that i know what the function is called) that you’ve answered this same question several times in the comments. first, thanks for answering me anyway! and second, maybe if you get a minute you could add it to your awesome docu so hopefully we can stop pestering you about it. 🙂
So, anyone have any idea on how we could incoporate WordPress 3.1’s new Internal Linking feature into a metabox?
It’s currently only availabile via the TINYMCE editor… but i’m sure there’s a way to get it into a metabox….
Kathy I just wanted to say I find it hilarious that you use “Bacon” for your echo statements. I’ve echo/print/alert/trace’ed the term “Bacon” for years. 🙂 Strange, it’s always the first thing that comes to mind.
From: http://wordpress.stackexchange.com/questions/8749/use-wp-3-1-internal-linking-widget-as-a-meta-box
I see we have these files…
/wp-includes/js/tinymce/wp-mce-link.php
/wp-includes/js/tinymce/plugins/wplink/js/wplink.js
@Joe- lol, indeed. i think i stole the idea from Ian Stewart when I was first learning Thematic and never saw any reason to change it! usually i set up my ‘fail’ condition to say something like ‘no bacon for you’, so it is extra disappointing!
i think dimas has a post on using multiple text editors, which is where i got the following code. but now that WPA supports footer_action you don’t need to use the normal add_action call. you can do it in the metabox declaration.
add this to your metabox array:
‘foot_action’ => ‘my_admin_print_footer_scripts’,
and then this is the function:
http://pastebin.com/4wjK2sTz
i just tested it and it gets all the new buttons that you might have added to your editor.
Hi Dimas,
Thanks for all your hard work on this – it is an amazing framework for developers.
I have got the metaboxes setup perfectly for custom post types and the data being successfully displayed in the front end templates. However, I am having difficulty with a metabox I have created for a singular page (Contact page). My issue is I can’t for the life of me get the data displaying in the front end template. Here is my code:
The data is successfully saving to the particular Page ID.
Would you be able to give me the template tags for retrieving this content on the front end?
Also an indication of where they have to appear, ie. In the Loop etc.
Many thanks
Paul
@paul – did you read this section?
http://farinspace.com/wpalchemy-metabox/#template
Paul,
If you’ve successfully got it working in your post types, then it should be no different for the pages. The thing to keep in mind, is that WordPress always has a
$post
global variable floating around. WPalchemy will use this var to detect for which post it needs to get the meta data for (typically in The Loop) … however there are instances where it can not do this:1) outside of The Loop, when no
$post
global is available2) when being used in a custom function, a function you created or a theme function
To get around this you can use the following, before going on to retrieving your variables.
Thankyou Dimas & Kathy for the replies…. I think it was a case of midnight coding brain not working – as it worked perfectly this morning. Now onto setting up multiple WYSIWYG editors.
Thanks again.
@dimas – do you have an example of a save filter?
Hi Kathy,
See this comment (I know, I know, all this useful data will be transfered to videos and other tutorials).
The main difference between
save_filter
vssave_action
is that with the filter, you must pass back the$meta
value, but you can modify the array before doing so, which allows you to save hidden values.The power in using any of these options is that you can manipulate other aspects of WordPress during an post update and per the values that a use enters in.
Oh, here is a video on Display Options which I did a while back, and will be released with the new version of the site. Should be useful to everyone.
Is it possible to export/import the metabox content (xml file) with the WordPress import/export feature ?
This doesn’t work for me (just ok for the post/page content)
@NetConstructor.com: I’ve managed to fix that issue by replacing this part of your code:
…with this:
Note, change the value form using $term->term_id to using $term->name. $term->term_id seems only to be for hierarchical taxonomies.
Hope that helps 🙂
Caleb
@Dimas
Thank you. I can only imagine how much time you have spent on this, answering questions, etc. Your dedication is admirable and this comment is simply to say thanks.
(and to follow this thread via email.)
@Dimas,
I am going to second the previous statement. You have given us a great tool and spend a lot of time helping us save time.
You… rule. Thank you!
Thanks for the incredible class you’ve put together. I’m still learning it’s ins and outs but its helped a lot so far.
I am excited you’re working on a admin options/plugin class, this will be very helpful.
Just another giant THANK YOU! I also saw your work being referenced as the “goto” example of a possibly upcoming WP metabox class … most excellent!
For those who may be interested … I’ve created a helper class used for Media Upload Box Integration, If you do have the opportunity to try it out please give me your feedback.
Dimas, the MediaAccess class doesn’t work well within have_fields_and_multi.
This has to do with the value of $wpalchemy_media_access->setGroupName and how the “last tocopy” group is constructed
Specifically:
– Add one field, then save. The last field gets duplicated.
or
– Add multiple fields at once, all of them get the same value, plus a duplicate shows up after saving.
Ya, still in dev, thanks for the feedback, I’ll have a fix for that sometime today
@Rhiannon, I’ve made an adjustment to the MetaBox class, latest v1.4.5, when using the MediaAccess class you can do something like:
the “n” + NUMBER will automatically get updated/incremented.
I’ll post a video describing it in a little more detail tomorrow evening.
No, thank you for the great work 🙂
Anyway, I managed to fix this particular problem by changing line 357 from this
to this
I made other changes, I’m posting them in case they are useful to other people – and so you can work on them if you like them, since I’m kind of a noob at programming.
First of all I added a quick and dirty way to open the media library to a specific file type. i.e.
Here are the modifications to MediaAccess.php:
Add this:
Then modify public function getButtonLink like this
Then, following your video tutorial on making the groups sortable, and by looking around in WP core code, I managed to style the sorting animation in a similar fashion to that of sorting the entire metaboxes.
This goes in the metabox template.
There’s one last thing I’d like to ask you. Is there some way I can allow only a specific file type in the uploader for each group? Say I want a group for uploading a video, another group for a picture etc., and I want to make absolutely sure the end user can only upload the correct file type for that field.
Thanks again 🙂
@Dimas
Ops, I just saw your reply. Testing now, thanks 🙂
I am using the Data Storage type: “Extract” for 3 fields- Address, Latitude, Longitude and wish to run an SQL query to display only these 3 columns with their values.
However I can only figure out how to get one of the columns to show, and it’s data by running this:
SELECT DISTINCT wp_postmeta.meta_value AS address
FROM wp_postmeta, wp_posts
WHERE post_type = ‘dealers’
AND wp_postmeta.meta_key = ‘_dealer_address’
ORDER BY wp_postmeta.meta_value
Could someone point me in a direction of how to run the query to include all 3 columns?
Thanks.
@Joe,
keep in mind that the “extract” storage type is very specialized and you typically (I’d say 99% of the time will not need to use it).
Doing the following would return all the meta if not using “extract”:
However if you do have a specialized case where you actually need to do an SQL query then you can try the following:
This query pivots the results into columns, its a little complex and probably not very optimized:
This one returns the key/value pairs which you can then use to create a PHP array/structure (preferred):
@Dimas,
Your solution did work in setting up the table in the format I was looking for (in your first example).
What I’m trying to do is mimic the setup of the table in this: http://code.google.com/apis/maps/articles/phpsqlsearch_v3.html#outputxml
Because I have a custom post type (dealers) using your custom metabox for latitude and longitude.
Your SQL query tested just fine in phpMyAdmin and looked identical to my other manually-created test dealer table, but when I tried to replace the google maps example query in the PHP- it was a no-go.
Is it too complicated of a query you think?
original test query in the PHP: $query = sprintf(“SELECT address, name, lat, lng, ( 3959 * acos( cos( radians(‘%s’) ) * cos( radians( lat ) ) * cos( radians( lng ) – radians(‘%s’) ) + sin( radians(‘%s’) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
Great stuff.
I ran into a possible bug though, and it’s a bit of a weird one. When using only one single checkbox, WordPress throws warnings:
Notice: Undefined index: rtws_featured_items in /xxxxx/wp-content/themes/childtheme/WPAlchemy/MetaBox.php on line 2090
Notice: Undefined index: rtws_featured_items in /xxxxx/wp-content/themes/childtheme/WPAlchemy/MetaBox.php on line 2090
Warning: Cannot modify header information – headers already sent by (output started at /xxxxx/wp-content/themes/childtheme/WPAlchemy/MetaBox.php:2090) in /xxxxx/wp-includes/pluggable.php on line 897
I found two different ways to avoid this:
1. Turn off debugging (obviously)
2. Add any other field – this is the part that seems weird to me
Here’s my template:
the_field('rtws_featured_item'); ?>
<input type="checkbox" name="the_name(); ?>" value="on"the_checkbox_state('on'); ?>/> Feature this on the Homepage
the_field('ab_solute_non_sense'); ?>
<input type="hidden" name="the_name(); ?>" value="the_value(); ?>"/>
It’s a hidden field that does nothing, at least nothing I need. I bumped into this “solution” when I noticed the warning while modifying your example template, deleting the fields I didn’t need bit by bit.
This is not really a grave error, and I’ve been using a number of plugins that also stop WordPress in its tracks when WP_DEBUG is switched on, but I still thought I should ask about this. I should add that I’ve been playing around with custom meta boxes a lot recently – so it’s possible that I’ve polluted this WordPress installation before trying your script on it.
Is this something you’ve seen before, and can you see or guess what’s going on? I’ll try to reproduce this on a clean WordPress installation soon, but I thought I’d check back here first.
Thanks,
M.
Thanks a lot for this awesome class 🙂
Hi, what’s the best way to sanitize the data when using the fields in a template file?
Will this allow adding a meta box to a taxonomy? So it shows up on the add screen and not just the edit screen of the taxonomy, say like a extra field on the category type..
@Micha, I’ll take a look at the issue. I have a “checkbox_meta.php” included on github which has some checkbox examples.
@Bill, I don’t quite understand your meaning? Currently there is no data validation for meta box fields, however this can be added. Probably the easiest way would be by using javascript to do some basic checks.
Even though data validation is nice to have, i have not had much need for it currently, as website admins/clients have a vested interest in keeping the site looking nice, that is, testing the page after they add content to it.
@Brad, WPAlchemy_MetaBox will not help you with that, sorry. I currently have a lite version of WPAlchemy_Taxonomy, however it doesn’t do what you describe either. But I will take note and perhaps add functionality.
@Dimas, maybe I’m not approaching this correctly. I’m learning still and this seems like a simple task that even WordPress should support, so maybe I need to approach this differently?
Here is what I’ve done:
I have a new custom post type called advertisements. After that I wanted categories for the advertisements called Stores. So, when my client goes to add a new store, meta fields will be available for the store like Image, Url and such.
So I created a taxonomy to the custom post type. But the meta fields are only visible when editing, this is backwards. So for a client to add a store, they would need to use the add function from the Store menu option, after adding the category then go and edit to add the additional fields, this is quite redundant.
But it’s not just your plug-in, it seems like everywhere I go all WordPress shows is edit field entries, nothing for the add screen. I’ve spent many hours searching and it’s frustrating and silly.
Brad, This issue has come up before, however I think I might have a solution for you … it involves a little CSS and JS.
The jist is this: each meta box is identified by ID, something like
_custom_meta_metabox
, you could add some CSS to initially hide the meta box.Then you would use some jQuery to attach some events to the categories checkboxes, which would show/hide specific meta boxes based off of selection.
Conceptually it sounds simple. I will try to implement myself, and perhaps create a video how-to for it.
@Brad,I created a video on how to accomplish what I think you are looking for: How To Show/Hide WordPress Meta Boxes By Selecting Categories
@Dimas, what you did was really good work, the video and code clearly allow assigning meta to a specific category post, hiding when not needed, definitely great information but not what I was looking for, but I can see why you thought that.
I was talking about when adding a taxonomy category assigned to a custom post type. Not when adding the custom post type. Maybe I will send you a video or code.
Lets say I have Admin custom Post type menu option of Coupons.
Coupons
Add new coupon
Categories
Stores
The stores menu option is nothing more than a taxonomy assigned to the Coupons custom post type. So when I click stores, it takes me to a category screen, it’s on this screen that I need to assign meta fields. I hope you understand now. Thanks
Hi there,
That’s a great class and I’m using it and loving it. I have a question:
In my project I have products in categories and news. The news could be about a product category and when that is the case, I put them in that category as well. So I can have a post that is both in News category and Products->Clothes category, for example. I have a metabox with include_category => ‘products’, but it shows on my news posts, because they are too in that category. Adding exclude_category => ‘news’ didn’t work, because as you said “When you use exclude and include options together the include option will override any exclude options”. I have other categories as well (and the client could add some later), so I can’t just exclude news. Can you advice me what to do? I thought of editing the class, but figured I should ask first.
Thanks.
Dimitar, I’d advise that you use the output_filter, this would allow you to create a custom output filter for that meta box. Good for cases where include/exclude are too simple.
That sounds helpful, thanks. How can I get the post id inside the filter function? I suppose I could try with $_GET[‘post’], but is there another way?
Dimitar, I should have mentioned, and my documentation above doesn’t seem to mention it either … the post id is automatically passed … your filter function would look like:
Returning
true
orfalse
will determine if the meta box will get displayed or not.Thanks, it works great!
hello 🙂
is there any possibility to hide editor only in some custom post type?
i create custom post type called ‘imprezy’, then i add metabox like that:
$imp_metabox = new WPAlchemy_MetaBox(array(
// some other configs…
‘types’ => array(‘imprezy’),
‘hide_editor’ => TRUE
));
this hides editor from ‘imprezy’ content type, it is ok. but it also hide editor in regular post, which i want to avoid. any solution for this?
@konradk, the functionality should be working as expected, are you using a custom “output_filter” by any chance?
I will try to take a look at the code tonight for a solution, my initial test between ‘post’ type and ‘page’ type worked well. I will test with an actual custom post type.
Dimas, would it make sense to augment:
$custom_metabox->the_value();
So that the_content filter is applied to it?
If I’m reading your code correctly, the_value() just echoes the field out. thanks.
Hi,
I am wondering if you can help with this request. I am currently using gravity forms to create a front end form for my custom post type and I am wondering if it is possible to integrate your metaboxes within the front end form so users can fill out a form which will update the metaboxes.
T.
When I use the hide_editor parameter and set it to true, it hides the editor for my POSTs, not just the custom post type I’ve declared. Here’s the code I am using:
http://pastebin.com/ypTfLHDc
If I set it to “false”, the editor box shows up on POSTs. If I set it to true, the box is removed from POSTs. Any idea why this would be affecting posts and not limited to my custom post type? thanks.
@Bill, @konradk, I apologize, I will have a look at this issue today (it totally skipped my mind).
@Bill, @konradk, I can not reproduce. Here is what I’ve done: I have created a custom post type “event” and I have setup two meta boxes like so:
In my examples above,
$checkbox_mb
shows up without the editor and$simple_mb
shows up with the editor on both posts and pages.FYI: I am running WPAlchemy_MetaBox v1.4.5 and WP 3.1.2
Thanks Dimas. When I copy your code (and change ‘event’ to my custom post type) , I still get the problem. The editor box fails to display on both my custom post type and ‘post’.
Specifically, both editing screens have this CSS in the page:
#postdiv, #postdivrich { display:none; }
I will keep looking.
Dimas, just curious — when you defined your ‘event’ type, did you add support for the editor?
'supports' => array('title','author','thumbnail','editor'),
Dimas, one more tidbit.
In my testing, it’s only hidden on the “add new” post page.
/wp-admin/post-new.php
If I edit an existing post, it displays.
I successfully used this class in a wordpress 3 site. For some reason on a wordpress 3.1.2 site I get the following error:
Warning: parse_url() expects exactly 1 parameter, 2 given in /home/4/7/8/2292/2292/public_html/wp-content/themes/cousins/WPAlchemy/MetaBox.php on line 981
Here is the code in my functions.php file:
Any idea what is causing this and how to fix it?
@Bill, I’ve fixed the issue grab the latest stable version v1.4.6 (master).
@Melinda, I made a modification which should do the trick, please try v1.4.7 (dev) and post back if it works or not.
Do you have some example with Media Uploader
yes, using my MediaAccess class (in dev)
Hi Dimas,
Excellent stuff from you – thanks
I am having a problem where I cannot get metabox to work with the custom post type (News – in my case), no data is saved.
$custom_news_metabox = new WPAlchemy_MetaBox(array
(
‘id’ => ‘_custom_news_metabox’,
‘title’ => ‘News – external source’,
‘types’ => array(‘news’),
‘context’ => ‘normal’,
‘priority’ => ‘high’,
‘template’ => TEMPLATEPATH . ‘/custom/external_meta.php’,
));
but this work and I only want to have the field for News
$custom_news_metabox = new WPAlchemy_MetaBox(array
(
‘id’ => ‘_custom_news_metabox’,
‘title’ => ‘News external source’,
‘types’ => array(‘post’,’page’, ‘news’),
‘context’ => ‘normal’,
‘priority’ => ‘high’,
‘template’ => TEMPLATEPATH . ‘/custom/external_meta.php’,
));
Any suggestions?
I just tried v1.4.5 it works fine but using 1.4.6 causes the problem.
Thanks for the help
@pb, fixed in v1.4.8
Dimas, thanks — my problem is solved. 🙂
Hello Dimas. First: Thank you for this awesome class! It solves a lot.
I think that there’s a compatibility problem with More Fields (http://goo.gl/9zkN1) plugin.
If I have a field created with More fields (for other post type) with the same name of the one created with Metabox, Metabox saves in DB only the meta_key value and not the meta_value.
Did you noticed that?
Regards, Fracesco.
Hello Dimas, I have several custom field saved in the DB by plugins.
I switched to Metabox because it rocks, but in the post editor it does not show the old values (I use the same meta_key of course).
@Antonello, unfortunately my meta box class saves its data as a single serialized value (actually it has two types of save modes), i am betting that the other plugins do not do this.
I say “unfortunately” because I do realize that my class isn’t as WordPress friendly as it can be. I will take a care of this in a future version. Please let me know which plugins you are referring to, this will help me test and make sure people switching over from these plugins will have a pleasant experience.
Thank you for your reply Dimas.
I used More fields to save data in standard WP format (e.g. meta_key = “key1” and meta_value = “value1”). No array, just one key and one value for each field.
I configured Metabox to use WPALCHEMY_MODE_EXTRACT so it saves data in an identical manner as More field does (as I see in the DB). The problem is that Metabox cannot read data saved before, even if they were saved with the same identical key.
regards, antonello
Antonello, I was in a similar boat and got it to work.
Check your database, in the post meta table there will be a _slug_fields entry. The slug will be the slug you assigned to the meta box.
This option holds a serialized array of your various fieldnames and seems to be required. I created this for each post, and then my values showed up.
Let me know if this doesn’t make sense.
Thank you Bill! I will check it and report
Antonello
Hi Dimas,
Thanks for providing the fix…works great.
One question: if the meta data is stored as array how do you query using query_post (i.e. values inside array)
query_posts('meta_key=somekey&meta_value=samevalue')
Code tips please
Thanks
@pb, see the following article, also as I mentioned earlier, this is a shortcoming of the class that I will be fixing in a future release.
Hi Dimas,
Thanks for the great code, I’ve been using it a lot lately.
I was wondering if there is an option to include/exclude based on parent page ID? I’ve had a look around and didn’t see anything though might have missed it.
Thanks again,
Frances
Frances, there isn’t a direct option for
include/exclude_parent_post_id
but I can see how this would be useful as a direct option. Mean while you could do something like:Hi Dimas, thanks for the quick reply. I added some classes to the body in admin-header.php that output the page ID and post_parent, and then in then just used CSS to display only on those child pages.
Another question: Is it possible to use shortcodes in a metabox? I can output the shortcode string successfully as text, but unable to get it to resolve. I was originally basing this on:
get_post_meta($post->ID, 'foo', true);
Thanks again,
Frances
Hi Dimas, do you have an examples which use save_filter and save_action? thanks.
Dimas, please ignore my previous note about save_action.
But, I do have a question — is it possible to use WPAlchemy with a filed of type “file?” I would like to offer uploading of a file.
When I add the code and dump the $meta with a save_filter script, the $meta variable does not include anything about the file being uploaded.
thanks.
I am attempting to use WPAlchemy in a custom post type and all is going great so far except one thing. I can’t wrap my head around how to display my custom meta values in the admin post list. This is a custom post type in which I have custom columns outputting custom meta. From my functions file how would I call these values?
Here’s a snippet of how it was setup before I started using the class:
function xpsp_business_edit_columns($columns){
$columns = array(
"cb" => "",
"title" => "Business",
"email" => "E-Mail Address",
"business_type" => "Business Type",
);
return $columns;
}
function xpsp_business_custom_columns($column){
global $post;
switch ($column)
{
case "email":
$custom = get_post_custom();
echo $custom["xpsp_business_email"];
break;
case "business_type":
echo get_the_term_list($post->ID, 'business_type', '', ', ','');
break;
}
}
Your help is greatly appreciated. After this I can’t wait to play with the MediaAccess.php.
I answered my own question after some trial and error.
I was trying to use the class to call the data as per the section of the guide above that describes using values in your template. This didn’t work from the functions.php file, so I used a standard get_post_meta call to retrieve what I needed.
Here’s what I did:
case "thumbnail":
$src = get_post_meta($post->ID, '_xpsp_business', TRUE);
$src = $src['logo'];
if ($src == NULL) { echo "No logo uploaded."; } else { echo ""; }
break;
@Bill, you should be able to have access to the PHP
$_FILES
globalwith this you can manipulate the file as you need to.@Vince, glad you got everything working, please feel free to give me any feedback you may have which may enhance a users experience when using the helper class for the first time.
Dimas: I just had a thought on having the ability to show a metabox based on a specific post format (gallery, video, aside, etc). I was thinking this would work similar to the include_template include option. Is there an easy way to do this currently?
@luke – i believe the include code for that is:
‘types’ => array(‘portfolio’)
@kathy – I gave that a shot but I didn’t work. I believe that is just for “Post Types”. I’m trying to show if a particular “Post Format” is chosen. This would require the post to be saved/published to know what post format has been selected. I initially had the same thought as you though…
@luke- you’re right, i misread your question. no idea if alchemy supports that yet. i haven’t seen it come up in the comments before and i’ve been subscribed to this thread for a long time. guess we’ll have to wait on the man himself!
@kathy – I haven’t either. I may fork it on github and give it a wack… Something like
'format' => 'video'
might be an ideal solution@Frances did you make any progress with the shortcodes? I am working on that myself right now.
@Frances – btw- yesterday Dimas updated his dev branch at github to work w/ shortcodes! it’s awesome.
hi dimas- another q for you… i’d like to use the same custom-meta.php template on 2 different templates… the meta info will be the same, but in the templates the data will go to different places. I am wondering if could do something like
if( is template #1) { echo “this is for template #1; } else { echo “this is for template #2;}
this would help me w/ duplicating posts and using the same template part (just called in a different place)
@kathy, try one of the following:
Good observation/requirement, something to think about on my part.
@Luke, good feature request, shouln’t be to hard to add i believe.
thanks dimas, i’ll have to check it out. i found that $post->page_template also works in the backend
do text inputs strip quotes by default? can i get around this with a save filter?
@kathy
I got distracted with another task and now come back to shortcodes again with a different task. Shall look at the new dev branch.
@Dimas,
Thanks again!
something has happened where the tinyMCE text editors don’t save the html formatting anymore? I also noticed that text inputs aren’t saving quotes. epic bad timing.
Do try a previously tagged version and see if it works, let me know!
went back to 1.4.4… which is what I was using before and I am still stuck. Am using the code from Aaron’s comment on your multiple WYSIWYG editors post.
http://www.farinspace.com/multiple-wordpress-wysiwyg-visual-editors/#comment-body-14642
if i look at the editor via the HTML button, the p tags are there, but they aren’t getting saved.
This is great, I’ve got it up and running on a site i’m currently building. I’ve ran into a minor problem. When I try to order post by title it seems to break everything. I’m using a Thematic child theme. Here’s my loop: $loop = new WP_Query( array( ‘post_type’ => ‘rentals’, ‘availability’ => ‘available’, ‘posts_per_page’ => 10, ‘orderby’ => ‘title’ ) );
Works great if I get rid of ‘orderby’ => ‘title’.
Do you have a donate button? I’d like to contribute, but find myself having less time than money. I’d be happy to throw some loot your way for all the hard work. This is exactly what I need.
Rich
Dimas, is it possible to put a metabox with content = “side” but have it appear below the PUBLISH metabox? I can put it at the top, above the PUBLISH metabox (priority=high). But, if I set priority to “low”, the metabox loads below a taxonomy metabox that I also have. Just wondering if I can force the new metabox to load immediately below the PUBLISH metabox.
that should be “context=side”, not content. ie:
Dimas, is it possible to put a metabox with context = “side” but have it appear below the PUBLISH metabox? I can put it at the top, above the PUBLISH metabox (priority=high). But, if I set priority to “low”, the metabox loads below a taxonomy metabox that I also have. Just wondering if I can force the new metabox to load immediately below the PUBLISH metabox.
I’m using the wordpress plugin “Relevanssi” to improve the search on my site. it acutally works pretty good except it doesn’t look in the metabox I declared with alchemy… how do they are saved as in the wp structure?
the plugin enable me to search in custom post type, taxonomies and custom fields.
hi dimas, is there any way to filter the wp_kses on a per metabox basis? i’d like to use one for embed code (and iframe actually) and it gets stripped on save.
@kathy Have you tried using a textarea? I use that for embed codes and so far haven’t had any trouble. I believe the regular text input won’t work.
@kathy, at first glance you should be able to also use the
save_filter
and run the wp_kses function on the input before saving it.@luke – yes i’m using a textarea. tried to put in an iframe and no joy.
@dimas- thanks. i thought it was going through the kses somewhere along the way… as i thought that was the reason the iframe was getting stripped. i’ll check out save filter and report back.
I’m dreaming of a setup where a metabox is created for every term is a custom taxonomy. The inputs would be same in each box but would have a name that associate with the given taxonomy term. How feasible is this or is it even possible?
@Brett, totally feasible, you would probably have to write some setup code that uses WPAlchemy to create each of the meta boxes. The setup code would essentially loop through the taxonomies and creates the meta box.
**novice alert**
I’m trying to incorporate this into an existing plugin that I have forked and it currently has some data that it passes via an array. Is it possible to pass in that data to, say, a select box?
A quick question regarding have_fields_and_multi for repeating fields: is it possible to have a repeating field group within another? My situation is this:
A friend has a site for portfolios she creates. There’s a materials section, where I would first like a repeating field to create different material groups (i.e. Acrylics, Metals, etc.). Within each dynamic material group (i.e. Acylics) there would be the ability to create multiple options (i.e. Acrylic Red, Acrylic Blue, etc.)
Ultimately all this information gets plugged in as form options dynamically, hence the complexity of this.
This might be completely straight-forward but I thought I would check to make sure it’s not an issue. Thanks!
@Bobby, it depends, there isn’t a direct function to plug it into a select box, but of course you can loop over that data and simply create select options:
@Sean,
At the moment WPAlchemy repeating fields JS are a single level (no nesting). So off the bat nested repeating fields will not work.
But you are in luck, just today I tackled nested repeating fields on a different project, pretty f***ing tricky, I want to refine it a bit more (perhaps turn it into a jQuery plugin) but I am willing to share the code I have so far. It is still pretty complex, however.
HTML Setup
https://gist.github.com/994668
Javascript
https://gist.github.com/994658
I’ve only got it working for 2 levels but think it should work for n levels.
Thanks for providing the code!
I’m still wrapping my head around it to be honest. Is there anything else to be added for the HTML? I.e. any of the typical code you’ve setup for WPAlchemy?
@Sean, to be honest you will have to do some fiddling … for starters you will need to loop existing values and put them into the HTML. You can probably use some of the helper functions, but most of the HTML/Form will be custom so you might run into issues.
I recommend that you take a look at how WPAlchemy writes out the form values, you could simply mimic how it does it, see this section and the code blocks below it. Additionally you may also need to pull out the specific values from the
$meta
array which is available within the HTML “template” (do aprint_r($meta)
), use this to do your looping and construct your HTML.Please pardon my question as I am new to WP and PHP, but while I have found your Class helpful, I for the life of me cannot get it to pull anything from it. I have been able to set it up on the back end of WP (Create MetaBoxes on a specific page), but when I go to call anything on the front end I just get:
Fatal error: Call to a member function the_value() on a non-object…
I don’t understand what I am missing. I am calling the global at the start of the page template and calling the information through:
the_value(‘board_name’)?>
I am completely lost…
I have tried several different object calls, including:
get_the_name()
And have not been able to call anything. I consistently am getting Fatal errors over anything WPAlchemy related.
Need help ASAP.
I am at a complete loss. I have been fighting this all day, and I am either too green or looking in the wrong parts to get this to work.
I set up a Meta box with the following code in functions.php:
new WPAlchemy_MetaBox(array
(
‘id’ => ‘_about_mission’,
‘title’ => ‘Our Mission’,
‘template’ => TEMPLATEPATH . ‘/custom/about-mission.php’,
‘include_template’ => array(‘about.php’) // use an array for multiple items
// ‘include_template’ => ‘product.php,press.php’ // comma separated lists work too
));
Then, in the Meta box template file I put as follows:
Enter Statement
the_field(‘our_mission’); ?>
<textarea name="the_name(); ?>” rows=”3″>the_value(); ?>
I then proceed to try and call it:
have_fields(‘our_mission’))
{
echo ”;
$ingredients_metabox->the_value(‘our_mission’);
echo ”;
}
?>
Now, I just used a snipet of code after fighting with my own code for so long and I still couldn’t get it to pull anything through.
Help me, someone! Gah!
I just copy/pasted every single line verbatim from the documentation and still cannot pass any of the things define from MetaBox.php. NOTHING. I still continue to get a Fatal error. I absolutely do not understand.
Now I just copy pasted the whole contents from MetaBox.php in to my functions.php file and still nothing will pass from this. What is going on?!
Dimas – amazing stuff! Thanks so much.
I have run into a strange problem with post meta not being “attached” to posts after migrating from one server to another. All data is there in post_meta table and actually can be got via get_post_custom(), though not using:
get_post_meta(get_the_ID(), $meta_box_mb->get_the_id(), TRUE);
The values also don’t show up in the admin (as in on the pages they are attached to).
I tried a quick copy on my local server and the issue persists. Anything you have seen before?
Forgot to mention:
version 1.4.8
wp 3.1.3
sql export/import
@Lawrence, do me a favor and use something like gist.github.com or pastebin.com to post your code.
@Travis, I have run into a similar issue before (actually a user here has run into this issue), if you are doing a search and replace for certain values in the SQL dump then you may be replacing values in a serialized array (this is what WPALchemy currently uses), when PHP serializes things it is very particular about string lengths and such, if something is being replaced and the lengths are not being updated, this can cause problems.
Do tell me your procedure for export, then import so I can follow along and perhaps try to recreate it.
Lawrence, you aren’t supposed to copy MetaBox.php into your functions.php. that is nowhere in the instructions. i suggest you stop, take a break, and come back w/ fresh eyes. seriously i often solve things in the morning in 20 minutes that where taking me 5 hours when i was frustrated. the class does work so it is just a matter of you following the docu to properly implement it.
then- i can’t really tell if your code is posting properly. try using pastebin.com or putting your code between <pre><code></pre> tags.
this part of the instructions covers the setup of the metabox
http://www.farinspace.com/wpalchemy-metabox/#setup
in your above posted code you are defining the metabox, but not setting it equal to anything. you’ve got to give it a name! (which could just be your code not posting properly… idk) so that later you can call it back.
$ingredients_metabox = new WPAlchemy_MetaBox(array
(
‘id’ => ‘_about_mission’,
‘title’ => ‘Our Mission’,
‘template’ => TEMPLATEPATH . ‘/custom/about-mission.php’,
‘include_template’ => array(‘about.php’) // use an array for multiple items
// ‘include_template’ => ‘product.php,press.php’ // comma separated lists work too
));
then you call it in your template following these instructions:
http://www.farinspace.com/wpalchemy-metabox/#template
assuming you setup your metabox object to be called $custom_metabox, you’d add the following.
global $custom_metabox;
$custom_metabox->the_meta();
$custom_metabox->the_value(‘your meta field name’);
to your template. and that will echo out the value you’ve saved for ‘your meta field name’
dimas has included some sample code in the WP_Alchemy download. take a look at how he has set up his metaboxes.
@kathy, You ROCK!
Aha – that was it…
Situation arose as I was storing full urls in the post_meta, then finding/replacing xyz.dev with longername.com on migration. Just did a quick check with moving the install to zxy.dev and everything worked perfectly.
Guess I will just have to go back and redo some things so I am just storing ‘filename.jpg’ and deal with the rest of the URLs in the templates (which makes more sense too I suppose – laziness… ha).
Keep up the good work!
I apologize for seeming so frantic. I was butting heads with that all day, and as I said before, I am super green to PHP and WordPress.
That being said, thank you so much! Kathy, thank you so much for clarifying and breaking some things down for me, and Dimas, thank you for being open for help yourself.
In the end it was this line that was messing me up:
I wasn’t defining the metabox, like Kathy so graciously let me know. Thank you both so much for being very willing with your knowledge.
Alright, ran in to another snag that maybe I could get some feedback on. I have been able to pull from all of the meta boxes using this awesome WPAlchemy Class, but I have been having issues with a instance. I am trying to take the values from the given code to then fill an unordered list. Essentially filling up the with ‘s as there is data to be called upon.
I again apologize if my questions are terrible as I am new to PHP.
I set up a meta box with the following:
The following meta box:
Then, I reference the functions at the top of my HTML:
Following all of this, I attempt to fill my list:
Thanks in advance for any help/advice/tips.
My bad, I didn’t know it would filter out the unordered list (ul) elements out of the last code snippet. I am trying to fill up an unordered list with list items (li) while pulling in the values.
The code at the bottom should be wrapped in an unordered list (ul)(/ul).
I am not super sold on this method, I am open to other ways of achieving the result. I am sure that my way is far from ideal.
Thanks again.
lawrence, you aren’t setting up a loop. look again at the sample in: http://www.farinspace.com/wpalchemy-metabox/#template
it isn’t enough to say have_fields()… have_fields() means nothing by itself, you must use it in setting up a while loop. i also like to first test to see if it has any values in it at all using have_value() …. which isn’t in the docu, but Dimas has answered for me previously in the comments.
if ($members_metabox->have_value('board_members')):
echo '';
while($members_metabox->have_fields('board_members')) :
echo '' . $members_metabox->get_the_value('board_name') . '';
endwhile;
echo '';
endif;
Kathy, thanks for the speedy response! I went with your example, and I couldn’t get it to work. I then swapped out the second ‘board_members’ with ‘board_name’ and also changed the Mode back to default in my functions.php file and tried passing anything with several different code combinations with no result.
You had characters missing from several quote marks, so I will paste how I set up your example loop:
From this I am not getting anything to show in the DOM. Note: I took out the greater-than and less-than signs on the unordered and list elements to better show you what I am doing.
I also attempted this way just to make sure I wasn’t misreading the code you presented. It too gave the same result.
@lawrence – hmmm… that should have worked, b/c it is a stripped down version of working code that i am using. though apparently some markup is getting stripped even inside the code tags, weird.
“also changed the Mode back to default in my functions.php file” i haven’t come across a need to use extract mode yet. for what it appears you are doing, i’d leave that section alone.
i actually tested my code this AM (the hacked down version) and i get an unordered list of names. for this paste i just changed the names of the metabox and the fields/groups. check this paste and see if that helps.
http://pastebin.com/hnMAWz7H
you can also try a
print_r($members_metabox);
right after
$members_metabox->the_meta();
as that might tell you what is IN your metabox object. the values are saving correctly in the backend right?
Kathy rocks! 🙂
Kathy does rock! 🙂
I tried this solution before and couldn’t get anything to work. Nothing is still showing up. However, I never tried using the
code. I did this, and this is what was spit out:
It seems that the function is in fact able to pull from the meta boxes I created. I am just having a hard time understanding why it’s having difficulty fully pulling through.
Is the fact that there are two values are am trying to pull from one multiple field messing me up? It seems like I would need a way to cycle through the possible values?
thanks guys. 😉
looking at your print_r… where we’re expecting to see the group name (associated with have_fields_and_multi) to be ‘board_members’, i’m seeing ‘docs’ which makes me think you copied in Dimas’ have_fields_and_multi example and forgot to change the loop name in your metabox template.
[meta] => Array ( [docs] =>
Array ( [0] => Array ( [board_name] => Kay Stoltz [board_position] => President )
[1] => Array ( [board_name] => Eric Johnson [board_position] => Vice President )
....truncated....
)
if you change it you’ll need to re-enter the date you’ve already added. or as a test you could change the output of my pastebin to have_value(‘docs’) and have_fields(‘docs’) …
Thanks, Kathy!
I noticed that as well, and I checked and I believe I clearly made the correct change to the loop name:
Could there possibly be something overriding this?
I changed the loop name on my template file to ‘docs’, without changing the following in my functions.php file:
And as you noted, it is pulling it fine. I just don’t understand why it’s still pulling for ‘docs’ and not ‘board_members’. Is there another place I needed to change the ‘docs’ reference in the functions.php or other code that Dimas offered us?
Excuse me, I didn’t mean functions.php file, I meant from my ‘template’ file that houses the meta box. Sorry for the confusion.
the loop name must be the same in both your metabox template (in this case custom/about-members.php) AND in your output template… whereever you are calling the data .
as i said in my last post, right now it appears to me that in your metabox template you are calling the loop ‘docs’ while in your output you are calling it ‘board_members’… which isn’t printing anything b/c nothing is stored in the meta for that.
change the value in your metabox template. then resave your post.
Kathy, thanks again! You are so helpful.
So I went in and did find that I hadn’t updated the about-members.php file and did so. I then updated the post, and I still am finding that it’s calling it ‘docs’. Do I need to deleted the page and re-create it for it to update itself?
Kathy,
I didn’t bother to check the meta box. It was cleared and now I am able to enter in fields and have it populate.
Thank you so much for your help! I will attempt to not bug you as much in the future. 🙂
On another note, I was wondering if you could possibly point me in a direction to learn more on PHP? Most of what I have learned I was self taught through W3Schools.
Thanks again!
Man, I thought I was out of the woods, but now I find that on the page with the meta box (about.php) I do not have any ability to add names/positions anymore. On top of that, I can’t ‘remove all’ from the meta box, nor can I use any other edit functions on that page.
Any suggestions to what is bringing this about now?
We really need a WP Alchemy forum, these comments are getting difficult to follow. Any update Dimas? I recommend bbPress.
@lawrence – can’t really point you to a good place for learning PHP: though i end up at http://php.net and http://codex.wordpress.org all the time. i’m totally self-taught too- lots of time spent meticulously iterating and googling when things break. 97% of the time someone has already gone through the same problem, so get good with asking google. oh and lots of generous help from people who are more knowledgeable- which is important when you are still at a stage where you can’t form good search queries. don’t forget to pay it forward! it’s good karma.
@Vince – agreed.
Hi, this looks to be VERY useful for a project I am working on. I am interested in using this only for specific page templates, and after reading through, this sounds like it will work. On a only slightly related note, can someone suggest where I would start if I wanted to add a page template through a plugin?
Vote Dimas for mayor of WordPress !!! 🙂
Seriously, WPAlchemy is really making up for some lacking features of wordpress and the new media upload integration is tasty.
Good job sir.
Hi everybody.
I’m building a quite complex custom post type structure and I would need some help regarding my metaboxes.
What I want to do:
1. Thank’s to the
have_fields_and_multi()
function, the user enters data in simple textinput
fields (with a “Add new” button)2. The values from the previous text inputs should be used to build a
select
dropdown in another metabox.To make it simple, here is a mockup (also attached to this post): http://idzr.org/0c95
I have the first part working, it’s easy. But I can’t figure out how to make the second part to work. If I use a
while($mb->have_fields_and_multi('aaa'))
in anotherwhile($mb->have_fields_and_multi('bbb'))
the page is infinite (the loop doesn’t end). If I useforeach
I have other problems.Do you have an idea about how I can achieve this ? Thanks!
@Sinklar,
have_fields_and_multi()
is basically a single level iterator, so if you are trying to do a nested loop it will not work.What I recommend you do is use some javascript (jQuery) to build your select boxes. This will benefit you in two ways. 1) you will not need to do a php loop through any values 2) the user will not have to save the page first before having access to the values. The event you should trigger off of is: each time a field is created, recreate the select boxes.
With jQuery you can do the following:
Thanks! I finally got it working with
foreach
before I saw your answer. The user has to save it before the items do appear in theselect
but it doesn’t matter…Now the million dollars question : in my theme template, is it possible to retrieve the entries sorted by the value of the
select
?My metaboxes : http://cl.ly/2o2u0I2u2j3p1p3V2O1J
Hi Dimas, is there a way to limit the metabox by taxonomy in the same way as by tag or category?
@kathy, nothing built-in yet (I’ll try to add this one soon), in the meanwhile you can use the output_filter and do your own taxonomy check.
thanks dimas! filling in the $taxonomy and $terms arguments this works just fine for now:
function my_output_filter($post_id) {
if(is_object_in_term( $post_id, $taxonomy, $terms)) {
return TRUE;
} else {
return FALSE;
}
}
No help for me ? 😉
@Sinklar, sorry about that, I don’t quite understand how you want them sorted, can you explain?
I’ll take a guess here, I assume once the user uses the select box to select and apartment type (1br or 2br) you want to sort the list of available apartments by 1br and then 2br and so forth?
The array for this should be something like:
To do a sort on type you will have to use array_multisort.
hi again dimas, did you know that if you put quotes in a text input they get stripped out (along w/ the text they were surrounding)? is this intentional? is it something that i should just work around with the save filter?
Kathy, I was unaware, I’ve updated the “dev” version with the fix, please give it a go, do a few tests to make sure it works well in the meta box content template and in the theme template and let me know. I will update “production” with the update.
Does include_category_id also work with custom taxonomies?
@Jonathan, yes it should.
Dimas, I’ve been playing around with the shortcodes and it seems to working with one exception. When using a shortcode with two parts, a beginning and an end, nothing is returned.
For example, when using WordPress’s video embed shortcode:
[embed width="550" height="400"]http://vimeo.com/24840381[/embed]
, nothing is returned in the web page, but the option value still shows in the admin metabox field.When using a “self contained” shortcode, for example,
[shortcode width="550"]
, things work as expected. I hope that makes some sense…Is there a way to process or output a “two part” shortcode? I’ve tried both a text input and a textarea to no avail.
Quick question that I’m hoping has a simple answer.
When you’re displaying the meta data in your templates, is there a way to code it so that html included within the get_the_post-meta tag is only shown if that meta field as been filled out? Sorry if I’m not wording this right, everything I know about php I learned from wordpress so my knowledge is kind of haphazard. For example, I have this code to display the ‘Client’ field:
php $meta = get_post_meta(get_the_ID(), $custom_metabox->get_the_id(), TRUE);
echo "Client:";
echo $meta['client'];
Right now, the Client: heading is still displayed even if that field wasn’t filled out in the post which, obviously, is not good. Is there something I can do so that if there’s no data in the ‘client’ filed, nothing in that bit of php will be displayed? I’m guess I’d need some sort of if/else setup but I’m not sure exactly how to do it.
@Dimas – I include_category_id an initial try with no success. What I am going for is that a metabox shows up when a particular term in a custom taxonomy is selected. I realize that, unless I use a JS solution, it wouldn’t do it immediately. My test is a post type that already has the term selected and I am expecting the metabox to show up when editing that term. Am I on the right track?
@Luke, the embed shortcode is actually a little weird, see this and this. I’ve added support in the latest dev (1.4.11) version of wpalchemy.
@Jonathan, you are on the right track … I’ll take a look at include category/taxonomy, in the mean while use the ‘output_filter’ like so (a few comments back @kathy was doing something similar) …
@Nicole, you can do it a couple different ways:
if you are within a loop or have a global
$post
var you can doThanks, Dimas! Shortcodes are a bit strange in how some of them seem function. I’m basically trying to get a video shortcode to work (one that supports JW Player). I tried JW Player for WordPress Plugin shortcode but to no avail and now trying Pro Player shortcode without any luck. The JW Player in “self contained” and the Pro Player is “two part”.
Any ideas on what I’m missing? A global call? Not a big deal, but would be nice to figure out.
@Dimas, thank you for the suggestion to use the output filter! I’ll give it a try.
Hi Dimas. Excellent work. This is fantastic. I have a question. Regarding the have_fields_and_multi function. Is it possible to re-order the field sets easily in the write window? Magic Fields has the ability to drag and drop field sets to a new order with repeating, or duplicated field sets. For example, if the user were entering ‘players’ as in the roster of a team. Each player is entered in a duplicated field set as meta data attached to the custom post type, ‘team’. Then, let’s say they wanted to change the order in which they entered the players, is there an easy way to do this? Maybe have a link for ‘+’ and one for ‘-‘ to move a field set up or down in the order?
@ethan – you can drag and drop w/ alchemy following dimas’ directions here:
http://www.farinspace.com/sorting-wordpress-meta-box-fields/
@kathy – many thanks for pointing me to the tutorial
Hi Dimas,
Thanks for sharing with use, it helped a lot….
@Kathy Thanks for comment support 😉
@Vince I agree!
Dimas when can we expect a bbPress to support the development?
@Mike, started working on a bbPress install last night, need to play with it a bit…
@Dimas, that is great news, if you need any help let use know :-p
Hello – can you please help me to understand what I’m doing incorrectly?
I am using this feature to show a list of events:
http://riggswerks.com/clients/auriamicro (lower right corner).
But all the events are sharing meta data. This is the way I’ve structured my php/html:
https://gist.github.com/1038742
@Christian, you might need to do the following (explicitly requesting the meta data, per post ID):
Hi Dimas,
I’ve been using WPAlchemy for quite some projects now, it’s of great help so first of all: thanks a lot, you rock!
What i’ve been wondering (it’s nitpicking though) is why you’re defining the _TEMPLATEURL constant instead of using get_bloginfo(‘template_url’). Not that it really matters, just thought you must have had a reason for it and I didn’t quite figure it out myself yet.
Keep up the good work!
Danny
Ah well, please disregard my previous comment. * slap myself *. It’s because of including the metabox templates and http wrappers. I feel kinda stupid now.. 😉
I just wanted to say a massive thank you for this class. WPAlchemy is really awesome!
I’ve tried pretty much every custom meta box plugin out there and while they are all very good at the basics, they all suffer from one problem or another.
With WPAlchemy, although it’s more work to setup, I get complete control over every aspect of the meta box fields. It’s just so much more flexible. And the repeating fields and sortable option is nothing short of fantastic.
Thank you, thank you for your great work, I really appreciate all the effort you’ve put into this. 🙂
@Danny, I will have to update the example files in the download, but I actually now prefer to use the following:
Some of my other favorites in my cheat sheet are:
@Matt, thank you for your comment. Your feelings are well understood. I much prefer the flexibility when developing.
I hate the feeling of thinking I found a great tool/plugin, and using it, only to then realize that I need a change to an area which the tool/plugin does not easily allow and/or now I having to go into the tool/plugin to make modifications.
Any feedback you have in regards to making it easier, more elegant, please let me know.
For what it’s worth, according to WordPress.org, it’s better to use:
get_template_directory_uri()
instead of usingget_bloginfo('template_directory')
andget_stylesheet_directory_uri()
instead of usingget_bloginfo('stylesheet_directory')
.Carry on 🙂
One thing that I haven’t worked out how to do yet is show a thumbnail of the image that was selected from the Media Uploader. It would be great to show the thumbnail next to the meta box field that shows the path.
I wonder if there is some example code for that?
@Matt – You could try something like this:
This might come across better…?
if( $mb->get_the_value( 'hero_background_image' ) ) :
echo 'get_the_value() ) . '" />'
endif;
@Luke: Thanks for the tip. Your code seem to get mangled, but I got the sense of it. I see this will only work when you update the post, so eventually I’ll look for dynamic jQuery solution, but this works for now:
http://twitpic.com/5f9qmq
Many thanks 🙂
How would I create a WYSIWYG TinyMCE text area in my meta-box template?
@Matt, I don’t have a full definitive answer for you but you should check out How to Use Multiple WordPress WYSIWYG Visual Editors and be sure to skim the comments as there are several nuggets in there.
Cool, that’s looks perfect! Many thanks for the pointer. Do you have a PayPal donation button somewhere, I’d like to make a donation 🙂
Possibly a dumb question… is it possible to use WPAlchemy when creating a theme options page?
@Bill, I am always learning more and more about WordPress each project I’m involved in. I developed WPAlchemy primarily to aid with post/page/custom post types meta box creation … so it is really untested in theme options pages. Just yesterday I learned about the
do_meta_boxes()
function which has corrected a couple assumptions I had about meta boxes.Hey,
How would i echo the value of a custom field using a function outside the loop? I have tried this code in my functions.php file but doesn’t seem to do anything:
Any suggestions?
Thanks
@Matt
Maybe I’m an idiot but I can’t figure out how to display the data that was entered into the metabox fields in my theme….I know there’s the “Using The Meta Box Values In Your Template” section, but I’m not quite sure where to place that/how to integrate it.
Anyhow, thanks!
@Ryan, at its basic you put this in your theme template (page.php, single.php, somewhere in The Loop).
It seems like non-ascii characters are not saved correctly while using WPAlchemy (I also verified it in mysql). Any suggestion on how to make it work?
@Dimas
Legend! Thanks man 🙂
Great class! Thanks a lot can I donate some money to say thank you?! Awesome … 🙂
Hi Dimas.
WPAlchemy is great! I’m only at the surface but what I see is awesome. Thank you.
I also ask if you can point me in the right direction. I use a custom meta box to write some details about movies, you can see an example here http://j.mp/jrZ5Oi it’s called “Ficha Tecnica”.
The goal is make a search with the names, but there are no results. If a name is in the post content, then I got the post, but how can I look into custom meta fields?
Thanks again.
Note that the constant TEMPLATEPATH you’re using in functions.php file doesn’t work with child themes. However, STYLESHEETPATH works.
@Javier, take a look at the Search Everything plugin.
Additionally you may need to use WPAlchemy in WPALCHEMY_MODE_EXTRACT mode. This is because by default WPAlchemy will store everything as a single entry in wp_postmeta as a serialized array … and this may trip up the search. Also if you use repeating fields, array serialization is unavoidable … well not quite, if you really needed to make only a few fields searchable, you could use the “save_filter” and custom save those fields the standard way in the wp_postmeta table.
@Ma’moun, good catch, I am trying to move away from using TEMPLATEPATH altogether in favor of this and this.
Thanks Dimas!
WPALCHEMY_MODE_EXTRACT was the key!
What is the best way I can enqueue script/style in the pages that a specific meta-box is being loaded in? I am trying to do something like this:
$custom_school_mb = new WPAlchemy_MetaBox(array(
...
'head_action' => 'meta_tabs',
...
));
function meta_tabs() {
wp_enqueue_style( 'fkp-metabox-tabs', _TEMPLATEURL . '/css/metabox-tabs.css' );
wp_enqueue_script( 'fkp-metabox-tabs', _TEMPLATEURL . '/js/metabox-tabs.js', array( 'jquery' ) );
}
but it doesn’t work…
@ma’moun – it’s init_action not head_action for enqueing stuff
@kathy
Oh, thanks. That did it!
dimas,
i’m still not sure i’m enacting the save_filters right. basically i want it to ensure that if the user has selected ‘featured’ in the ‘featured_tax’ radio group, that the ‘excluded_tax’ radio group will be set to null. i can do it w/ jquery, but i guess i am always up for overkill… and just b/c i’d finally like to know how to use this correctly.
function taxonomy_save_filter($meta, $post_id){
if($meta['featured_tax']=='featured'){
$meta['excluded_tax']=='';
}
return $meta;
}
@kathy, in your situation with two radio groups, I myself would probably opt to use jquery as it would be more intuitive for the user.
However, it appears that you are using the filter correctly, you should be able to set it to blank
''
ornull
. In the latest version 1.4.12 … the user returned array now gets cleaned up properly (in case it was giving you some troubles).Hi 🙂
I’ve setup a checkbox that I would like to use with a conditional. I’ve read through the documentation above and haven’t found what I’m looking for.
Could anyone tell me how I would check if the checkbox is checked with an if statement? Is this possible?
@Duane, when you download there are some examples included, please have a look.
Hi, I’ve been trying to learn how to create my own meta boxes for a week now, and it seems like all the tuts i’ve tried don’t work with my thesis theme. I’m wondering if i’m using thesis should I put the functions.php code in my custom_functions.php file or not? I’m not to experience with php but I really want to get this down.
@Max, yes you should put it in your
custom_functions.php
file.@Max, if you are having problems, post your code to https://gist.github.com and I/we will help you out…
Any ideas how to pull data into an rss feed?
Hi,
Thank you for this very usefull script.
For me i used radio boxes as meta boxes as :
have_fields_and_multi(‘docs’)): ?>
the_group_open(); ?>
the_field(‘access’); ?>
Premium ?:
<input type="radio" name="the_name(); ?>” value=”premium”is_value(‘premium’)?’ checked=”checked”‘:”; ?>/> Oui
<input type="radio" name="the_name(); ?>” value=”nonpremium”is_value(‘nonpremium’)?’ checked=”checked”‘:”; ?>/> Non
the_group_close(); ?>
The question is how to display this on frontpage template ?
Thanks
@Shelomo, check out WordPress’ feed hooks, you would then just look up the extra meta data and put them into the feed however you want.
Hello i upload a comment here, but i cannot see where is it, i re-upload it and sorry for the admin.
First of all, thanks for this magnific “plugin”, i use it but need some advice.
I want to use radio box as coded below inside meta.php:
have_fields_and_multi('docs')): ?>
the_group_open(); ?>
the_field('access'); ?>
Premium ?:
<input type="radio" name="the_name(); ?>" value="premium"is_value('premium')?' checked="checked"':''; ?>/> Oui
<input type="radio" name="the_name(); ?>" value="nonpremium"is_value('nonpremium')?' checked="checked"':''; ?>/> Non
the_group_close(); ?>
The question is : how to display the result on template theme?
Thanks all!
@ikalangita, I’ll be glad to help you, can you first repost your code using https://gist.github.com
Code: https://github.com/urbangeekz/WPAlchemy
I really think there’s something broken in the code, because it’s not working. I tried with the directions given, and I also tried adding the functions.php code to my base thesis function.php file and keep everything in tact so there’s no need to change of any of the code and it doesn’t work.
Let me know if you see something i’m not catching…
@Max, indeed there is something wrong with the example … in the
simple-spec.php
file replaceget_stylesheet_directory_uri()
withSTYLESHEETPATH
.I will correct/update the examples I have on github.
Okay, sweet! just so you know I went ahead and edited the rest of the:
full-spec.php
checkbox-spec.php
radio-spec.php
select-spec.php
the same way that you mentioned. Now I think I’ll be able to follow along with the documentation 🙂 Thanks!
Thanks Dimas. I did take a look at the examples. I realized I wasn’t clear enough though. The examples are for setting metaboxes up. I’m trying to figure out how to use the checkbox value to display content in a template conditionally. For example…
You tick a checkbox if you want to hide a certain element in a template. I need to know how to use the checkbox meta with a conditional inside a template. (if checkbox is checked display this, otherwise hide it).
I’m sorry if there is indeed an example in the download, but I can’t seem to find one.
WPAlchemy is awesome btw 🙂
Hey Dimas,
I just want to make sure everything that I’ve done so far is looking right.
https://github.com/urbangeekz/WPAlchemy
I’m only using:
include_once 'metaboxes/setup.php';
include_once 'metaboxes/simple-spec.php';
because that seems like all I really need at this point.
I’ve edited:
simple-spec.php
simple-meta.php
let me know if everything seems good so far. If I wanted to call “artist_name” field in that post to display, how would I go about doing so?
I’m starting to actually love how simple this is 🙂
@Dimas, I’m not sure if I’m doing something wrong or if this is a bug, but selects and radios (all I’ve tested) don’t hold their values inside a “have_fields_and_multi” group.
If I wanted to include the meta box for only one category “music” and I wanted the metabox to show up once I clicked the “music” category how would I get that working?
When I add:
'include_category' => 'music'
The metabox doesn’t show up until I save the post as draft and then it appears, I want it to appear the minute I declare I’m posting this in the “music” category. Thoughts?
@Max Take a look at: http://www.farinspace.com/show-hide-meta-box-by-category/
@Ma’moun thanks, but i’m not sure where am I adding the javascript to?
@Ma’moun that javascript only seems to work for after the post has either been saved as draft with the category is selected or published.
I’m looking for something for instance that:
– I click “add new post”
– I check the proper category “music”
and it automatically opens the metabox, the javascript seems to only work for after the post has been saved.
@Max Getting the meta-box after saving/updating the post is the default behavior that you’ll get without any modifications. What the JS mentioned there does is exactly what you are looking for, which is to dynamically show/hide the meta-box without saving/updating.
There are many ways to add your custom JS, but the most clean and elegant in my opinion is packaging it as a file and then using WP’s wp_enqueue_script() function:
function my_custom_meta_init() {
wp_enqueue_script( 'KEY_NAME_FOR_YOUR_SCRIPT', get_stylesheet_directory_uri() . '/PATH/TO/YOUR/JS(UNDER YOUR ACTIVE THEME DIRECTORY)', array( 'jquery'' ) );
}
and finally add this as init action for your meta-box definition:
'init_action' => 'my_custom_meta_init'
This way you’ll get the JS script loaded just in the pages that have your custom meta-box.
by default wordpress does not show and hide the metabox without saving.
I’m not following… I applied the instructions on the post you showed me and it works after the post has either been saved, save as draft, or published with the category selected. That’s the only time it works.
Now, if I go create “add new post” and without saving anything, click the category, nothing happens. Even in the example video he’s clicking and unclicking a already saved post, which leads me to think it doesn’t work unless the post has been saved.
Could you explain your method of getting it to work more through clearly, i’m not understanding. Maybe provide java code not including category ID area
[4,3]
.I recommend re-watching the video then. In 1:01 you will see how that works even with new unsaved posts.
I just fixed it 🙂 For some reason it wasn’t working but now, it seems to work. I’m still interested in keeping it clean, so I would add this:
function my_custom_meta_init() {
wp_enqueue_script( 'KEY_NAME_FOR_YOUR_SCRIPT', get_stylesheet_directory_uri() . '/PATH/TO/YOUR/JS(UNDER YOUR ACTIVE THEME DIRECTORY)', array( 'jquery'' ) );
}
to what file, to the same one I have my definitions?
@Dimas I think a forum would make our life easier. Maybe bbPress is becoming good enough to start using it on a productive site?
@Max Glad you got it working 🙂 And yes, I think that the definition file is a good choice for the function.
Forums coming … also with the latest release of WP3.2 folks please let me know how things are working. I will be doing some tests in the next few days.
If i wanted to programmicly add metam What would be the best way as just using add_post_meta and WPALCHEMY_MODE_EXTRACT doesnt currently work as wpalchemy adds a special field still.
@Dimas I have a problem with Unicode text. When I enter Arabic text in a field and save the post, it doesn’t get encoded properly although it’s being saved correctly in the database (tried to check the row directly using PHPMyAdmin).
By the way, although I didn’t test that before upgrading to 3.2, I am still not saying that it’s an issue with 3.2.
Hi Dimas,
I’ve included all the relevant directories to my install of WordPress, added the include_once syntax to my function.php so I can test out simple-meta.php & simple-spec.php but when I try and login to my WordPress Admin UI I get this Output instead of the login form.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras orci lorem, bibendum in pharetra ac, luctus ut mauris.
Title
Fatal error: Call to a member function the_field() on a non-object in /var/www/teamtactics/wp-content/themes/tt/metaboxes/simple-meta.php on line 8
Any idea what I have done wrong here? Any feedback greatly appreciated. Thanks in-advance! Cheers, Sahus
Hi Dimas. So far no issues that seem WP3.2 specific. just issues of my own creating. 🙂 but also, this one i’ve discovered when trying to make my metabox UI look more badass.
if i put a span inside the dodelete link, the delete link stops working.
<a href="#" class="button dodelete" title="">Remove
also, since updating from version 1.4.9 to 1.4.12 my attempt to “alchify” some dropdowns with all the categories, posts, pages, etc gets messed up.
this was the function i was using:
http://pastebin.com/U7PMMu0p
i was trying to pass the $mb object to my function, which i don’t even know if that is proper code, but it seemed to be working.
now i get this error:
Warning: htmlentities() expects parameter 1 to be string, array given in D:\Users\helga\xampp\htdocs\single\wp-content\themes\kd-alyeska-thematic\admin\WPAlchemy\MetaBox.php on line 1671
@Sahus Pilwal I pet you tried to call the function directly without specifying the class, no? (e.g. the_field() instead of $metabox->the_field())
Thank you for that class. Especially the the thing with the multiple visual editors. I was looking for that so long.
@Dimas Could you please take a look at my issue when you have some free time (#comment-16908)? I know I am becoming annoying but I have to complete my project.. I successfully could solve every issue I had excluding this, since I don’t have any experience with encoding stuff. I would appreciate your time.
@Ma’moun, utf-8 support added to v1.4.13
ask and ye shall receive. dimas, have we mentioned that you’re awesome? 🙂 will this also fix the saving of quotes and apostrophes in text inputs?
@kathy, this was fixed in v1.4.10 however the issue you have is different, i’ve applied a fix see v1.4.14.
very cool that quotes and things work. shows how close i was paying attention. but my issue w/ htmlentities is still there. i don’t know what htmlentities does yet though and am too tired to investigate further tonight.
Agree with kathy, you’re really awesome 😀 Thanks!
I am trying to hide a meta box if a post for a custom post type does not have a certain value for a taxonomy term.
I can use an if/then statement in the template to only display the form if the post has the desired value for the tax term. But, if the post does not have the desired tax term, the meta box itself will still display even when the if/then does not display the form. So, I have an empty box in some cases which is confusing to the people using the site to enter the custom content.
I tried using an if/then statement to only create the metabox instance if the post has the appropriate term value. However, I am unable to get the term value from wp_get_object_terms unless the post object exists. wp_get_object_terms seems to get the term value correctly in the context of the template but not in the context of the ‘spec’ .php file, which defines the instance.
I also tried using an action to call a custom function that calls remove_meta_box function. But this would not remove the metabox regardless of whether I have a condition in the function or not.
the following would not remove the meta box at all.
function remove_post_custom_fields() {
remove_meta_box( ‘id_property_from_object’ , ‘my-post-type’ , ‘normal’ );
}
add_action( ‘admin_menu’ , ‘remove_post_custom_fields’ );
any suggestions?
@Hayden, see this comment.
Question: If we want to include wpalchemy to be bundled within a theme. How would this be done.
Hi Dimas / Guys,
Finally got WPAlchemy working in my theme!!! Woohoo 😉
Now a few questions if I may. Not sure if they have already been answered. Is it possible to parse in shortcodes into meta boxes which I can retrieve / echo out the values so WordPress can output the shortcode functionality? Any thoughts greatly appreciated… Cheers Sas
@Sahus – i asked about this a while back and since then Dimas has updated alchemy so that you can enter shortcodes in textareas and when you echo out the textarea’s value the shortcode will be parsed correctly
I needed a way to have a default radio button checked and couldn’t find it as part of your class or the comments. If you’ve got this built in, please ignore and enlighten me. Here’s how I implemented my code:
<p>
<strong>Featured Event:</strong>
<br />
<?php
$mb->the_field('event_feature');
$the_value = $mb->get_the_value();
$vals = array('yes','no');
$default_checked = 'no';
foreach ($vals as $val):
?>
<input type="radio" name="<?php $mb->the_name(); ?>" value="<?php echo $val; ?>"<?php if (!empty($the_value)) { $mb->the_radio_state($val);} elseif ($val == $default_checked) { echo ' checked="checked"';} ?>/> <?php echo $val; ?>
<?php endforeach; ?>
</p>
You can have as many radio buttons as you want and any labels/values. Just change the $vals array.
@steve – agree that a ‘default’ would be a good option.
@dimas – i found this very cool tutorial on how to add fields to the quick edit menu: http://shibashake.com/wordpress-theme/expand-the-wordpress-quick-edit-menu/
i have implemented a column that displays some data from one of my metaboxes. the trouble is that when i update the meta from the quick edit screen (the new value shows in my DB) but when i edit my post the alchemy get_the_value() and get_the_select_states() don’t work any more.
is there some secret ninja way i can update the $custom_metabox object when i update_post_meta or delete_post_meta somewhere else?
this particular metabox is in extract_mode and so should only be getting 1 value (for a set of radio buttons)
I’ve done this before by building metaboxes from scratch and with the plugin “Custom Field Template” and haven’t had an issue but I’m trying to create a dropdown inside a wpalchemy metabox of a custom post type called “artists” for a record label. The dropdown works in most cases as it saves the selection upon update but if there are any additional custom meta boxes after the one with the custom query the settings do not save.
I’m looking to find out the best way to do a custom query within a wpalchemy meta box without affecting other meta boxes. I’m currently using get_posts(); Here is the basics of what is going on in my query:
$posts = get_posts('post_type=artist&numberposts=-1&order=ASC&orderby=title');
foreach($posts as $post) :
echo the post name / id using wpalchemy
endforeach;
should I be doing a different query type or what?
Re my previous comment: Classic case of talking it through then figuring it out 5 minutes later.
I had to add this before my query:
$old_post = $post;
do magic stuff
then after the query did its thing:
$post = $old_post;
to get it all back on track again
the_select_state method does not seem to be returning ‘selected’ if the string contains a comma.
eg.
<option value="Chef's Choice"the_select_state("Chef's Choice"); ?>>Chef's Choice
The meta value saves correctly but the select menu in the metabox does not show the selected state.
I am using WPML plugin and would like to get some fields, like media fields, in the templates from the original language page and not the current, in case I am in a translation page. Unfortunately I cannot use the class get functions with post other than the one currently in the loop.. but I could get things working by using WP’s get_post_meta() function. However, my problem now with have_fields() function, that I need to get multiple fields group.
I’ve tried to temporarily change the query object for the class function, but that doesn’t work:
// get the original page id, in case we are in a translation page
$original_id = function_exists('icl_object_id') ? icl_object_id($post->ID, 'page', true, 'en') : $post->ID;
..
if(defined('ICL_LANGUAGE_CODE') && ICL_LANGUAGE_CODE != 'en') :
global $post;
$post_backup = $post;
$post = get_post($original_id);
endif;
while($agro_page_mb->have_fields('agro-stats')) :
...
endwhile;
if(defined('ICL_LANGUAGE_CODE') && ICL_LANGUAGE_CODE != 'en') :
$post = $post_backup;
endif;
Any thoughts…?
PS I think that a simple change to make get_the_field() and have_fields() taking an argument for the post id would just do it. It can be so useful for some cases like mine. Although I think I can change that my-self, that would make the upgrading harder for me.
@Hayden, I’ll look into it.
@Ma’moun, try:
@Dimas
It returns an empty string from the translation page:
string(0) ""
From the original language file:
array(2) { [0]=> string(5) "Array" [1]=> string(5) "Array" }
No, wait.. this actually works! Thanks man.
Well. Now I’m trying to build a dropdown of a taxonomy terms, so the user can link one of them to the post:
http://pastebin.com/KHS57bnB
The drop-down works as expected, showing all of my terms. However, something strange happens with the TinyMCE everytime I enable this metabox, which can be seen here: http://tardis1.tinygrab.com/awL8
Any clue??
Thanks!
I get an htmlentities error when trying to use multiple checkboxes. Anybody else had this? Even the demo ones don’t seem to work… they display fine, but when I check a few and update the post, the selected ones give me
htmlentities() expects parameter 1 to be string, array given in [……]/wp-content/wpalchemy/MetaBox.php on line 1671
@Gab, forgot to push the latest version, see v1.4.14, should take care of the issue.
Shameless plug: Not exactly WPAlchemy related, but if you’ve thought about supporting/donating, checkout Sidekick WordPress Plugin (Your gift when pledging your support)
I’m working with WordPress 3.2.1 and I am having some issues with this.
Now, It is possible that I am messing this up, I tried adding the info from the functions.php into my themes functions file and added the folder metaboxes into my theme folder as well. When I try to do anything in the backend, the page doesn’t load.
Am I doing something incorrect with the files?
I can’t seem to get exclude_tag_id or exclude_tag to work. My understanding is that you use this to keep a meta box from showing up on a page for posts that are tagged with that tag. Am I understanding this correctly? Does this work with a taxonomy that is registered to a custom post type?
I have a custom post type called Events that I have created and a taxonomy of “event_tags” registered to the custom post type. I created some tags within that taxonomy. The one I want the meta box excluded from is called “destination” and its ID is 6. I have tried to exclude this but it doesn’t seem to work.
Here is my meta box code:
// add event time custom meta box
new WPAlchemy_MetaBox(array
(
‘id’ => ‘_event_time’,
‘title’ => ‘Event Time’,
‘types’ => array(‘events’), // added only for events
‘context’ => ‘side’, // defaults to “normal”
‘priority’ => ‘low’, // defaults to “high”
‘exclude_tag_id’ => 6,
‘template’ => TEMPLATEPATH . ‘/custom/event-time.php’
));
Any ideas on how I can make this work?
Is it possible to use this class to add custom meta boxes to a custom ‘category/taxonomy’ I’ve set up?
For example, let’s say I have a new custom post type of ‘book’ and a custom taxonomy of ‘author’, I’d like it so that when adding an author I could upload a picture of them as well.
Thanks 🙂
@Phil, I will review the sample files to make sure they are properly setup.
@Melinda, see this comment … the include_tag, exclude_tag currently do not work for custom taxonomies, this will be fixed in a later release. For now use the “output_filter” callback.
@Matt, I have a very, very early implementation of something for Taxonomies. It is not as mature as wpalchemy metabox class. But the class is easy enough to follow and adjust if you wanted to give it a go for your project.
Thanks! That works perfectly! I will be watching for updates in a later release. Thanks again!
Great code! I love that it just abstracts all the gory details away…
I’m having some trouble, though. The custom meta boxes show up on the page editor no problem, but they don’t seem to be saving. I have this in my functions.php:
include_once 'WPAlchemy/MetaBox.php';
// include css to help style our custom meta boxes
if (is_admin()) {
wp_enqueue_style( 'custom_meta_css' , TEMPLATEPATH . '/WPAlchemy/meta.css');
}
$custom_metabox = new WPAlchemy_MetaBox(array
(
'id' => 'custom_meta', // underscore prefix hides fields from the custom fields area
'title' => 'My Custom Meta',
'template' => TEMPLATEPATH . '/WPAlchemy/meta.php'
));
And I have meta.css, meta.php, MediaAccess.php and MetaBox.php all in the WPAlchemy dir. Any thoughts?
Thanks!
Thanks @Dimas I’ll have a look at that 🙂
Hey Dimas.
WPAlchemy is too awesome, respect for sharing it with the community 🙂
There’s a small issue with importing content. I’ve setup several metaboxes for a custom post type. When I try and export the custom post type content and import it to another version of the site with the same meta fields, the content is corrupted. All metabox content is replaced with a capital A.
Do you have any idea why this may be happening?
Anyone have any luck creating a group of fields that are repeatable with the WYSIWYG editor?
I haven’t found any documentation other than this: http://www.farinspace.com/multiple-wordpress-wysiwyg-visual-editors/
That works fine to add the WYSIWYG, although off the bat it doesn’t save line-breaks or formatting. And when you use the “Add” button to create multiple fields it doesn’t let you write in the WYSIWYG until you save the post.
Screenshot: http://grab.by/aA9s
The duplicated WYSIWYG is disabled upon duplication, and it also starts it out at 100px high.
Any thoughts here?
Sorry for commenting above before reading all comments and without a detailed explanation.
I’m running WordPress 3.2.1 and WPAlchemy 1.4.14. I have setup several metaboxes using WPAlchemy on a sub-domain for a client to start uploading content while I work on a local version.
When importing the “documents” custom post type content with the WordPress importer, all content is imported except metaboxes. All metabox content is replaced with A. I see that a few other users have experienced similar issues.
Has this been resolved? If so how would I go about getting metabox content from one version of the site over to my local version?
@Duane, I don’t know why, can you tell me your exact export, import procedure? Are you using WordPress Export/Import XML or going via the database? Give me a step by step and I will try to reproduce to solve the issue.
@Coby, make sure you are using the latest version.
Scratch that last question. Got it all figured out… I should have read the comments better.
Thank you so much for providing all of this amazing code.
@Dimas, I tried using the WordPress export/import XML I tried Migrating with BackupBuddy and I tried importing the database which I exported from phpMyAdmin.
When exporting the XML I went TOOLS -> EXPORT -> CHOOSE WHAT TO EXPORT -> DOCUMENTS.
I then imported the XML, but the metabox content wasn’t imported.
Not sure if you’re familiar with BackupBuddy, it provides an option to backup and migrate. It handles file extraction and database dumps. That didn’t work either.
I also tried copying the websites files over, exporting the SQL database and importing it on the server I wish to migrate to. That didn’t work either.
I’ve got one more idea on what might be the problem. Is it possible that using a different version of WPAlchemy could cause the problem?
I’m going to make sure both sites are using the same version and I’ll post my feedback.
Thanks for the speedy reply.
@Duane, early on in development there were issues with WordPress double serializing the data, but I’ve added code in WPAlchemy do take care of the issue.
Additionally there is an issue when a use does a db dump and then imports it and then does a search and replace on the wp_postmeta table, if anything changes inside a serialized string it will get corrupt (This isn’t an issue with WPAlchemy, just the nature of PHP serialized data).
I recommend that you look at the wp_postmeta table and check the values before and after export/import.
When you say that it makes me thing that you might be running to a character set issue? I am not sure why everything would get replaced.
I have added a metabox to my edit post screen for a custom post type called “releases” on a record label site that displays a list of “artists” from another custom post type. I have it working just fine, saves the data, and i can do a get_posts query and get what I need on the front end.
I’m looking to go a bit further though, beyond meta and tell that drop down on the edit release metabox to use the selected artist page id from the to be the parent of the a release custom post. I’ve read a bit about wp_insert_post and post_parent but I don’t know if I need to create my own metabox from scratch or is wpalchemy capable of doing this? I dunno wpalchemy goes beyond adding metadata to the database.
Dirty way of doing what I needed: I edited my release meta php template for wpalchemy and basically threw this in as a field within the metabox:
<input type="text" id="parent_id" name="parent_id"
value="post_parent; ?>" />
and I can manually set the post parent by entering the target post id. It’s a start and it updated the database so it works so far.
@jesse, just so i understand, when a user selects a item from the drop down (each item is associated with a post_id), you want to be able to get the selected post parent_id?
No i wanted to have a field (not really post meta) that would allow me to make a new post of one custom post type (releases on a record label) a child of a post of another custom post type (artists). Mixing two post types without using post meta.
Probably not the most ideal way but having a release be a child of an artist will work better than post meta. I can then list children of the artist as releases that I have tied to their parent artist through post id. The field I added, which doesn’t really use the wpalchemy class other than my text field residing in a wpalchemy template file, updates the wp post_parent dbase field with whatever ID I want.
I may or may not use this on the final site but I wanted to give it a go and see if it’s what I needed.
Hey @Dimas.
So I’ve just taken a look at the wp_postmeta table. One of the metabox id’s is document_info. On the site site where I am exporting from, one of the document_info values are a:1:{s:6:”author”;s:14:”Illana Meltzer”;}. All other WPAlchemy metabox values are similar, obviously with the corresponding values. On the site I’m importing the XML, the same value is returned as Array. Actually all WPAlchemy metabox values are Array. This is really confusing and I don’t have any idea why this is happening.
Is there perhaps anything else I could provide to shed more light on this issue? Could running different versions of WordPress have something to do with it?
Update: Doing a migration with BackupBuddy works. All metabox values are identical, but importing the XML via wordpress importer still gives the issue spoken about above. Not a major train smash and I’m going to test importing with a different site sometime today just to confirm it doesn’t work. If no one else is having this problem it must be something to do with this particular installation.
Thanks so much for your time @Dimas, much appreciated.
Hi @Dimas
I’ve created 3 separate custom meta-boxes, ‘name’, ‘image’ and ‘url’. Is there any way in which I can control the order in which they appear on the admin page? At the moment I’m seeing ‘image’ > ‘name’ > ‘url’, but I’d like to put ‘name’ first.
Thanks.
Hey,
I’m using the WPAlchemy MediaAccess class and the code below displays the values for the cloned fields which is great!
How do i echo only the first field?
If i remove the foreach function the output is “Array”.
Help appreciated 🙂
Thanks
Following on from my comment below, I’ve tried using the ‘context’ and ‘priority’ parameters on my metaboxes, but they don’t seem to have any effect. Any suggestions?
@matt – i just had to do that. i don’t think there is an alchemy function for returning the first value (though you could use the is_first() and then break your while loop), but i just had to do this myself.. and you can accomplish it with arrays.
`
$array = $outdoors_metabox->the_meta();
$image_id= $array[‘outdoors’][0][‘image_id’];
`
where ‘image_id’ is the field in my ‘outdoors’ loop
@kathy
Thanks Kathy! 🙂
I am working on implementing the media uploader into a metabox. Everything works great on the admin side but I can’t seem to get the data to pull into my page template. I have spent hours going through all 687 comments trying various suggestions and still nothing. I have looked at the section describing how to use the meta box values in your template numerous times and tried the different options numerous times and still nothing.
Can anyone help me?
I feel like this should be easy and I must be missing something very simple.
Here is my meta box creation code from my functions.php file:
Here is my meta box fields template (gallery_images_repeatingfields.php) code:
The code in my page template has changed so many times with everything that I have tried that I am not sure I know what should go here.
Here is my page template (gallery.php) code:
Can anyone help me? I am feeling quite dumb right now.
I previewed this message and the code isn’t showing up completely correct. Let me know if there is a better way to show you my code.
Thanks!
Are there any examples of file uploads without “Media Access”? I’d really like to just have simple file upload inputs and run my own processing saving a value for the end results location. Is this possible?
@Melinda, please repost, use gist.github.com and then just post a link to your code snippets (I’ll delete your prev post when you do repost).
@Christian, yes I think its possible, I’ll do a few tests myself, but i figure its possible using the “save_filter” in wpalchemy, you can then inspect
$_POST
and$_FILES
vars and then do your own processing.Can anyone tell me how to define simple image upload with select file rather than using wordpress media upload?. I searched all posts here. There is no post explaining simple upload option. Thanks
I am working on implementing the media uploader into a metabox. Everything works great on the admin side but I can’t seem to get the data to pull into my page template. I have spent hours going through all 687 comments trying various suggestions and still nothing. I have looked at the section describing how to use the meta box values in your template numerous times and tried the different options numerous times and still nothing.
Can anyone help me?
I feel like this should be easy and I must be missing something very simple.
Here is a link to the code on gist.github.com:
https://gist.github.com/1116170
Thanks!
@Melinda, I’ve made some slight adjustments … I use print_r to pring some vars to screen, check if you see data printed out … you’ve got to remember that “imgurl” is a variable inside an array (since you are using the repeating fields), you can’t access it directly.
https://gist.github.com/1116182
@Dimas
I tried the slightly altered code you sent and it did print the data out. It printed this:
Array ( [gallery_image] => Array ( [0] => Array ( [imgurl] => http://dev2.mccawphotographics.com/wp-content/uploads/2011/07/IMG_3183.jpg [title] => 1 [gname] => test ) ) ) Array ( [0] => Array ( [imgurl] => http://dev2.mccawphotographics.com/wp-content/uploads/2011/07/IMG_3183.jpg [title] => 1 [gname] => test ) )
Since I can’t access “imgurl” directly what is the best way to get the “imgurl” for each image to populate my src of my img tag?
@Melinda, I’ve modified the code to output the images: https://gist.github.com/1116182
@Dimas Using repeatable fields, is there a way to run some code right after adding a new field? I need to enable TinyMCE editor for new instants. I’ve tried to run my code right after the button click:
but since it checks for ‘tocopy’ class existance it should run AFTER WPAlcemy Class original function that removes the class. Otherwise, the last added field would be always excluded.
@Ma’moun, try using the built in javascript events:
@Dimas Exactly what I needed. Works great.. thanks!
@Dimas Thanks! That works great! Is there a way give the first image a different css class than the remaining images?
@Melinda, I’ve edited the example: https://gist.github.com/1116182
@Dimas Thanks so much! That works perfectly!
I have changed the code slightly because I want to integrate Shadowbox to create a gallery. I tried echoing get_the_post_thumbnail in the src for the image because instead of pulling in the full size image I want to pull in the thumbnail, but it isn’t working yet. Is it because I am using the repeating fields that this doesn’t work?
My revised code is here: https://gist.github.com/ae30e837cfb4aa17f879
I am also trying to pull the thumbnail into the metabox so the user can see the image they just added instead of just the url. I haven’t been able to get get_the_post_thumbnail to work there either.
I couldn’t get this working in WordPress 3.2 until I manually called wp_tiny_mce() in the admin header. See WPSE 22599 and 22466.
I was able to use the WPAlchemy meta box class to save taxonomy terms.
The main issue is to bypass normal save which saves values from metabox into post_meta table and instead use a custom function to save data to taxonomy tables.
I used ‘save_filter’ => ‘save_myposttype_taxonomy’ filter function with return false to bypass the normal save behavior. Instead used my filter function to save the values of my taxonomy term menus with wp_set_post_terms.
I realize Dimas has a separate class for taxonomy meta boxes under development.
Would it be worthwhile to do the following? Are there any problems with this?
-modify the meta box class for saving taxonomy terms
-add a configuration variable to the WPAlchemy class like ‘metabox_type’ = ‘taxonomy’
– if set to ‘taxonomy’ , class will internally use wp_set_post_terms to save instead of update_post_meta
– so user does not need to specify custom function to save taxonomy terms.
i don’t think there is anything wrong w/ the solution the way you have it. it’s a metabox that isn’t saving post meta so a custom filter seems appropriate, but what do i know 🙂
would you mind posting your function? i had to do this a few weeks ago and didn’t use alchemy for that box b/c i couldn’t figure it out.
I have a metabox i want to paste a youtube embed into but after I save, because of the quotes, it’s not saving or showing the saved tags and html code correctly.
I removed the tag brackets b/c it wasn’t letting me paste the code to yr site comments so the iframe should have greater than and less than signs around each:
example:
iframe width=”560″ height=”349″ src=”http://www.youtube.com/embed/SCZk34CcBow” frameborder=”0″ allowfullscreen /iframe
cuts off just before the 560 width so the text field after saving says:
<iframe width="
and nothing more. Do i have to do anything special to get around this?
@jesse – i had some issues with quotes in text fields once. i thought it got resolved. but in your case a text area seems more fitting.
@jesse, be sure you are using version 1.4.14
@Dimas
I was able to solve how to pull a thumbnail into my page template gallery.php for my shadowbox gallery. I am not sure if this is the best way to do it or if there is a better method. Here is a link showing how I did it: https://gist.github.com/02f423c21cfb053b2399
I’m feeling quite stupid here. I’m attempting to use this but no matter where I try and install the wpalchemy folder, and then add the suggested code from above (just for testing purposes):
// include the class in your theme or plugin
include_once 'WPAlchemy/MetaBox.php';
// include css to help style our custom meta boxes
if (is_admin()) { wp_enqueue_style('custom_meta_css', get_bloginfo('stylesheet_directory') . '/custom/meta.css'); }
$custom_metabox = new WPAlchemy_MetaBox(array
(
'id' => '_custom_meta',
'title' => 'My Custom Meta',
'template' => STYLESHEETPATH . '/custom/meta.php'
));
I get the dreadful blank white screen when something has gone awry with your functions.php file. I guessed from the zip file, that I was to place the wpalchemy folder in wp-content and the metaboxes folder in my personal theme folder. One thing I did notice is that the path to the wpalchemy folder is WPAlchemy for the functions file but the folder itself is all lowercase.
If I’ve uploaded in all the right places, then what am I doing wrong? (I’m using 3.2.1 Multisite)
Just wanted to say that I finally figured it out… I placed the WPAlchemy folder (with the capital letters in place) in my theme folder and I no longer get the blank white screen.
I just noticed one thing about my solution that isn’t working correctly. The thumbnail that is being pulled in is the thumbnail for the 2nd image in the gallery. And it is pulling in the same thumbnail for each image in the gallery. Can anyone see in my code what may be causing this? Is there a better way to do this? My code is here: https://gist.github.com/02f423c21cfb053b2399
This might be a bit obscure and outside the WPAlchemy Product (and if it is, feel free to ignore) but… I want to either remove the rich editor meta-box for a page based on it’s ID or just hide it display:none style. I understand that I can easliy do this with CPT’s, but this is something I’d like to do with a Home Page template I’ve created in “pages” which will only have a slideshow. I added a Media Uploader metabox based on WPAlchemy and would like to remove the editor since it has no use. This will be passed to a user who might get confused with it being there, and for me it’s just the right way to do it (if possible). See a screen shot here: http://t.co/iElyWps
@Rich – if i understand you correctly, hiding the post editor is already a built-in capability of alchemy.
you just set ‘hide_editor’=>true when declaring your metabox
see the Display Options on this page
http://www.farinspace.com/wpalchemy-metabox/#display_options
i do that myself when creating homepage templates w/ slideshows
@Kathy,
Wow, i must have missed that.. Thank you so much! It worked like a charm.
hi, i am new. it looks great , i can make it work with the default install you suggest and i think it will be easy to print the values and everything. i could not though use it to display a media button to allow authors to upload an image. what should i read. ?
also i could not find meta.php i guess it changed to MetaBox.php
thnx
@dimitris,
meta.php
has turned into these files. See this post for MediaAccess usage.@Dimas thnx for the reply. i did find the files and the example you have and i can upload an image and display it in my posts, BUT is there a way to add a delete button? also is there a way to display the image the author uploaded like the featured image functionality?
@dimitris – yes you can do that w/o the mediaaccess class, but it is more complicated. i’ve put what i do in the comments on the mediaaccess post (seemed like it was more relevant there)
http://www.farinspace.com/wordpress-media-uploader-integration/comment-page-2/#comment-17330
Grr…. I’ve been at this for hours, and I haven’t been able to make this class show anything. I can echo out a testing statement in the class file, so I know it’s being included. I did the same thing with the callback function, so the class is definitely getting called. But it refuses to show any fields whatsoever. All I get is the title of the box, and then an empty box. What could I be doing wrong?
Can someone please give an example of using this in a plugin so I can see a working example?
there are samples in the download file. i’m not sure exactly what problem you are have… are you getting an empty metabox? ensure the metabox’s template path is correct, though an incorrect path should throw an error.
Interestingly, it looks like it was not a correct path, yet it was not throwing an error. I got it to display the template correctly, and to save values once I changed the template reference to one that worked for me.
My next challenge is to display metabox values on a widget associated with a post. No success yet with the current code, but I’m working on it…
How would you right an if statement based on the results of a radio box group? For example, if box 1 is checked, echo this, if box 2… and so on.
Thanks
Fantastic! Thanks for making my life easier. Can’t wait to dive in further.
Forgive me if this has been addressed before, but I seem to be encountering something with selects and multi. When I have a select within my multi code I get a new meta box on every update. Have you seen this before?
Thanks again for the great work.
Hello there, thanks for coding this very useful class.
I’m encountering an issue that I can’t seem to wrap my head around (although it might just be me failing @ wordpress)
I got some Metaboxes set up and i’m using the “save_filter” param when declaring them to do some data validation (basicly one of the metas must be unique, so I check the metas of the other posts to prevent save if there’s any duplicate), and it’s working wonders (meta only saves if correct, rest of the post saves no matter what).
I just can’t find a way to provide feedback to my users if the validation fails. Providing this feedback through Javascript -ranging anywhere from inserting an element into the dom to displaying a simple alert()- would be ideal.
Anyone got an idea?
Thanks by advance
@nik
Hi – I’ve been trying this out for the first time. Just encountering a little problem with ‘have_fields_and_multi’. Whenever I click on the ‘update’ button in the editing window, it creates a new instance of the group that’s empty. If I keep clicking ‘update’ it keeps adding empty sets of that group. There’s probably a simple explanation that a newbie like me is missing. Any thoughts would be appreciated. Thanks.
@Ethan, please post you code using http://gist.github.com and I and others will have a look.
Hi Dimas – many thanks in advance for taking a look at this. Trying to set up a website for a highschool athletics department, and your class is the perfect tool to help. Here is the code snippets – please let me know if I am missing anything else you need to see: https://gist.github.com/1151456
@Ethan – very cool that you are doing league/team management w/ alchemy.
i just tested your MB locally and i think the problem you have (where you get a new group on save is b/c your ‘Outcome’ dropdown has ‘TBD’ as a VALUE by default. b/c it has an actual value the group is not empty so alchemy saves it and then its default behavior is to always offer a new blank group on update.
to fix this, change:
<option value="TBD" is_value('TBD')?' selected="selected"':''; ?>>TBD
to
<option value="" is_value('')?' selected="selected"':''; ?>>TBD
@Kathy – you’re awesome! I greatly appreciate your attentiveness to these comments. My hat’s off to Dimas and yourself. Many thanks.
Another quick question. I am using the jQuery datepicker plugin on a date field in my form. When I add a new group, the datepicker in the new group is not active. Any suggestions on a filter, or how to tie in to the ‘add’ action to re-initiate the datepicker plugin?
@Ethan, see this comment.
@Dimas, thanks for your help. I tried implementing this technique (see code below) but it isn’t working for me yet. Please advise.
@Ethan, try changing the following:
Additionally look into using jQuery live bindings …
@Dimas, once again you’ve helped out a bunch. I looked into the live bindings and played around with it. For the benefit of everyone reading this, this is the code that works flawlessly:
$('.team_schedule_datepicker').live('click', function(){
$( this ).datepicker({ dateFormat: 'yy-mm-dd', showOn:'focus' }).focus();
});
Arg!
Just “wasted” a bunch of time figuring this out. So for anyone like myself who use the Roots (http://www.rootstheme.com/) theme. The WPAlchemy functions must exist in the original functions.php. And nowhere else like roots-custom.php or the like.
@Scott, sounds like a scope issue, might need to do
global $mb;
(or similar)I have a problem on the out put…
I’m using…
while( $testimonial_metabox->have_fields( ‘testimonials’ ) )
The output works fine exactly as expected.
But I want to insert a div which will style the group which is also variable but created outside of the group.
But when the page renders, the field shows blank. If I move this particular field into the group it works, but then I have to define this field for each each time I replicate the group.
Any ideas?
Hi, I’m loving this plugin but I’ve hit a snag. I have no idea how to do a query_post (with meta_query) for values inside a “have_fields_and_multi” field due to their array nature. Even WPALCHEMY_MODE_EXTRACT doesn’t help as it doesn’t affect that kind of field. Is there any way to do it?
Thanks!
Hi, many thanks for providing such a brilliant plugin. Just what I needed! I think I’m having trouble with saving my field content though. For example, if I have a meta data text box and I enter some text into it then click ‘update’ on the post/page edit screen, the text disappears. Not sure what’s going on but would be really grateful if you could suggest a cure.
Many thanks in advance.
I solved the above – it was a typo! I’m using the loop to display the contents of a page in two different areas in a page template (using WP_Query). I can’t seem to call the metabox value more than once. In other words, it’ll work in the original loop [using
if(have_posts())
] but won’t work in any extra loops calling the same content.I can’t seem to work out how to make this work. Any help would be much appreciated!
Thanks again
I´m not sure of how I should get started using this. I downloaded WPAlchemy and I got two folders: WpAlchemy and Themes. WpAlchemy goes where? I´m guessing i should paste the content of Themes/mytheme into my current theme right?
Then pasting the following into functions.php:
// include the class in your theme or plugin
include_once ‘WPAlchemy/MetaBox.php’;
// include css to help style our custom meta boxes
if (is_admin()) { wp_enqueue_style(‘custom_meta_css’, get_bloginfo(‘stylesheet_directory’) . ‘/custom/meta.css’); }
$custom_metabox = new WPAlchemy_MetaBox(array
(
‘id’ => ‘_custom_meta’,
‘title’ => ‘My Custom Meta’,
‘template’ => STYLESHEETPATH . ‘/custom/meta.php’
));
However, there is no custom folder included anywhere and there isnt even a meta.php file in any of the folders you download?
What am I missing?
@Johan, I have a video on installation and setup: http://youtu.be/gQdJMI8fXuk
@Sam Kitson, try explicitly setting an ID (WPAlchemy will try to guess the current post ID, but sometimes it just cant):
@Antonio, consider using the
save_filter
this will allow you to add specific values from your repeating fields usingadd_post_meta
:@Armand, I don’t quite follow … perhaps a code example (please use https://gist.github.com)
Thank you! Now I´m on my way! 😉
Dimas,
I posted the code here.
https://gist.github.com/1185725
Thanks for looking at it.
@Armand, here is my revision: https://gist.github.com/1186363
Also, don’t use
wpautop()
directly, use it when you are doing the final output (you might also trynl2br()
)Dimas,
Thanks for your modifications. I’ve tried that before, but when I use the output, I’m using…
https://gist.github.com/1186710
The “background” field comes out blank. That’s the problem with this method. Am I doing this wrong?
Thanks again for your suggestions.
@Armand, the first method is recommended: https://gist.github.com/1186752
Let me describe why it was not working: when you are in a
have_fields()
loop, WPAlchemy makes an assumption that all the values you are trying to fetch are part of the group, in this case “background” is not, so it needs to be fetched outside of the loop first.Been trying to figure something out, and didn’t see anything about it.
I am making a plugin that uses the WPAlchemy class. I need to use the repeatable fields, which work great. Except when I try and run a repeatable group within another repeatable group… I need to be able to make a section that is repeatable, but has fields within that section that are also repeatable…
If I use the while and endwhile I end up with an infinite loop. I have tried using the wp_reset_postdata(); but no luck. Any thoughts?
Dimas,
Thank you so much. It works perfectly. You’re awesome and this plugin is amazing.
@Dan Gavin, unfortunately my initial attempt at repeating fields does not support nested groups.
What you can do/attempt is to create a custom loop instead of using the
have_fields_x()
functions … if you view source on a repeating field group you will see what wpalchemy writes out:Your custom loop would have to mimic this, the javascript for the repeating fields is pretty solid and should be able to be reused inside nested groups (e.g. using the class names).
In a future release repeating fields will change to possibly use PHP iterators to easily allow nested groups.
Dimas, I’ve got a custom hierarchical taxonomy with 1000+ terms and growing that’s causing serious hang time while editing a post. I’d like to replace it with a custom meta box. While being able to add terms from the metabox would be nice, the biggest part is being able to use the metabox to properly tag the child terms and parent terms. (The example here is a location taxonomy, e.g. City, State, and Country). I am thinking that an autocomplete solution using AJAX to load the terms is going to be the way to go.
I am looking for examples or even just suggestions that I can work with. Do you have any ideas?
The auto-complete solution sounds like the best solution, I’ve used this solution, for a different project (non-wordpress) which has some 30,000 terms … it works really well and it has some nice matching features/callbacks.
anyone know how to preselect a selectbox?
Hey Dimas,
Is there any way to use this class to add custom “user meta” rather than post/page meta?
Does anyone have a good example of using alchemy with a date and time picker?
Another questions… ho do you limit deletion of a group. I have a delete button for the group, but I don’t want someone to use it that’s the only group in that set.
Meaning you can only delete from the second on, and if there is only one, you can’t delete it.
Anyone?
Also, still wondering if anyone knows how to set a default item on a selectbox.
@Armand
I’m not sure if you’re asking “in general” or specifically related to this class… but “in general”, the way you select a default item in a selectbox is like this:
<select name="blahblah">
<option value="blah" selected>Blah</option>
<option value="bleh">Bleh</option>
</select>
Where “Blah” would be selected
Okay.. I tried posting this comment on a different page but I don’t think it works. Several apologies if it shows up twice on the site.
Hey,
I posted a discussion on the Facebook page as well but I’m hitting a wall right now and I’m hoping somebody can help me:
I’ve created a metabox to get some specific information about individual products I’m putting on my site. That way I can create a template so that all of the information gets input and formatted and I don’t have to format each product’s information page from scratch. Simple enough…
But now I would like to create a catalog/category template that calls information from that same metabox. Only problem is…I can’t figure out if there’s a way to loop through all of the pages using that metabox and get specific info. For example:
I’ve published a bunch of pages of men’s shoes (the ‘gender’ variable has a value of ‘mens’ on each of these pages, via a radio input in the metabox). So on the catalog/category template I want to display a photo for each of these shoes and a short description of each. In theory, it seems simple. But the one piece I’m missing is: Is there a way to loop through ALL of my shoe products and only write the ones that the ‘gender’ value == ‘mens’ where I’m trying to write the men’s shoes? And then, similarly, do the same for women’s shoes, etc?
In theory, I’d want to be able to just write the template to loop through my product pages and call the category by value so that I don’t have to update the catalog every time I add a new product; it should be able to update dynamically with the addition of a new matching value. (Hope that makes sense.)
I can’t figure out how to do this, as I don’t know how to write the loop to go through the metabox’s data, not just one specific page’s data.
Any help with this would be extremely appreciated. 🙂 Thanks in advance!!
@Nina, what you describe sounds like a perfect candidate for the use of taxonomies in WordPress. In fact I would recommend that you look into it and learn more about it as it will give you a lot more mileage as your site grows.
If you are going to proceed with WPAlchemy for your intended behavior, I recommend you read a little about the storage modes. Using this option will allow you to use the wordpress
get_posts()
functionYou can then loop through the returned posts, something like:
Be sure to read about the WP_Query object as well, it goes more in depth as to the parameters that you can use, with
get_posts()
.@Josh, its untested with user meta, and am pretty sure it won’t work. On github I have a quick/short class for meta data for taxonomies which can probably be adapted for user meta (just a hunch).
@Dimas thank you so much for the quick response!
I took your advice and have been reading up on taxonomies all day…And it’s all bringing up another question: What I’m running into is that I can’t find a very thorough resource for implementing taxonomies with my desired functions.
Originally I thought I’d need one separate page for each category, i.e. men’s shoes, men’s boots, etc. that display all products in a given category. Plus separate pages that only display products in a given subcategory, i.e. men’s mountaineering boots, men’s backpacking boots, etc.
In reading up about taxonomies, I’m finding a way to easily list corresponding posts, and I’ve seen mentions of taxonomies being applicable to pages, but I haven’t found anywhere that specifically explains the way to actually show taxonomy results in pages–which is a problem, as all of my products are listed on pages…Plus I’m not finding anything that shows how to create a specific format for the information to appear. All I’ve found is how to list the applicable posts–make the posts with applicable taxonomy classification show, with default author and publish information.
So while taxonomies does seem like the best way to do this, I’m struggling in that I can’t figure out a way to customize the page and the results. I don’t want the whole page to appear in the list; I only want a specified photo, a specified description, and a list of links. (See my interim solution using an iframe here.)
This is more or less what I’m looking to accomplish, but I’m trying to find a better method than iframes (at this point, I’m not stuck on the display functionality here, but this page illustrates the general information I’m looking to include for each product; rather than a blurb from the individual products’ pages, I’ve written a unique description specifically for this “category” page and then included the same photo from the individual page as well as three links–one to the product page itself, one to its corresponding review post, and an affiliate link).
So as I’ve been studying the taxonomy functionality, I’m beginning to think that there isn’t a way to do what I’m trying to do with taxonomies, given that I have specific formatting needs and am using pages. Am I wrong? Is there a way to create a category template and format it the way I need to and then include the information I need (photo, unique description, and specified links) from each of the pages?
Thanks again for your help. I recognize this is a lot but I’m new to all of this (as I’m sure you can tell) so this project is a bit of a struggle for me. I really, really appreciate your help.
Hi, I started a thread on WP stackexchange on “Sorting custom columns with WPAlchemy”.
If some of you are interested, go on !
@Nina, taxonomies will help you categorize stuff … and once you’ve done that, you can use WP_Query do do custom searches, which will return custom lists of posts.
So for example … I would have a category template/page, which would display basic category info, and then I would do a WP_Query to get specific posts that relate to this category.
With the list, I can get the post information … not only the title and content, but also any additional meta data (via meta boxes) that I have attached to it. In your case an image-url, cat-description, and aff-link. I would loop the list and display the info as needed.
The above is really a simplistic explanation, and to be honest I don’t have much practice with taxonomies (i’m not intimately familiar with it other than a couple of uses).
Hi Dimas,
I’ve been using WP Alchemy on my website and love it! I’m now in the early stages of trying to set up an online store with the WP E-Commerce plugin, and would like use WP Alchemy to add custom meta boxes to the product pages. It seems like I should be able to do this, but I can’t figure how to define it in the spec file. Any help is really appreciated!
@Josh,
Yeah, that would typically work, but when using this class, when I save, the same option would still be selected and the select box would not reflect my new changes.
So I’m still trying to figure this out.
@Armand,
I just noticed the same issue–I’ve got a select box in one of my metaboxes that no longer saves the value when I change it and update the page. What’s weird is that the updated page reflects the saved value, but the edit page continually resets to no selection when I save it. So any time I update the page, I have to remember to update the select box again, otherwise the value disappears from the page.
I’m trying to figure out if it has something to do with my page template. Before I assign a template to my page, the select box holds value just fine. But when I update the page template, that’s when it resets.
I’m curious to know whether your problem is related to templates, too?
v1.4.15 takes care of some select box issues.
So after a lot of trial and error, I did manage to get custom meta boxes added to WP E-Commerce. In case anyone else runs into this, here’s the fix. Since that plugin uses custom post types, turns out all I had to do is define the type when setting up my meta function, like so:
‘types’ => array(‘post’,’page’, ‘wpsc-product’)
Thanks again for the great plugin Dimas!
I have a quick question if you don’t mind.
Group of fields for every week day, and I’m trying avoid repeating code by making it a function. But I can’t get the function to work. Have a look at pastie.
It seems to choke when ever $custom_metabox is mentioned. Big thanks! 🙂
looks like a scope issue, use
global $custom_metabox;
inside the function, at the beginning.I have a problem. I have two plugins I created using WPAlchemy. When I try to active the the second plugin, I get…
Fatal error: Cannot redeclare class WPAlchemy_MetaBox
Any ideas?
I tried to do something like if class exists but still get an error.
@Armand, I’ll have a solution for you soon.
I have a custom metabox for an existing custom post type. The current metabox uses extract mode for the meta values. I assume this means that the data for the meta fields are serialized as a single field in the database.
I need to add a new field which will act like a sticky post priority. This will be a number and I need for the archive page of the custom post to display the order of custom posts with entries having a sticky priority number at the top and ordered first by the number.
If I simply add the new sticky priority field to the metabox can I use a standard meta field query in query posts or would it be better if I stored the sticky priority field as a regular meta value and not serialized.
Is there a way to have both serialized and normal meta values in a single metabox?
Hayden, you have the “array” / “extract” backwards, see this article for more info …
Ran into another instance of the same issue.
Someone has a theme using WPAlchemy so when they went to activate my plugin, the also received…
Fatal error: Cannot redeclare class WPAlchemy_MetaBox
I tried several options to use the class twice.
I thought I had it…
I wrapped the class in with…
This stopped the “redeclare” error. But only if BOTH instances of the class were wrapped.
I thought this fixed it, but even though both plugins seem to work, the problem is neither one will save now.
Anyone have any ideas or solutions? I know Dimas is working on one.
@armand – have you tried wrapping the include_once statement like so?
if ( !class_exists( 'WPAlchemy_MetaBox' ) ) {
include_once( dirname ( __FILE__ ). '/WPAlchemy/MetaBox.php');
}}
no idea if that will solve your problem, just an idea.
@kathy…
Yes, I tried that and it still gave a fatal error.
A problem with select boxes ONLY with “have_fields_and_multi”.
If you have a select box with just “have fields” everything works fine.
BUT… if you have a select box with “have_fields_and_multi”, then each and every time you SAVE the page, WPAlchemy will add another instance. I wasn’t noticing it at first, but when I checked my page I noticed 16 instances of my group.
Anyone else have this issue? I believe it is the code itself.
Like I said, it’s ONLY with select boxes and “have_fields_and_multi”. Anything else I’ve used with “have_fields_and_multi” I have no problems with.
Ok, I got the select boxes working. Apparently… it was my fault. UGH! Not sure what went wrong. I copied code above. I went to GitHub and used code there and it worked fine. Maybe that was the fix.
Not sure, but if you use GitHub code you’ll be fine.
Now, just to be able to use WPAlchemy more than once with two seperate plugins. Working on that too.
Armand, I will have this resolved for you this evening …
It will probably involve a combination of using class_exists and wordpress hooks.
Thanks… I’ve tried several methods. I tried wrapping the class with class_exists and it looked like it worked until I went to save. The other issue with this method, is that it didn’t work unless I wrapped both instances. The issue I could foresee is making it backwards compatible. Meaning, if someone has an older version of WPAlchemy.
Thanks. I look forward to seeing the update. I’ve been watching GitHub. 🙂
Hello,
a very basic problem… I dont manage to display the content in my site. Following your tutorial I get to the point of
print_r ( $meta);
and it displays the content I gave to the fields in this format
Array ( [name] => Nombre [description] => esta es la descripción [authors] => Array ( [0] => autor pepe [1] => autor paco [2] => autor jose ) [info] => informacioon [links] => Array ( [0] => Array ( [title] => http://enlace.com [url] => http://pepe.com [nofollow] => 1 [target] => _self ) ) [and_one] => Array ( [0] => uno individual ) [and_one_group] => Array ( [0] => Array ( [title] => el grupo 1 [description] => el grupo 2 ) ) [docs] => Array ( [0] => Array ( [title] => tiulo [link] => enlace ) ) )
But then I cannot display the content of each field. I have tried both the $custom_meta-> and the get_post_meta and also tried with extract-array.
Just in case,
global $custom_metabox;
$meta = $custom_metabox->the_meta()
print_r ($meta);
works fine
but
$meta = get_post_meta(get_the_ID(), $custom_metabox->get_the_id(), TRUE);
print_r ($meta);
it is not working.
Any suggestion?
@Antonio, you are like almost there, all you have to do now is target the values you need in the array and echo/print it …
I’m using wp_insert_post to create a post and assign a value to a custom field. I’ve built a metabox via WPAlchemy with a select box containing a list of values associated with the same custom field. The only problem is that when you go and edit the post, WPAlchemy doesn’t show the appropriate value as “selected”.
Is there a way that I can force WPAlchemy to update the select state when a value is set for the custom field?
@Jonathan… here’s sample code I’m using for a select box that works.
Hope this helps.
@Jonathan… Sorry about that, code didn’t post all the way.
I uploaded code to Github.
Here’s the link: https://gist.github.com/1258146
@Armand – Thank you for the example! I re-read my comment and I see that my question wasn’t entirely clearly. The select state works great with the code I currently have.. the trouble is that I want it to be selected when its not set via WP Alchemy.
In this case, I’m setting the meta value via the add_post_meta function after I run wp_insert_post. So, in essence, I’m wanting WP Alchemy to check and see if there is a value set to a custom field that its assigned to and, if so, I want it to show it as selected.
Another way of looking at this would be using the “custom fields” interface in WordPress to set the value on a custom field otherwise controlled by WP Alchemy. When I set the value via the standard custom field interface and save the page, I would like WP Alchemy to notice the updated value and then update the select state accordingly.
Is there any way to make WPAlchemy work with post templates also? I’m using the Single Post Template plugin by Nathan Rice which uses post meta wp_post_template instead of wp_page_template. I’d like to be able to use the include_template parameter on both pages and posts if possible.
@Bud, just use a custom function for the output filter, in the callback just check for wp_post_template instead.
Thanks for getting back so fast.
I want to be able to check for both wp_page_template and wp_post_template. The problem is that I am not enough of a programmer to know what to do properly.
I see where I can change it to wp_post_template but I don’t know how to check for both.
@Bud, your callback might look something like:
@Jonathan Wold, if you haven’t already solved you problem, if you’ve changed the storage modes that will help, but you also have to ensure that the names/keys are the same … additionally you may consider using the “save_filter” and saving just the specific fields you need using add/update_post_meta and in your “x-meta.php” file you would retrieve the value manually and display it.
Thanks Dimas.
The above code didn’t work but it gave me a direction and I can now have custom meta boxes for page and post templates, so all is good.
Thanks
@Dimas I think there is something else going on here. The trouble is getting WP Alchemy to recognize data as “selected” when it didn’t assign it itself. It may have something to do with the data being inserted on post creation? Here are the relevant bits of code I’m using:
https://gist.github.com/1b62f5fdc8e4005403e9
Playing around with WPAlchemy. It looks great so far! Thanks for a brilliant script!
Hey,
Just wondering if it was possible to copy groups within groups, bit hard to explain but hopefully this code can show you what i’m trying to accomplish…
Basically, for example i have a text field that can be copied/duplicated like so…
My Group Of Text Boxes
Text Box 1
Text Box 2
Text Box 3
Then link: Add Text Box
Then link: New Group of Txt Boxes
I want to copy the entire group of text boxes, is this possible?
Hope this makes sense.
Thanks
Matt
I´m adding WYSIWYG-editors to some textfields in my metaboxes and it is working as intended, except that if I disable the normal editor in my custom post then the WYSIWYG-editor does not show up in my metabox. Is there a way to resolve this?
Adding in ‘editor’ in the custom post ‘support’ array brings the WYSIWYG-editor back in my metabox, but since I´m not using the ordinary editor I dont want it there at all.
@MattStrange, it is not possible at this time to do repeatable nesting at this time using the methods currently present in wpalchemy, it is possible to do it on your own with php loops and proper field naming, the js that wpalchemy uses will do the duplication for you properly no matter how far nested you are (designed that way). I’ve had several requests for this, so I think I will try to tackle that this weekend sometime.
@Johan, I think you can do one of the following: 1) use wpalchemy to turn off the editor (it basically hides it) vs using CPT option, 2) you can try using the proper includes needed for the editor to work: https://gist.github.com/1279185
I want to interact 2 select, how to do?
@Dimas – I found the trouble! WP Alchemy adds another custom field “$id . _fields” (e.g. _my_custom_metabox_fields) that stores the value of the custom field you added and is used by WP Alchemy to “register” that field. I simply had to run add_post_meta and insert the field name (serialized) as the value.
@Jonathan, sorry i missed that, glade you got it resolved though 🙂
I’m very confused , it seems that everything is well configured , but I only get ” Array ” ….
Let me show show in detail:
http://pastie.org/2686623
Could you please give me a hand on this
thanks
@Locke, it is an array because its a repeating field group: https://gist.github.com/1283241
Thanks Dimas 🙂
hey @dimas that do the work, thanks! , now what I’m looking is that is echoing everything:
array(1) { ["_nb_docs"]=> array(1) { [0]=> array(4) { ["_nb_title"]=> string(5) "Crema" ["_nb_kind"]=> string(4) "Cara" ["_nb_weight"]=> string(5) "1.5kg" ["_nb_beneficios"]=> string(5) "Hello" } } } Array
🙁
Mate you are the bomb. I am going to dive in to this one see how it goes. Wish I could code like you one day 🙂
Hey Dimas, thanks a ton! I’ve got a problem, though. While I’m logged into my blog, everything works fine. But, after I log out and try logging in again, a blank white screen appears and I can’t access anything in my admin area. Thoughts?
I’ve tried to do some trouble shooting, but can’t find the solution. All I’ve been able to find is that when I delete the code you tell us to paste into our functions.php file, I can access my blog’s admin area (but of course the metaboxes are gone).
Thanks man for your help!
Nevermind, I figured it out. When I pasted the code into functions.php, I had a few blank lines below it… my bad! Thanks again for your awesome work.
Fantastic work – this is the most flexible way I’ve come accross to create good looking WordPress meta boxes. I have one problem though, which I hope someone can help me with. I have a repeating field group with a text input, to which I am attaching a jQuery UI datepicker. When the datepicker is applied, it is applied to every field group, including the hidden field group from which new ones are copied. This causes the jQuery datepicker to fail on all but the first field group, because all newly added text input elements have duplicate id attributes. Any ideas how to overcome this?
@Emyr with jQuery you can do the following:
there are two available events … “wpa_copy” and “wpa_delete”
Hi Dimas,
Regarding “Emyr Thomas” question about using jQuery within a repeating field group, i have a similar issue where the jQuery breaks.
When i use the following code outside the
the_group
it seems to work flawlessly.http://pastebin.com/qyN5e1rX
But within the_group the jQuery breaks and the checkbox style doesn’t display correctly.
Any ideas on getting this to work?
I’m using the following iphoneStyle script:
http://awardwinningfjords.com/2009/06/16/iphone-style-checkboxes.html
Cheers
@MattStrange, similar to the @Emyr problem, basically js is used to clone the element(s), typically things applied via js will not travel with the cloned element(s), in some cases you can use live, but in other cases, like the above, you have to detect the cloning event and reapply your js. So basically you would do something similar to the above:
Thanks Dimas,
Hmm, i used the code you provided and the checkbox doesn’t seem to change to the jQuery iPhoneStyle and returns only a regular checkbox.
I’m not sure why? Does the script have to be within the $mb->the_group?
Cheers
Matt
@MattStrange, you’ll want to give it a class name if you haven’t already …
class="on_off"
and not use an ID … also be sure the JS is not in the repeating field loop somewhere.I have a metabox with a repeating field group, like “docs” in example above.
Every time I save some post, empty group is added. Is this bug or feature?
@Mike, it shouldn’t happen, by default it will start with one empty field, but after that is entered, then it should not display another empty field. Please post your [file]-meta.php file to http://gist.github.com so I can have a look.
Hi Dimas!
Here’s a quick question, can I loop through multi fields and sort in descending order? I’m loving the have_fields_and_multi functionality.
@Wendy, I would recommend doing it using the “save_filter”, something like:
Awesome work! Really been a joy to use compared to the other solutions I’ve found. Two questions: first, are there any issues with using multiple WPAlchemy metaboxes on the same page? Second, I’m noticing that even though I am using WPALCHEMY_MODE_EXTRACT, I’m winding up with the meta values saved both as a single serialized value in one row in the db, as well as each meta value getting their own row. Is that the desired behavior?
@Rich, I am glade you like it over some of the others, I think its a matter of taste with some, I personally like a balance of simplicity and flexibility. I absolutely hate it when I have to jump through hoops to do very simple things like add additional markup, or style things how i want it, etc.
1) no issues with multiple metaboxes on the same page that I am aware of.
2) even with the EXTRACT mode, wpalchemy will keep its own serialized data of just the field names for its own tracking purposes.
ok, that’s what I figured about #2, just wanted to make sure I wasn’t doing something wrong 🙂
Hi, I need some help, I’m going nuts! I used WPalchemy a few months back on a project and haven’t used it since. Now I’m trying to implement it on a new project and no matter what I do, I can’t get any values out of the data stored by WPAlchmemy in the postmeta.
Here’s my setup function: http://pastebin.com/hddqP5iv
Here’s my metabox code: http://pastebin.com/DVh07rHZ
Here’s my template code: http://pastebin.com/bXZ9MfQn
I get nothing output in the echo statements. I’ve also tried the straight “the_value()” method and that doesn’t work either.
Could some kind soul point me in the right direction? Many thanks.
@matt – not sure it will work, but try
global $metabox_settings;
$metabox_settings->the_meta();
Thanks kathy. Yes, I tried that method too and no luck. In fact, I tried all the methods in the original documentation. None of them work.
The stored data is definitely in the postmeta table. I simply can’t get it to show up.
Could there be any conflict with previous plugins that create similar data? I’ve tried a few of the Custom Field / meta box plugins on this WP installation.
@Matt, few things you can try …
Hello,
I am using your plugin in many custom post type with a lot of options = a lot of code so I was thinking in including them just for the custom post type I am using it but it is not working.
Do you know the implications of this code in functions.php or why I am getting a blank page??
if ( get_post_type() = ‘my_post_type’ || is_admin() ) { include_once ‘metaboxes/my_post_type-spec.php’; }
Thanks a lot and regards
Hi Antonio,
I am using the plugins in custom post types as well, and I just do the regular include in functions.php without conditionals, and then when I instantiate the new metabox in the spec file, just assign the type there:
‘types’ => array(‘my-post-type’)
I’m trying to modify the newly cloned item in a repeating field group, but I don’t think I’ve actually got hold of the cloned item. If I do a console.log(the_clone), I seem to have the event, rather than the jQuery node I was expecting. The target of the event seems to be an empty div with an id of wpalchemy. What am I doing wrong? Sorry, I’m a bit of a jQuery noob!
@Emyr, try https://gist.github.com/1313326
I’m asking this before I try it to see if it’s workable or not: I have a case where I am adding new rows to table for an order form. The new row’s UI will vary depending on the type of product being added, and after the new row is added, additional fields might be dynamically added to the row depending on other selections. My question is, is it possible/feasible to use each row as a group and use have_fields_and_multi() in this case? Just trying to wrap my head around the best way to go about it.
Also, maybe WPAlchemy should have a forum or something, there’s a lot of nice info getting buried in the comments.
I’m adding a value to my custom post types (featured) using a checkbox:
the_field('featured'); ?>
<input type="checkbox" name="the_name(); ?>" value="1"get_the_value()) echo ' checked="checked"'; ?> style="float:left; margin-right:4px;" /> Featured
I’m pulling the posts with this conditional
if ($action_mb->get_the_value('featured'))
This seems to work with new posts of this type, but is not working reliably with posts that were already created. I wanted to see what was happening in the db, but I can’t find the metabox data. Does anyone have any ideas why this might be happening, and can you point me to where the data is stored? I would like to figure out why it’s happening without having to reenter the data, especially if I get a request for another filter when there’s much more data there.
@Wendy, metabox data is stored in
wp_postmeta
it is associated with the post_id.Thanks Dimas for the tips: your suggestions made me realise that I had a serious stupid mistake in my code: I was calling the WPAlchemy metabox outside a Loop! If I put it in a Loop, it’s fine and I can grab the stored data OK.
Out of interest, is there any way of calling it from outside a Loop?
@Matt, yes …
OK, I’m thoroughly confused now, LOL. That’s pretty much what I originally had, except I didn’t call
the_meta(post_id)
before I calledthe_value('my_val')
Is this why my template code didn’t work? (http://pastebin.com/bXZ9MfQn)
@Matt, you typically do not have to use
the_meta()
as wpalchemy is Loop aware, however there are instances where you may want to use it with apost_id
to explicitly get meta data for a specific post, such as outside the Loop.Right, I understand now 🙂 Thanks for your time and patience, I really appreciate it.
@Wendy the purpost of doing this
if ( get_post_type() = ‘my_post_type’ || is_admin() ) { include_once ‘metaboxes/my_post_type-spec.php’; }
it is to dont load that code for every single post in my site. If you have more than 2000 posts I believe that this will do a lot for performance.
@Dimas I also believe as @Rich Rodecker that a forum will make sense !!
Forums on the way … http://forums.farinspace.com … it’ll start off as a basic bbPress install and I’ll go from there.
hurray and +1 for a forum.
Hi Dimas,
For now I have a custom meta box installed with 3 fields in a group: date, time and location. It works great and is exactly what I had in mind 🙂 Only one opportunity:
Is it possible to have a query now where I can search for a specific date? So I would like to show all events on one date.
Dimas
Many thanks for your work that’s gone into this. Such a simple setup but allows for such powerful meta configurations.
Great work.
@Kathy
Any chance you can share your code for adding media buttons to TinyMCE fields, that you mentioned in WYSIWYG thread? Are they work with repeatable fields?
why dont you just use bbpress plugin for support area?
http://wordpress.org/extend/plugins/bbpress/
are u planning custom taxonomy as include/exclude option ?
Thanks
@Dylan
I am having a problem with MediaAccess when using it in a repeatable fields loop. Here is how the issue can be reproduced for me:
(1) Use the new field button to get a new uploading field (a.docopy-*)
(2) Then use the WP media pop-up to insert a file (the problem doesn’t happen if I manually put an image URL in the field)
Once I click ‘Insert File’ button from within the pop-up, something weird happens. The image URL gets copied to the field I want, but, it gets also inserted to every new field I create. So say, I created a new field and inserted the file http://bla.com/bla.png to it, now any new field I create gets automatically filled with the value http://bla.com/bla.png. Furthermore, when I save/update the page, the last field I created gets duplicated.
Looks like the ‘Insert File’ button inside the media pop-up sends the URL incorrectly..?
Damn it, @Dylan is the author of Geo Mashup plugin! I meant @Dimas.. I really should go to sleep!
i am trying save_action or save_filter with:
function mycb_save_action_func($meta,$post_id){
// Update post
$my_post = array();
$my_post['ID'] = $post_id;
$my_post['post_excerpt'] = $meta['example1'].$meta['example2'];
// Update the post into the database
wp_update_post( $my_post );
return $meta;
}
just trying to update post exceprt with meta data but getting this error:
Fatal error: Maximum function nesting level of ‘100’ reached, aborting!
how can i fix this?
This class is awesome, I use it in all of my projects. I just ran into a slight issue and was hoping someone might know the answer.
When you pull data into a metabox textarea is there a way to keep the formatting. For example, If I put 2 paragraphs into a field how do I keep it as 2 separate pagagraphs? Currently it just runs the text all together in one paragraph. Is there a way to keep it separate? I have a metabox that uses a text area for the user to enter their biography and it is quite possible they may enter more than one paragraph.
Thanks,
Melinda
@Melinda You might want to have a look at this function: http://codex.wordpress.org/Function_Reference/wpautop. It’s the one that WordPress uses to paragraphify (yep) the output of the main editor. I’ve found it to be quite useful.
@Caleb Thanks! That worked perfectly! Thanks for pointing that out it was exactly what I needed.
Hello,
is it possible to call the value of a metabox from another plugin or just in single.php, etc?
I need to write something in a wp_table using mysql depending of the value of a metabox created with wpalchemy. Where should I write my mysql command? In a plugin? functions.php?
Thanks
Hi Dimas
I’m using your awesome class again. I’ve created a meta for a custom post type that is a checkbox. The idea is that if the checkbox is selected, the post is featured and gets shown on the front page. I’m having trouble filtering the loop using the checkbox ‘featured’ meta. I need to show only the posts that have the checkbox selected.
Many many thanks in advance for any help with this one. I know you’re a busy man.
@Dimas – Have you considered extending the WPAlchemy functionality to allow for adding metaboxes to custom taxonomies? I’m looking for a way to allow the end user to upload and associate an image with a custom taxonomy and, given my familiarity with WPAlchemy, it would be great to put it to use.
@Jonathan Wold
I think there is a beta code for this, but still in early development stage. Look at ‘taxonomy’ branch under github plugin repository.
@Sam-
I am doing the featured thing with a checkbox.
On the home page, I have, within the loop:
$my_mb->the_meta();
if ($my_mb->get_the_value('featured'))
(do my listing here)
Does that make sense?
@Sam, take a look at WPAlchemy MetaBox: Data Storage Modes also.
@Dimas
I am having a problem with MediaAccess when using it in a repeatable fields loop. Here is how the issue can be reproduced for me:
(1) Use the new field button to get a new uploading field (a.docopy-*)
(2) Then use the WP media pop-up to insert a file (the problem doesn’t happen if I manually put an image URL in the field)
Once I click ‘Insert File’ button from within the pop-up, something weird happens. The image URL gets copied to the field I want, but, it gets also inserted to every new field I create. So say, I created a new field and inserted the file //PATH/bla.png to it, now any new field I create gets automatically filled with the value //PATH/bla.png. Furthermore, when I save/update the page, the last field I created gets always duplicated.
Looks like the ‘Insert File’ button inside the media pop-up sends the URL in an incorrect way..?
Hi @Wendy,
Many thanks for that – I’ll give it a shot. I think I may have been over complicating things.
@Dimas – also, thank you – I already have the storage mode set to single variables but I’ll have a scan through.
@Dimas @Wendy
Thanks guys! It worked a treat.
@dimas,
is there a method to count the number of records in a have_fields_and_multi loop?
Just wanted to stop in and say thanks for the help and for the amazing work you’ve done! Keep it up!
@kathy, currently there isnt and easy method for that, soon … you can use
get_the_value()
prior to going into the repeating loop and do a simplecount()
@Jonathan, thanks!
@Mamouneyya, I will have to investigate … additionally the MediaAccess may likely become obsolete with the release of wp 3.3 and its new media improvements, however I am not sure if the updates are only in the area of the uploader or also in the media management areas.
i did figure out a way to count. turns it was pretty simple after all
$test = $featured_metabox->get_the_value('slides');
echo count($test);
Thanks for creating such an awesome and (usually) user-friendly script! I’m figuring it out for the most part, however just ran into the same issue with repeating fields as Mike (from comment on October 19, 2011). I have a metabox for links that every time I save the post, an empty field is added to the group, even if I’ve deleted it. I’ve posted my meta.php file here: https://gist.github.com/1355397 if you wouldn’t mind taking a look.
@Kristen, try https://gist.github.com/1355419 … the main reason is that the select box always has a value, you must have a default blank value.
@Dimas, thanks for the quick and working solution! That fixed the issue with the empty link field.
Just out of curiosity, it possible to include/define more than one metabox in a [file]-spec.php file? Basically I want to have two separate metaboxes show within the same post-type. I have separate [file]-meta.php for each to define the templates and would like to not have to create separate [file]-spec.php files as well if that’s possible.
I played around with a couple options I thought would work, but can’t get the metaboxes to show up properly.
Thanks again!
@Kirsten, the [file]-spec.php file is just a guideline, it helps with organization, switching meta boxes on/off with include statements. If you want you can put several meta box definitions/specs in one file … remember, for each definition, the
id
should be different andtemplate
should point to its own [file]-meta.phpI may have spoken too soon with my “featured” checkbox behavior. It’s not always working to display posts if the box is checked. I am using array mode, maybe that’s the problem? I don’t understand why it works with certain posts and not with others, even after examining them in the db. I’ve changed the way I refer to the checkbox in the metabox and how I display it, and the same posts consistently display, while others, don’t.
So I’m using the code I referenced above to display:
$my_mb->the_meta();
if ($my_mb->get_the_value('featured'))
(do my listing here)
and here it is in the meta file:
$mb->the_field('featured'); ?>
<input type="checkbox" name="the_name(); ?>" value="featured"the_checkbox_state('featured'); ?>/> featured
When I look in the db, I always see featured in the array there after I set it, but it doesn’t always display on my page.
Any ideas?
IS it possible to use this for a custom taxonomy metabox?
Hi @Dimas, I have a question about ‘have_fields_and_multi’ and MediaAccess.
I’ve set up a custom metabox that uses MediaAccess and ‘have_fields_and_multi’ to allow adding ‘unlimited’ images. However, when you insert one image it duplicates the url into all the other text boxes as well.
Here’s my code: http://pastebin.com/CCVKysE6
Any suggestions, thanks?
Apologies, you’ve already answered the question here: http://www.farinspace.com/wordpress-media-uploader-integration/
Thanks 🙂
@Matt
Could you please direct me to the mentioned answer? Because I’m having the same issue and I don’t see any related comment in the mentioned thread.
Hi @Mamouneyya. Click on the link in my comment above and then scroll down to the bit titled ‘Using MediaAccess Field/Button with MetaBox Repeating Fields Functionality’. Under this there’s a video guide and some code that should do exactly what you need. Hope that helps 🙂
Thanks Matt. Looks like I misunderstood your issue. I have already used the code in that thread, but I had a strange problem so that everytime I insert a file in a repeatable field it gets inserted in every field I add later. Also that was causing in a duplicated file at the last after updating the post, because of the value being always in the .tocopy hidden field.
Anyway, @Dimas, looked like I could solve this issue, which I already reported in comment#18820. It seems that the group name in setGroupName() should end with ‘-n’ or maybe ‘-[LETTER]’? I don’t know but I was using names ending with ‘-‘ and even ‘file’ and they both caused the issue I described. Now I tried to end it with ‘-n’ and it suddenly works!
God, we really need a forum!
@Dimas
It looks like that the class doesn’t delete the DB entry when deleting a field in a repeatable fields loop.. is that an intended behavior or what? I find it really bad, and will make a huge mess to the DB. Also, it makes the way mentioned here to count the number of fields useless:
Hi Dimas,
I’m having problem when showing the fields in the posts loop.
I call the function $custom_metabox->the_value(‘my_field’); inside the loop and it’s seems all my posts display the same result for the custom field value eventhough each posts has different “my_field” value. Any workaround for this issue, please ?
@Dimas
I’m just beginning coding for a site that is going to be using WPAlchemy quite a bit, and wondered if you can elaborate in any way how WPAlchemy and MediaAccess will/may change with wp 3.3?
Thanks!
Frances
@frances, WPAlchemy will continue to be supported as wordpress changes, eventually WordPress may integrate a more simplified way to create metaboxes, and WPAlchemy will always try to use the tools available within WordPress. However I don’t think the core would support all of the features that WPAlchemy has, deferring to plugins to add such additions.
From what I hear, there are going to be some changes with the WordPress media management … however I am still unclear on whether it’s just a new media uploader that is getting added vs an entire concept/management change, hence the MediaAccess class may become obsolete or more likely will change as a result.
@Mamouneyya, WPAlchemy tries very hard to keep all the data clean, removing unused values, so ill have to investigate what you are seeing, please file a bug on github with steps to reproduce what you are seeing.
@Dimas,
thanks for your quick reply. I’ve had a very quick play with the 3.3b3 — not using WPAlchemy with it yet though.
I’m just checking in on my question/problem from 11/10. My “featured content” (depending on a checkbox) is still not displaying consistently, and it’s always the same posts that don’t appear as expected.
@Sam, is your display featured content using a checkbox working consistently every time? I am banging my head on this one! Any help would be greatly appreciated, as I’ve tried everything I can think of, and don’t understand why these posts aren’t displaying when I’m seeing the expected values in the db…
I may just be forgetting to do something within the loop, but not sure why it’s always the same posts that aren’t displaying… I even did a “find differences” on 2 records from the db, one that worked and one that didn’t, they both have the “featured” field, and the only difference I’m seeing is unrelated content within the array.
apologies if I’ve already posted this. I would also like for admin to be able to check another box for separating out a different set of posts so want to make sure this is working properly.
Thanks!
Wendy
Media Uploads with Image Previews and Repeating Fields
Every so often I have a need to implement MediaAccess with preview images and repeating fields for clients. That time has come again, and this time I thought I’d share exactly how I do it. This is almost exactly the same code I use in my Folio Buddy plugin that is very popular with Photographers, so it has been thoroughly tested in real-world environments.
First, a caveat: I do not have time to offer support on this. I’m really sorry about that, but my time is truly at a premium right now. I am providing it as-is in hopes it is useful to others, and/or that it may be taken and developed even further.
There are three parts to this:
1. The code that is to be copied into your metabox template and tweaked to suit your needs.
2. The code that has to be hacked/added in to the MediaAccess.php file from WPAlchemy to allow for the grabbing of attachment IDs (URLs alone are not near as useful, IMO) and to set up AJAX to insert the preview image.
3. The code that needs to be added to your functions.php (or equivalent) file to handle WPAlchemy setup, AJAX callbacks to WordPress, and a utility function that I borrowed form somewhere (don’t remember the original source now) to make sure “Insert Media” buttons are always visible in the media manager popup.
Here you go:
http://pastie.org/2878298
(Hopefully I haven’t forgotten anything!)
Cheers.
Dameian
i am trying to hide metaboxes in a theme with condition but its not working for some reason
here is my code.
if($disable != “true”){
$custom_metabox = new WPAlchemy_MetaBox(array
(
‘id’ => ‘_custom_meta’,
‘title’ => ‘Custom Options’,
‘template’ => STYLESHEETPATH . ‘/functions/WPAlchemy/simple-meta.php’,
‘types’ => array(‘page’,’post’)
));
}
any ideas..
How do you get checkboxes in repeatable groups to display in a template properly? I can only get “Array” to display when there’s more than one checkbox checked. Posted about it here http://wordpress.stackexchange.com/questions/34610/wpalchemy-checkboxes
@Dameian, or anyone trying to use @Dameian’s code provided just above.. There’s several things he left out and/or were wrong in the code. I just spent a few hours fumbling around trying to make it work..
1. In his code snippet’s he’s using $wpo_metabox_media as the meta-box name, but he switches to $wpo_sponsor_metabox_media for some reason, change these references to the $wpo_metabox_media. That will help with most of the issues.
2. Don’t forget you have to include the MediaAccess.php class, this isn’t done by default in the wpalchemy setup package.
3. Where it sets up the group he’s put “PUT_A_UNIQUE_NAME_HERE” in the setGroupName, what he really means is “use your “have_fields_and_multi” name as the group name.
4. And Finally {i think} in the add/edit/delete etc buttons ALSO “use your “have_fields_and_multi” name in the class.
Hope that helps someone else save time. and Thanks Dameian for the start, a little clean tutorial next tho’ eh’? 🙂
Is it possible to set the default values for metaboxes? Sorry if it was such question already, googled a lot and didn’t found anything.
Thanks!
@Denoizzed, there is a gotcha here, if you are using repeating fields it is best not to have default values and or invert the question associated with the checkbox.
Just had to say thanks. This is the MOST useful thing ever made, better than the wheel 🙂
Dear Dimas
WPAlchemy is a wonderful program. I was also able to install easily.
A database is also smart.
Very Thanks!
There is a wish, submit a new post from outside the WordPress Admin panel. I can use the tag “wp_insert_post” & “add_post_meta”.
Since table structure is different, is it impossible?
Are there any good methods?
Kind regards,
Thanks a lot for your work on this class. With Media Access this is perfect. Not sure if I should post here or in the forum I have seen been mentioned.
Have added functionality to grab attachment id from images, and other files in a ajax call. In addition to other information of the attachment. Have tried to make a simple way to let users edit this information similar to how you can edit images in the editor and this is what I have so far. Maybe it’s useful for some, so Ill share my current solution. Only tested locally so might not be a good solution.
http://pastie.org/2943850
is there any chance to use wpalchemy for site settings? in option pages?
@Ünsal, my next release of my Sidekick plugin will be needing a options page for adding settings/options. I think I will be tackling that area next, it will be using the MetaBox class or it’ll be a class of its own. I need to explore the
do_meta_boxes
hook in wordpress more.Hello! Is it possible to add multiple metaboxes and retrieve all fields in my theme from a specific metabox?
@vi, yes, see the examples included, each metabox is named uniquely which allows you to target specific ones.
Dimas..
I need to use http://wordpress.org/extend/plugins/wordpress-mu-sitewide-tags/ and for some reason wpalchemy creates post meta on tags blog too. Normally its good but i dont want all post meta data copies to other place because there will be probably 100k+ post from multisite and i am using WPALCHEMY_MODE_EXTRACT so each post have 20~ Post Meta. But i only need 2 of those Post Meta in that tags blog which i can set from settings in http://wordpress.org/extend/plugins/wordpress-mu-sitewide-tags/ option page. But if i set in there, saves double times same post meta :-/
How can i prevent wpalchemy saving post meta to tags blog? (I can edit that plugin if need)
@Ünsal, you should be able to limit where the metabox get displayed/used by using the include/exclude options or using the “output_filter” callback or by using your own custom if/else statement.
Hi,Dimas.
First of all, please let me appreciate from the bottom of your heart.
This plug-in is very wonderful. Please let me ask a question one.
when the custom-made field of a picture is used within a custom post type, media-up-loader does not operate well.
please let me know how to solve it.
script blow.
—-metabox.php
the_field(‘imgurl’);
$wpalchemy_media_access->setGroupName(‘nn’)->setInsertButtonLabel(‘insert’);
?>
pictuer
getField(array(‘name’ => $mb->get_the_name(), ‘value’ => $mb->get_the_value())); ?>
getButton(); ?>
—-setup.php
‘_custom_meta’,
‘title’ => ‘picture’,
‘template’ => get_stylesheet_directory() . ‘/metaboxes/metabox.php’,
‘types’ => array(‘xxxx’),
‘mode’ => WPALCHEMY_MODE_EXTRACT
));
?>
Hi Dimas,
Within a ‘have_fields_and_multi’ group i have a select box with the following code:
http://pastebin.com/wVACCXqn
I want to be able to have the first option selected (+) rather than having a blank option and then the user has to select the desired option.. ive tried the following but this somehow causes issues and duplicates the group.
http://pastebin.com/d5WdMn8W
Any ideas?
Kind Regards
@MattStrange, its a current shortcoming (which I will try to resolve with the next release) of using a preset value with I believe any field type within a repeating field group. You could use the “save_filter” to remove the last value which you know is blank.
Hi Dimas,
first of all, let me thank you for all the work you put in this. It’s well appreciated and it seems really helpful.
However, I’m in trouble setting this up. I’ve just downloaded WP3.2.1 and followed your video tut, but the meta box doesn’t appear on the Edit Post screen. I’ve checked on all the directories and links. Does this work for the latest WP version?
Hoping for your help. Thanks again 🙂
never mind my previous post. found the solution. and thanks again for this great blog!
Hello Dimas,
is it possible to call a meta from the content of the post with a shortcode or something similar?
Thanks
Hi,
Great job! Really usefull to customize wp!
I’m wondering if it would be possible to repeat a repeatable bloc.
I took a look at the core class and it seems not 🙂
Anyway thanks for the piece of code and have a great day!
Yassin
If I have multiple metabox panels can I display all the values of a single metabox group in my theme?
Hi Dimas,
Really enjoying working with this class, 🙂
I looked through the previous comments and found out how to use the jquery datepicker for the repeating group fields, please take a look at the following code, the first code at pastie seems to work but for the first field only.
http://pastie.org/3008196
I then tried to bind the jquery with wpa_copy but this fails, notice the change in the jQuery…
http://pastie.org/3008214
Really not sure what i’m doing wrong 🙁
Kind Regards
WP 3.3 is out! with this awesome new API:
http://codex.wordpress.org/Function_Reference/wp_editor
@Dimas A great time to cleanly add support for WYSIWYG fields 😉
Hi Dimas,
Since I updated to WP 3.3, I have this error message:
Notice: wp_enqueue_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or init hooks. Please see Debugging in WordPress for more information.
When I “deactivate” WPalchemy everything works fine :-/ I see it only when I have WP_DEBUG “on”… Tried it on different installs, different themes using WPalchemy and I have the same problem. No feedback about that problem ??
@Francis, this stems from the meta box css include code prior to initializing a meta box using WPAlchemy. I’ve adjusted the documentation above, the correct way should be:
@Mamouneyya, I will look into it.
@MattStrange, at a glance it looks like you are doing it correctly … make sure that the targeting with “the_clone” is working correctly, proper targeting is everything.
the code you have in your video to show the meta info on a template isnt working. its not displaying anything not even if i add print_r
@eli, not sure how to help you unless you provide your code, use http://gist.github.com and post your code snippet. From your description, although vague, perhaps you need to use
global
.@eli,
using the words “hello”, “please” and “thanks” might also help….
+1 @antonio!
@eli : standard operating procedure when you want tech help from someone should include what you are trying to do, what you have tried (code examples) and what errors you are seeing instead of what you expect. and a little politeness goes a long way… especially when all the code AND help is given free of charge.
Thanks Dimas, it worked perfectly well 🙂
I have another question for you: How can I display embedded videos using metaboxes ? I saw that you integrated the [embed] shortcode but don’t really know how to use it. :-/
Thanks for your help 🙂
@Francis, its not that wpalchemy integrates with the [embed] shortcode, it just handles it better than what it did, handles shortcodes better … see the embed documentation it might shed some more light on the matter.
Thanks Dimas. Unfortunately, I went already on that page, tried everything but can’t make it work. It always display the URL of the video but not the video itself. I tried [embed]URL[/embed] but still does not work. Here is my problem. Don’t know how to get the right code to display these videos ^^
@Francis, if you are using
$mb->the_value()
or$mb->get_the_value()
then the shortcodes are automagically handled for you … however if you are getting an array, and then doing your own looping, you would than have to usedo_shortcode( CONTENT_WITH_SHORTCODES )
to render out the content with shortcodes. If you are interested, the relevant code in wpalchemy is on lines 1669-1689 in MetaBox.php (which may shed some more light on things).My code is really simple but I only get the URL:
the_meta();
?>
have_fields('vids')) {
?>
the_value('videourl'); ?>
I am sure I forget something simple but can’t get it ^^
@Francis, try http://gist.github.com … much better for posting code and editable by anyone trying to assist. I’ll adjust your comment above when you post.
Sorry about that, here is my code: https://gist.github.com/1477638
Cheers,
Hi Dimas,
Ive been playing around with the jQuery Datepicker and WPAlchemy but still having problems getting it to work 🙁
I thought maybe the jQuery was conflicting with my other plugins so i started a fresh install of WordPress 3.3 and created a very minimum theme to test the datepicker in the custom fields, still doesn’t work and i’m lost for ideas.
If your not too busy could you take a peak at the source files:
http://www.lifeofstrange.com/demotheme.zip
If anybody has a solution for this i would be grateful for your response.
Kind Regards
Matt
Conditional Syntax for beginner
—
Can anyone help me with code for my template that will replace what I already have for custom fields? I have it pasted below, basically the theme finds if there is an entry for the custom field and then outputs everything after the last line. I would like to do that but with the custom meta boxes.
Here is the code to replace:
ID, "Link", true))) {
echo '
Link
ID, "Link", true);
echo '" target="blank">';
echo 'Visit this link →';
echo '';}?>
@Francis, you can try something like: https://gist.github.com/1491041
Hi Dimas,
I tried with this code but does not work neither. I searched on the web and it seems that do_shortcode does not work [embed] outside of the post editor:
http://www.deluxeblogtips.com/2011/11/show-youtube-video-outside-post.html
I tried then with wp_oembed_get(). I did a example with a real YouTube URL and it worked but when I try to implement WPalchemy code, it does not work :-/
https://gist.github.com/1493993
Hi Dimas,
Thanks again for the amazing WPAlchemy!
I’ve got a quick question regarding conditional statements. What I’m trying to do is this:
In a multi field, setup a field with select options. Depending on which option is chosen, I’d like to be able to show certain types of content. This is how I have it outputted at the moment:
the_meta(); while($highlevelcolumns_metabox->have_fields(‘columns’)) { ?>
get_the_value(‘twocolumnrow’)) { ?>
/* Conditional Content Shows Up */
get_the_value(‘threecolumnrow’)) { ?>
/* Conditional Content Shows Up */
And so on for a few more options.. Here’s the back-end code:
have_fields_and_multi(‘columns’)): ?>
the_group_open(); ?>
Select Column Type:
the_field(‘columntype’); ?>
<select name="the_name(); ?>”>
Select…
<option value="twocolumnrow"the_select_state(‘twocolumnrow’); ?>>Two Column
<option value="threecolumnrow"the_select_state(‘threecolumnrow’); ?>>Three Column
<option value="fourcolumnrow"the_select_state(‘fourcolumnrow’); ?>>Four Column
<option value="sixcolumnrow"the_select_state(‘sixcolumnrow’); ?>>Six Column
Remove Document
the_group_close(); ?>
If you have any thoughts that would be great! I’m sure it’s an easy fix but I’m going crazy trying to figure this out!
Hi Dimas,
It works now, I had to use get_the_value and not only the_value.
Thanks for your help 🙂
I will simplify my question. I want to use the wpalchemy-metabox instead of custom fields. Right now I have the following code:
?php if((get_post_meta($post->ID, "Link", true))) {
echo (THE CONDITIONAL CONTENT)')...
I would like to replace this, but how can I? Let’s say I am using the ‘title’ metabox from the example given. Can someone tell me how to implement that into my theme as done above (conditionally)?
Hello!
Firstly, thank you for your hard work. The code is great and works like a charm. I’m just having some problems with the output. I made a custom query to make a loop that shows only posts with a specific meta value. It works when i use the simple custom field solution, but i care about the user experience so i’m using you code. The problem is that it output something like “a:1:{s:9:”EventDate”;s:10:”19/12/2011″;}” and my query can’t find it =[. Have any ideia that could help me?
Thank you
Eduardo, you could use WP_ALCHEMY_MODE_EXTRACT to store the values as unique custom fields instead of bundling them. I guess this is the only way to be able to query for posts by meta_value.
Another way would be to create a save filter which stores the value into a unique field, but it makes only sense if you have a metabox with many fields and you don’t want to store all values into unique fields.
thx @Basti … @Eduardo, see WPAlchemy MetaBox: Data Storage Modes
any thought of integrating your excellent class with what will be coming in wordpress 3.4? http://core.trac.wordpress.org/ticket/18179
I’m guessing that your class might be overkill, but at least it can inform the new WP_Meta_Box class in development, because your class is the most mature one out there. Or even better, a stripped down version of your class can become the backbone of the new class. like woo menus did for the menu system.
Hi there,
I was wondering if it is possible to create a repeatable meta-box like you see in this video: http://www.screenr.com/a17s [starts at about 40 seconds]. If so, any suggestions on how?
Thanks,
Moshe
I am working on a very similar issue as @MattStrange, I am trying to dynamically add fields with jquery datepicker (and another field filtering out non-numbers) but the problem seems to be that the script is only run on the first fields not the dynamically generated ones. Any ideas how I might overcome this issue?
Thanks again for such a wonderful script and for your help last month. I’m working on another part of my site and am attempting to implement a repeatable dropdown/select field using WPAlchemy. I can get the repeatable fields to function and save properly when I hard-code the select options (https://gist.github.com/1561986). However, when I try to generate the options using a WPQuery, the repeatable fields function properly within the admin (i.e. I can see the dropdowns and can add new fields) however they are not saving when I update the post. I’ve posted the non-working code for my meta.php here: https://gist.github.com/1561943
Not sure where to start investigating what might be causing this, so appreciate any pointers you might have.
Thanks!
Hi Dimas,
I think you mentioned a couple of months ago that you were working on nested repeating fields (i.e. a repeating field in a repeating field) – but I can’t find the comment now. Will you be adding this to WPAlchemy, or may I request this?
Also, with MediaAccess, is there a way to get more than just the URL? For example, if you have an image with a caption, it wraps the image and link in the ‘caption’ shortcode. Is it possible to grab that data?
Ciao,
Frances
I also just noticed a rather strange behavior when I try to display items from a repeating field metabox. I have a grouped set of links (with a url and title field) and it appears that the first item (in this case a website link) does not display, but all of the other items in the array do. If I enter test data where I have Link One and Link Two, the list of links will start with Link Two and Link One is nowhere to be found!
I’ve tried changing the mode to both EXTRACT or ARRAY or none, but that did not fix the issue. I’ve also tried copying the exact code that you list above for
have_fields_and_multi
in case I’d changed something when I customized the code, but, again, no luck.using WPALCHEMY_MODE_EXTRACT and it works fine if I add value from the meta box field but If I add from a custom field its not showing in the meta box. any help? thanks
First….awesome job! Second, I was curious if I was perhaps doing something wrong using the MetaBox with a custom template. It appears that the metabox only shows if the template is changed, then saved/updated. I *thought* I had purchased a theme at one point where this appeared/disappeared when the template was changed.
Ideally it would be great (provided I’m not doing something wrong) to have the metabox appear/disappear based upon which template is selected in the drop down without having to save/update.
Doug.
I have solved my issue of adding script to dynamically rendered fields by using .live (which I realize there are better methods, but I will look into that later.)
http://pastebin.com/UZXpf4LX
Now that I have all my repeating fields working properly I am working on a way to cherry pick data from each set of repeating fields.
Basically the admin can add tracks to my CPT ‘Album’ and I want my sidebar widget to show 1 track and some of its associated information from 1 album randomly.
In one of the video walkthrough Dimas mentions possibly adding a way to use MODE_EXTRACT on secondary tiers, but I don’t think that has made it in yet. Has it?
Any ideas are greatly appreciated!
Update: So I solved my issue of cherry picking fields of data by using jQuery to apply a count to all the divs labeled “trackInfo” and then randomly pull all the output inside those divs. (essentially)
This is a quick solution for me and won’t really effect the site much as there would never be more than 20 tracks to choose from, but realistically I would prefer a server side solution, more to the point, if WPALCHEMY_MODE_EXTRACT worked on secondary fields it would be much more effective than a JS solution.
@brokenflipside, I am not sure exactly what you are trying to do, but, perhaps an ajax solution … where you can randomly return data about a single album/track (with repeating fields you would still get track info as an array) … however if you already have that data on the page, using js is probably the way to go since you are not making another server call.
@Dimas, my custom post type is Albums.
Each album has my custom metabox (using your fantabulous class) to add the albums’ tracks. Each row includes 5 fields. This is the group.
I want to be able to grab 1 track and some of the corresponding info to display in a widget.
I accomplished this by loading all the tracks on every page refresh in a hidden div, then using jQuery grab the appropriate information and display a random set.
Using ajax would certainly do the trick, of course I would have to determine how to parse the array to only grab 1 track at a time.
You mentioned in your wpalchemy-metabox-data-storage-modes video that in the future you might add the ability to apply
WPALCHEMY_MODE_EXTRACT
to secondary tiered data, which I took to mean giving fields insidehave_fields_and_multi
they’re own set of data/metakey without grouping it all in a serial array.Does that make anymore sense? None the less I have a working solution, if anyone needs info (assuming that made sense, just ask!)
Hey.. First thing. thanks a lot – i love alchemy!! 🙂
Got a little problem… When ever i use this:
$clients->the_value('client_url')
i get the text value – no echo needed….
how can i assign that to a variable.
when i try to do this:
$var = $clients->the_value('client_url');
it still get echoed on screen.
@sagive you’ll want to us
get_the_value();
instead ofthe_value();
in order to have it store the value instead of echoing.of course 🙂 – thanks @Kirsten
How can I dynamically replace ‘a’, ‘b’, ‘c’ in the array with the titles of a post type?
have_fields(‘cb_ex’, count($items))): ?>
get_the_index()]; ?>
<input type="checkbox" name="the_name(); ?>” value=””the_checkbox_state($item); ?>/>
@Dimas Here is a problem I am running into and I just cannot seem to get my head around it. I want to create a repeatable WP rich text editor using WPAlchemy but when I add a new editor it looks fine but I cannot click in the ‘textarea’ and add text. If I refresh or click Update on the page the new editor disappears. Here is my code:
You can see I am using the new ‘wp_editor()’ function in WP 3.3. Maybe I need to be doing it a different way. Any thoughts or suggestions? Thanks.
@dimas or @anyone! Help! I have not modified the class AT ALL and I am getting this error when I migrate to the live server:
Fatal error: Cannot use string offset as an array in /MetaBox.php on line 1637
@Brokenflipside, this is a new one … I assume you are using the latest version on github … when do you get this error? try using screenr.com and show me.
@dimas ok, whew I over reacted for a second. After a breath I began investigating at a more macro scale and realized the error was directly related to my importing of the old servers post data through standard import option.
I will recreate the scenario tomorrow and post specifics. Yes I am using the most recent version. The error was being thrown whenever data from the dynamically rendered fields was being called. Though come to think of it all my data that is not from a dynamically rendered set of fields is not using wpalchemy…
@dimas ok, whew I over reacted for a second. After a breath I began investigating at a more macro scale and realized the error was directly related to my importing of the old servers post data through standard import option.
I deleted the imported data and started fresh, everything worked fine from here on out.
I will recreate the scenario tomorrow and post specifics. Yes I am using the most recent version. The error was being thrown whenever data from the dynamically rendered fields was being called. Though come to think of it all my data that is not from a dynamically rendered set of fields is not using wpalchemy…
@Dimas : please switch to google group (or something alike) and close the comments here, each time I’m looking for some infos I’m loosing so much time getting my hands back on it. Setting up a google group is easy and I’m sure I’m not the only one who would like to see that happen.
Also, why don’t you use the wiki on github for documentation so everyone can contribute with code example and share their use cases ?
If you want any help let me know, I’d be glad to help but You are the one in charge here 😉
Bests.
@Jonathan, I’ve been delayed a bit, but new site + forums launching this weekend … I have thought about moving docs to github.
To start i will be closing comments for this page, I will try to review all comments and get the useful ones into a forum topic/thread.
@Dimas, you are the man ! Looking forward to see this 🙂
Thanks for your time !
@Dimas, first off, thanks for a great plugin – it has revolutionised my custom posts.
A question for which I can’t seem to find the answer: how do I access WPAlchemy’s meta data to use in a WP_Query?
I have an events post type and want to select or exclude and order posts based on their start date, which is captured via an input:text form type in the post type’s metabox.
Any suggestions or perhaps a pointer to where to find a doc about this?
Thanks for your hard work.
Hi Dimas – I found the answer – apologies for wasting your time. When you sit coding and researching at midnight after 3 hours of sleep the night before, things sometimes seem impossible to find.
After doing a site:farinspace.com wp_query search, I found
http://www.farinspace.com/wpalchemy-metabox-data-storage-modes/
It has solved my problems, thank you very much 🙂
@dimas or @anyone Does anyone know how to get a thumbnail of the image you selected to show up in your metabox? I have integrated the wordpress media uploader to select images for a gallery and I want a thumbnail of each image to display so the client can easily reorder the images using the sorting method for metaboxes that was shown on this site. I just can’t seem to figure out how get the thumbnail to display.
Your help is greatly appreciated!
This is what I did to show a thumbnail of the image selected:
I added this line to my metabox php file.
<img src="get_the_value(); ?>” style=”width:100px;height:100px” />
That will show thumbnails for all boxes to make it easy to reorder, and it works fine.
The only issue is that you have to update the post before you can see the image, I don’t know how to show the image as soon as its selected, I think its Ajax that can have this done. Is its possible to get help on this.
Hi,
I’ve been playing around with this and I think I seem to grasp it (noob of a coder), but I wanted to know. How would I pull the data from my meta boxes in to the admin columns when viewing all CPT’s?
Comments are officially closed!