Add meta box to WordPress options page - wordpress

How can I add a (draggable) meta box to an options page for a plugin I created? Is this even possible? Because if I look in the docs I see that I can only add it to a 'post', 'page', 'link', or 'custom_post_type'.

Yes it's possible. The code in your previous question was correct but it misses something important or you haven't added that code to the question.
Here is a demo plugin that can help you get it working.
This Plugin demonstrates how you can build your own plugin pages using the WordPress provided draggable metaboxes, requires WordPress 2.7 version, supports WordPress 2.8 changed boxing layout engine
The basic code from the demo plugin is the following. Note that in the full exemple the side meta boxes are not working nor the two columns layout as it was written for WordPress 2.8 and current version is almost 5.0.
// Source code by Frank Bueltge at gist.github.com/bueltge/757903
class howto_metabox_plugin {
function howto_metabox_plugin() {
add_action('admin_menu', array($this, 'on_admin_menu'));
add_action('admin_post_save_howto_metaboxes_general', array($this, 'on_save_changes'));
}
function on_admin_menu() {
$this->pagehook = add_options_page('Howto Metabox Page Title', "HowTo Metaboxes", 'manage_options', 'howto_metaboxes', array($this, 'on_show_page'));
add_action('load-'.$this->pagehook, array($this, 'on_load_page'));
}
function on_load_page() {
wp_enqueue_script('common');
wp_enqueue_script('wp-lists');
wp_enqueue_script('postbox');
add_meta_box('howto-metaboxes-contentbox-2', 'Contentbox 2 Title', array($this, 'on_contentbox_2_content'), $this->pagehook, 'normal', 'core');
add_meta_box('howto-metaboxes-contentbox-additional-1', 'Contentbox Additional 1 Title', array($this, 'on_contentbox_additional_1_content'), $this->pagehook, 'additional', 'core');
}
function on_show_page() {
//define some data can be given to each metabox during rendering
$data = array('My Data 1', 'My Data 2', 'Available Data 1');
?>
<div id="howto-metaboxes-general" class="wrap">
<?php screen_icon('options-general'); ?>
<h2>Metabox Showcase Plugin Page</h2>
<form action="admin-post.php" method="post">
<?php wp_nonce_field('howto-metaboxes-general'); ?>
<input type="hidden" name="action" value="save_howto_metaboxes_general" />
<div id="poststuff" class="metabox-holder">
<div id="side-info-column" class="inner-sidebar">
<?php do_meta_boxes($this->pagehook, 'side', $data); ?>
</div>
<div id="post-body" class="has-sidebar">
<div id="post-body-content" class="has-sidebar-content">
<?php do_meta_boxes($this->pagehook, 'normal', $data); ?>
<?php do_meta_boxes($this->pagehook, 'additional', $data); ?>
<p>
<input type="submit" value="Save Changes" class="button-primary" name="Submit"/>
</p>
</div>
</div>
<br class="clear"/>
</div>
</form>
</div>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready( function($) {
// close postboxes that should be closed
$('.if-js-closed').removeClass('if-js-closed').addClass('closed');
// postboxes setup
postboxes.add_postbox_toggles('<?php echo $this->pagehook; ?>');
});
//]]>
</script>
<?php
}
function on_save_changes() {
if ( !current_user_can('manage_options') )
wp_die( __('Cheatin’ uh?') );
check_admin_referer('howto-metaboxes-general');
//process here your on $_POST validation and / or option saving
//lets redirect the post request into get request (you may add additional params at the url, if you need to show save results
wp_redirect($_POST['_wp_http_referer']);
}
function on_contentbox_2_content($data) {
sort($data);
?>
<p>The given parameter at <b>reverse sorted</b> order are: <em><?php echo implode(' | ', array_reverse($data)); ?></em></p>
<?php
}
function on_contentbox_additional_1_content($data) {
?>
<p>This and the 2nd <em>additional</em> box will be addressed by an other group identifier to render it by calling with this dedicated name.</p>
<p>You can have as much as needed box groups.</p>
<?php
}
}
$my_howto_metabox_plugin = new howto_metabox_plugin();

Related

Wordpress access registered setting on custom template

I have created a plugin and registered a new setting there.
class WordCountAndTimePlugin{
function __construct()
{
add_action('admin_menu', array($this, 'adminPage'));
add_action('admin_init', array($this, 'settings'));
}
function settings(){
add_settings_section('wcp_first_section', null, null, 'word-count-settings-page');
add_settings_field('wcp_headline', 'Headline Text', array(
$this, 'headlineHTML'
), 'word-count-settings-page', 'wcp_first_section');
register_setting('wordcountplugin', 'wcp_headline', array(
'sanitize_callback' => 'sanitize_text_field',
'default' => 'Post Statistics'
));
}
function headlineHTML(){?>
<input type="text" name="wcp_headline" value="<?php echo esc_attr(get_option('wcp_headline')) ?>">
<?php }
function adminPage(){
add_options_page('Word Count Settings', __('Word Count', 'wcpdomain'), 'manage_options', 'word-count-settings-page',
array($this, 'ourHTML'));
}
function ourHTML(){ ?>
<div class="wrap">
<h1>
Word Count Settings
</h1>
<form action="options.php" method="POST">
<?php
settings_fields('wordcountplugin');
do_settings_sections('word-count-settings-page');
submit_button();
?>
</form>
</div>
<?php }
}
$wordCountAndTimePlugin = new WordCountAndTimePlugin();
This plugin creates a setting in worpress menu.
And create a page to save this setting in a setting table.
I have added a custom page template for WordPress. And what I need is to access this wcp_headline value inside.
<?php
/* Template Name: My Template */
// need to call it here
?>
Is there a way to call this wcp_headline value inside this template?
You can use the get_option function like you used it in your plugin:
$wcp_headline = esc_attr(get_option('wcp_headline'));
The $wcp_headline variable can then be used anywhere in your theme file.

Show woocommerce errors

I have a woocommerce store and want to show wocommerce error messages in specific place of my theme, for example under submit button.
I know wocommerce error messages come from here:
<ul class="woocommerce-error">
<?php foreach ( $messages as $message ) : ?>
<li><?php echo wp_kses_post( $message ); ?></li>
<?php endforeach; ?>
</ul>
But, when i put this code in my page (for example edit-my-address.php page), its giving error!
What is working or simple code for showing messages in woocommerce?
Thanks in advance.
you can use both methods here..
woocommerce_show_messages();
wc_print_notices();
You can also show woocommerce custom notices according to your condition like...
wc_add_notice( 'This is a Success notice', 'success' );
wc_add_notice( 'This is a Error notice', 'error' );
wc_add_notice( 'This is a \'Notice\' notice\'', 'notice' );
You can add this piece of code to functions.php of your child theme
add_shortcode('woocommerce_notices', function($attrs) {
if (wc_notice_count() > 0) {
?>
<div class="woocommerce-notices-shortcode woocommerce">
<?php wc_print_notices(); ?>
</div>
<?php
}
});
And then use it as a shortcode [woocommerce_notices] in any desired post or page, or use <?php echo do_shortcode('[name_of_shortcode]'); ?> in a desired PHP template.
Tested and works. Good luck.
A bit late to the party but here is a solution.
Try to use the following piece of code (taken from the original file here: wp-content/plugins/woocommerce/templates/single-product.php)
<?php
/**
* woocommerce_before_main_content hook.
*
* #hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content)
* #hooked woocommerce_breadcrumb - 20
*/
do_action( 'woocommerce_before_main_content' );
?>
Hope it helps
you missed to add this line of code:
<?php wc_print_notices(); ?>
Add this to your functions.php file inside your child theme (or main theme if there is no child).
add_shortcode('woocommerce_notices', function($attrs) {
if (function_exists('wc_notice_count') && wc_notice_count() > 0) {
?>
<div class="woocommerce-notices-shortcode">
<?php wc_print_notices(); ?>
</div>
<script>
(function($) {
$(window).on("load", function(){
// You can execute some js here
});
})(jQuery);
</script>
<?php
// You can execute some php here
wc_clear_notices();
}
});
Then add a shortcode to your page as:
[woocommerce_notices]
The notices and the code will get executed wherever you paste the shortcode.

Browsing custom taxonomy terms on WordPress

I ran into a little problem and I might need your help to sort it out.
I an building a website that uses custom taxonomies and tags posts accordingly. So, there is a page like http://example.com/custom-taxonomy/term that displays all the posts tagged with "term".
The visitor should be able to go to http://example.com/custom-taxonomy/ and see a lists of all the terms that are used inside that custom taxonomy in order to browse them. This list should also be "paginated" since some taxonomies could have quite a lot of terms in them.
Any ideas on how I should handle this?
Thanks a bunch!
I'll answer my own question here, maybe it will help others.
I have created a custom page template that uses get_terms to get the terms for a specific taxonomy and iterates through them displaying them in the desired manner.
I then created a page with the exact same slug as the main taxonomy slug (http://example.com/actors in this case) and thus when going to /actors/ you actually see the page created that acts as an index page for the taxonomy. You can see it in effect at http://couch.ro/actori/
In the actual code I am also using the Taxonomy Images plugin for having images on the actual tags so the get_terms is executed through the apply_filter() function. You have the full code for the template below. Any feedback is highly appreciated!
<?php
/*
Template Name: Taxonomy Index
*/
$slug_to_taxonomy=array('actori'=>'actor','regizori'=>'director');
$terms_per_page=get_option( 'c2c_custom_post_limits' );
if ($terms_per_page['archives_limit']==0)
{
$terms_per_page=get_options('posts_per_page');
}
else
{
$terms_per_page=$terms_per_page['archives_limit'];
}
$slug=$post->post_name;
if (!isset($slug_to_taxonomy[$slug]))
{
header("Location: /");exit;
}
else
{
$taxonomy=$slug_to_taxonomy[$slug];
}
$terms_page=get_query_var('paged');
if (empty($terms_page))
{
$terms_page=1;
}
$terms=apply_filters( 'taxonomy-images-get-terms', '',array('having_images'=>false,'taxonomy'=>$taxonomy, 'term_args'=>array('offset'=>($terms_page-1)*$terms_per_page,'number'=>$terms_per_page)) );
if (empty($terms))
{
header("Location: /");exit;
}
$processed_terms=array();
foreach ($terms as $term)
{
if (!empty($term->image_id))
{
$image_src=wp_get_attachment_image_src($term->image_id,'archive-thumbnail');
$image_src=$image_src[0];
}
else
{
$image_src='http://couch.ro/wp-content/uploads/couchie_75.png';
}
$term_posts=get_posts(array('posts_per_page'=>3,'tax_query'=>array(array('taxonomy'=>$taxonomy,'field'=>'slug','terms'=>$term->slug))));
$actual_term_posts=array();
foreach ($term_posts as $post)
{
$actual_term_posts[$post->post_title]=get_permalink($post->id);
}
$processed_terms[]=array(
'name'=>$term->name,
'description'=>$term->description,
'url'=>get_term_link($term),
'image'=>$image_src,
'posts'=>$actual_term_posts,
'count'=>$term->count
);
}
$has_next_page=(isset($processed_terms[$terms_page]));
get_header();
?>
<div class="posts-wrap">
<div class="archive-title_wrap"><h1 class="archive-title"><?php the_title(); ?></h1></div>
<div id="post_list_wrap">
<?php
foreach ($processed_terms as $term)
{
echo "<div class='post post-archive'>
<a href='{$term['url']}' title='{$term['name']}'><img src='{$term['image']}' alt='{$term['name']}'></a>
<div class='rating' style='text-align:right;'>{$term['count']} ".($term['count']==1?'review':'reviewuri')."</div>
<h2 class='index-entry-title'>
<a href='{$term['url']}' title='{$term['name']}'>{$term['name']}</a>
</h2>
<div class='archive-meta entry-meta-index'>
<span>";
$first_term_post=true;
foreach ($term['posts'] as $title=>$link)
{
echo ($first_term_post?'':', ')."<a href='{$link}' title='{$title}'>{$title}</a>";
$first_term_post=false;
}
echo "</span>
</div>
</div>";
}
?>
</div>
<?php if ($terms_page>1 OR $has_next_page) { ?>
<div class="navigation">
<div class="nav-prev left"><?php if ($terms_page>1) echo "<a href='/{$slug}/".($terms_page>2?"page/".($terms_page-1)."/":'')."'>".__('« Previous Page', 'designcrumbs')."</a>"; ?></div>
<div class="nav-next right"><?php if ($has_next_page) echo "<a href='/{$slug}/page/".($terms_page+1)."/'>".__('Next Page »', 'designcrumbs')."</a>" ?></div>
<div class="clear"></div>
</div>
<?php } ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
You can use query_posts function like this
$termname = get_query_var('pagename'); //custom-taxonomy term
query_posts(array(
'post_type' => POST_TYPE,
'showposts' => $limit,
'custom-taxonomy' => $termname // use $term1.','.$term2.','.$term3 to get multiple terms posts
));
see Documentation at Wordpress
To get all Terms under Custom Taxonomy try this you will have full control.
global $wpdb;
$taxonomy = CUSTOM_CAT_TYPE;
$table_prefix = $wpdb->prefix;
$wpcat_id = NULL;
//Fetch category or Term as said
$wpcategories = (array) $wpdb->get_results("
SELECT * FROM {$table_prefix}terms, {$table_prefix}term_taxonomy
WHERE {$table_prefix}terms.term_id = {$table_prefix}term_taxonomy.term_id
AND {$table_prefix}term_taxonomy.taxonomy ='" . $taxonomy . "' and {$table_prefix}term_taxonomy.parent=0 ORDER BY {$table_prefix}terms.name ASC");
$wpcategories = array_values($wpcategories);
foreach ($wpcategories as $wpcat) {
$termid = $wpcat->term_id;
$name = $wpcat->name;
$termprice = $wpcat->term_price;
$tparent = $wpcat->parent;
}

Subpage with setting api wordpress

I'm currently trying to get my head around the settings api, which is been a bit of a struggle to be honest.
The problem I am having is that when I submit the form on the subpage, it just goes to the the options.php page?
Here is my code so far
function setup_theme_admin_menus() {
add_menu_page('Theme settings', 'SMate Options', 'manage_options',
'theme_settings', 'theme_settings_page');
add_submenu_page('theme_settings',
'Front Page Elements', 'Front Page', 'manage_options',
'theme_settings_fp', 'theme_front_page_settings');
add_submenu_page(
'theme_settings',
'Team Option',
'Team Option',
'manage_options',
'theme_team_options',
'theme_team_settings_fn'
);
}
add_action('admin_init', 'initialize_theme_options');
function initialize_theme_options(){
register_setting('team_details', 'team_details' );
add_settings_section(
'member1',
'MEMBER 1',
'theme_settings_fn',
'theme_team_options'
);
add_settings_field(
't1',
'Name',
'text_fn',
'theme_settings_team',
'member1'
);
add_settings_field(
'jt1',
'Job',
'text_fn',
'theme_settings_team',
'member1'
);
add_settings_field(
'lt1',
'Description',
'longtext_fn',
'theme_settings_team',
'member1'
);
}
add_action('admin_init', 'initialize_theme_options');
function theme_team_settings_fn() {
?>
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>Sandbox Theme Options</h2>
<?php print_r('team_details');
settings_errors(); ?>
<form method="post" action="options.php">
<?php do_settings_sections('theme_team_options'); ?>
<?php submit_button(); ?>
</form>
</div><!-- /.wrap -->
<?php
}
Any help would be greatly appreciated as I seem to have hit a brick wall and all tutorials seem to go through using add_theme_page
For starters your register_settings('option_group','option_name); shouldn't be the same name I would do team_details_group and maybe team_details_options, etc.
Then do settings_fields('team_details_group') right inside the form after the
<form method=post action=options.php>
followed immediately by $options = get_option('team_details_options')
then use team_details_options to inside the input fields name attribute to save any data i.e:
<input type="text" name="team_details_options[memberName]" />
Let me know if this helps or you need more information.

Can I use Wordpress' editor and media uploader outside of a Wordpress site?

I'm currently creating a simple CMS and I would really, really like to use the editor and mainly, image uploader from WordPress on my site. Is this possible?
I am aware that WordPress uses TinyMCE and that they do offer an image manager as a commercial add-on, which I will probably use if this is not possible.
You can use the wp function the_editor:
http://codex.wordpress.org/Function_Reference/the_editor
If you look up that function on google you'll find a bunch of pages describing how to insert the wordpress editor into plug-ins. They provide lots of different ways of doing what you're hopefully looking for.
I used something like:
<form id="new_post" name="new_post" method="post" action="" enctype="multipart/form-data">
<div><h2>Title</h2>
<input type="text" id="title" value="" tabindex="1" name="title" AUTOCOMPLETE=OFF/>
<div>
<h2>Description</h2>
<?php the_editor('', 'description', 'title', true); ?>
</div>
<input type="hidden" name="action" value="post" />
<p align="right"><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p>
<?php wp_nonce_field( 'new-post' ); ?>
</form>
Which you then have to save to the wordpress db using something like:
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter the content';
}
// Add the content of the form to $post as an array
$post = array(
'post_title' => $title,
'post_content' => $description,
/* 'post_category' => array('cat' => '3'), */ // Usable for custom taxonomies too
'post_status' => 'pending', // Choose: publish, pending, draft, auto-draft, future, etc.
'post_type' => 'post' // Use a custom post type if you want to
);
$newID = wp_insert_post($post); // Pass the value of $post to WordPress the insert function
// http://codex.wordpress.org/Function_Reference/wp_insert_post
// wp_redirect( home_url() );
} // end IF
// Do the wp_insert_post action to insert it
do_action('wp_insert_post', 'wp_insert_post');
That's the basics of it... Good luck!
Without knowing the details of your project, I can offer this as a starting point:
With respect to the image uploader, WordPress utilizes some version of the free upload handler Plupload in the current version of WP (3.3), which will handle image uploads.
http://www.plupload.com
If you are looking for features such as crop, resize, thumbnail, etc., then you are right - they do have a paid file and image managers (MCImageManager)
http://www.tinymce.com/enterprise/mcimagemanager.php

Resources