source : http://codex.wordpress.org/WordPress_Lessons
There is a comprehensive list of articles on Template Files and Template Tags in the Templates article.
Thursday, 5 February 2015
Frequently asked wordpress Question
1) What is WordPress?
Word press is a best Open Source CMS which allows it to be used free of cost. You can use it on any kind of personal or commercial website without have to pay a single penny for it. It is built on PHP/MySQL (which is again Open Source) and licensed under GPL.
2) How safe is website on WordPress?
The word press is safe to operate but still it is suggested to keep updating with the latest version of WordPress to avoid hacking.
3) Are there any limitations to a WordPress web site?
You can use WordPress for e-commerce sites, membership sites, photo galleries and any other type of site you can think of. The web site is created using the same html code as any other site so there are no limitations there either.
4) Do you need to have a blog in order to use WordPress for site?
WordPress was originally used as blogging software though it has since become popular for website also. It is not necessary to have a blog to use wordpress. Still having blog is commendable as it will help in search engine optimization.
5) From SEO point of view is wordpress helpful? Will it show the website on Google?
It is one of the benefit of using wordpress, it has inbuilt SEO search engine. Also, you can have an additional plug-in in wordpress to help with SEO and rank on a popular search engine like Google.
6) What is the current version of wordpress?
You need to quote the current version of WordPress available in market along with the release date.
7) What are the types of hooks in WordPress and mention their functions?
There are two types of hooks 1) Action hooks 2) Filter hooks
Hooks allow user to create WordPress theme or plugin with shortcode without changing the original files. Action hooks allow you to insert an additional code from an outside resource, whereas, Filter hooks will only allow you to add a content or text at the end of the post.
8) What do you mean by custom field in wordpress?
Custom field is a meta-data that allows you to store arbitrary information to the wordpress post. Through custom field extra information can be added to the post.
9) What are the positive aspects of wordpress?
Few positive aspects of wordpress are
By default, wp_ is the prefix for wordpress.
12) Why does WordPress use MySQL?
MySQL is widely available database server and is extremely fast. It is an open source and it is available at no cost also it is supported by many low-cost Linux hosts so its easy for anyone to host their website.
13) Is it possible to rename the WordPress folder?
Yes, it is possible to rename the WordPress folder. If WordPress is already installed you have to login to the weblog as the administrator and then change the settings
WordPress address (URI) :
Blog address( URI) :
After making the changes, you can rename the folder or directory with the WordPress file in it.
14) How many tables are there in WordPress by default?
There are about 11 tables in WordPress by default. Note: With succeeding releases of WordPress this number will change. You need to check phpMyAdmin to determine the number of tables in a vanilla version of latest WordPress installation.
15) What is WordPress loop?
To display post WordPress use PHP code, this code is known as loop.
16) How you can disable the WordPress comment?
If you go on dashboard under options-discussion there is a comment “ Allow people to post comment” try unchecking the comment.
17) What are the steps you can take if your WordPress file is hacked?
In WordPress template tags is a code that instructs WordPress to “do” or “get” something.
19) Does WordPress have cookies?
Yes, WordPress have cookies and WordPress uses cookies for verification of users while logged in.
20) In what case you don’t see plugin menu?
You can’t see your plugin menu when the blog is hosted on free wordpress.com as you cannot add plugin there. Also, if you do not have an account of an administrator level on your WordPress is not possible to see plugin.
21) At what instance you get locked out of your WordPress admin and see your website as a blank screen?
This would likely happen when you have pasted a code from a website with wrong formats, also when you have pasted a code in a wrong location. It may also happen when your IP is banned
22) Why you use a static front page in wordpress?
Some WordPress users wants their WordPress installation to be more than a blog site. To give their page a look more like a real website page some users use static front page.
23) What are the plugins you can use to create contact form in WordPress?
To create a contact form in WordPress you can use plugin like Gravity forms or also you can use a free plugin contact form 7.
24) Why widget does not show up in the sidebar?
While using widget you have to ensure whether your theme supports the widget and if it does then it must show the sidebar. If in any case if it happens that you don’t see the sidebar then it might be missing the “function.php” file or file similar to that. This can also happen if you have forgot to save the changes in the widget or refreshing the older display of the page.
25) Is there any limitation for using WordPress?
No, there is no limitation for using WordPress. WordPress can be used for innumerable purpose membership site, e-commerce site, photo-gallery and many more.
26) How is creating a site on wordpress.org different from wordpress.com?
Most of the things are similar in both except the choices of themes and the usage of plugins.
27) Why wordpress.com is considered more secure than wordpress.org?
WordPress.com is considered more secure than wordpress.org because they limit the themes and also does not allow installing plugin’s. However the security is more dependable on how the hosting company is hosting your website(wordpress.org) & also what are the steps they are taking to prevent the security problems.
28) Does de-activated plugins slow down a WordPress site?
No, de-activated plugins cannot slow down the WordPress site. Wordpress only loads the active plugins and ignores everything else.
29) In what case we cannot recommend WordPress to our client?
We cannot recommend WordPress on following situation:
Theme selection differs according to the requirement, but an ideal theme would be something that would not restrict to use the number of pages, plugins or static homepage.
31) How Custom theme is different than Normal theme?
Custom theme allows for SEO search, but with a SEO plugin available it would not make much difference to normal theme. One benefit using the Custom theme is that it allows to make the changes without going much into the coding part.
32) How you can create a static page with WordPress?
To create a static page in wordpress, in the page section you have to upload a php files to the server in the theme folder, and then select that as your template. This allows you to add any page and look that you wanted for your blog and it will remain static.
33) Is there any other CMS better WordPress?
WordPress is no doubt a good CMS, but Drupal and Joomla are among the best CMS you can work with.
34) Which is the best multi-lingual plugin for wordpress?
Keeping all the limitations in mind, WPML would be the best multi-lingual plugin for wordpress .
35) Can you update your own content on the site?
It depends on the type of the site or project, but yes one can update their own content on the site.
36) What are meta-tags?
Meta-tags are keywords and description used to display website or page information.
37) What should one use for plugin development — custom post types or custom database tables?
There is no specific preference for plugin development; it depends on what type of plugin’s one has to develop. Though few recommend custom post type, as it has few benefits comparison to custom database table.
38) Can you host WordPress using Amazon web services such as EC2, RDS, EBS etc?
Yes, you can host using Amazon web services.
39) Is there any way to write series in WordPress?
You can use organize series plugin to write series in wordpress.
40) What are the reasons why one should not hack WordPress core file?
The best reason not to hack the core files is that whatever you might be doing has to be reworked as a patch.
Word press is a best Open Source CMS which allows it to be used free of cost. You can use it on any kind of personal or commercial website without have to pay a single penny for it. It is built on PHP/MySQL (which is again Open Source) and licensed under GPL.
2) How safe is website on WordPress?
The word press is safe to operate but still it is suggested to keep updating with the latest version of WordPress to avoid hacking.
3) Are there any limitations to a WordPress web site?
You can use WordPress for e-commerce sites, membership sites, photo galleries and any other type of site you can think of. The web site is created using the same html code as any other site so there are no limitations there either.
4) Do you need to have a blog in order to use WordPress for site?
WordPress was originally used as blogging software though it has since become popular for website also. It is not necessary to have a blog to use wordpress. Still having blog is commendable as it will help in search engine optimization.
5) From SEO point of view is wordpress helpful? Will it show the website on Google?
It is one of the benefit of using wordpress, it has inbuilt SEO search engine. Also, you can have an additional plug-in in wordpress to help with SEO and rank on a popular search engine like Google.
6) What is the current version of wordpress?
You need to quote the current version of WordPress available in market along with the release date.
7) What are the types of hooks in WordPress and mention their functions?
There are two types of hooks 1) Action hooks 2) Filter hooks
Hooks allow user to create WordPress theme or plugin with shortcode without changing the original files. Action hooks allow you to insert an additional code from an outside resource, whereas, Filter hooks will only allow you to add a content or text at the end of the post.
8) What do you mean by custom field in wordpress?
Custom field is a meta-data that allows you to store arbitrary information to the wordpress post. Through custom field extra information can be added to the post.
9) What are the positive aspects of wordpress?
Few positive aspects of wordpress are
- Easy installation and upgrade
- In-built SEO engine
- Easy theme system
- Flexibility
- Multilingual- available in more than 70 languages
- Own data- no unwanted advert on your website
- Flexibility and Easy publishing option
- Create a unique name
- Create the plugin’s folder
- Create a sub-folder for PHP files, translations and assets
- Create the main plug-in file and fill in header information
- Create activation and de-activation functions
- Create an uninstall script
- Create a readme.txt file
- To detect paths to plugin file use proper constants and functions
By default, wp_ is the prefix for wordpress.
12) Why does WordPress use MySQL?
MySQL is widely available database server and is extremely fast. It is an open source and it is available at no cost also it is supported by many low-cost Linux hosts so its easy for anyone to host their website.
13) Is it possible to rename the WordPress folder?
Yes, it is possible to rename the WordPress folder. If WordPress is already installed you have to login to the weblog as the administrator and then change the settings
WordPress address (URI) :
Blog address( URI) :
After making the changes, you can rename the folder or directory with the WordPress file in it.
14) How many tables are there in WordPress by default?
There are about 11 tables in WordPress by default. Note: With succeeding releases of WordPress this number will change. You need to check phpMyAdmin to determine the number of tables in a vanilla version of latest WordPress installation.
15) What is WordPress loop?
To display post WordPress use PHP code, this code is known as loop.
16) How you can disable the WordPress comment?
If you go on dashboard under options-discussion there is a comment “ Allow people to post comment” try unchecking the comment.
17) What are the steps you can take if your WordPress file is hacked?
- Install security plug-ins like WP security
- Re-install the latest version of WordPress
- Change password and user-ids for all your users
- Check your themes and plug-ins are up to date
In WordPress template tags is a code that instructs WordPress to “do” or “get” something.
19) Does WordPress have cookies?
Yes, WordPress have cookies and WordPress uses cookies for verification of users while logged in.
You can’t see your plugin menu when the blog is hosted on free wordpress.com as you cannot add plugin there. Also, if you do not have an account of an administrator level on your WordPress is not possible to see plugin.
21) At what instance you get locked out of your WordPress admin and see your website as a blank screen?
This would likely happen when you have pasted a code from a website with wrong formats, also when you have pasted a code in a wrong location. It may also happen when your IP is banned
22) Why you use a static front page in wordpress?
Some WordPress users wants their WordPress installation to be more than a blog site. To give their page a look more like a real website page some users use static front page.
23) What are the plugins you can use to create contact form in WordPress?
To create a contact form in WordPress you can use plugin like Gravity forms or also you can use a free plugin contact form 7.
24) Why widget does not show up in the sidebar?
While using widget you have to ensure whether your theme supports the widget and if it does then it must show the sidebar. If in any case if it happens that you don’t see the sidebar then it might be missing the “function.php” file or file similar to that. This can also happen if you have forgot to save the changes in the widget or refreshing the older display of the page.
25) Is there any limitation for using WordPress?
No, there is no limitation for using WordPress. WordPress can be used for innumerable purpose membership site, e-commerce site, photo-gallery and many more.
26) How is creating a site on wordpress.org different from wordpress.com?
Most of the things are similar in both except the choices of themes and the usage of plugins.
27) Why wordpress.com is considered more secure than wordpress.org?
WordPress.com is considered more secure than wordpress.org because they limit the themes and also does not allow installing plugin’s. However the security is more dependable on how the hosting company is hosting your website(wordpress.org) & also what are the steps they are taking to prevent the security problems.
28) Does de-activated plugins slow down a WordPress site?
No, de-activated plugins cannot slow down the WordPress site. Wordpress only loads the active plugins and ignores everything else.
29) In what case we cannot recommend WordPress to our client?
We cannot recommend WordPress on following situation:
- If client is working on non-CMS base project
- If site wants complex or innovative e-commerce
- In case of enterprise intranet solution
- Sites requiring custom scripting solutions.
Theme selection differs according to the requirement, but an ideal theme would be something that would not restrict to use the number of pages, plugins or static homepage.
31) How Custom theme is different than Normal theme?
Custom theme allows for SEO search, but with a SEO plugin available it would not make much difference to normal theme. One benefit using the Custom theme is that it allows to make the changes without going much into the coding part.
32) How you can create a static page with WordPress?
To create a static page in wordpress, in the page section you have to upload a php files to the server in the theme folder, and then select that as your template. This allows you to add any page and look that you wanted for your blog and it will remain static.
33) Is there any other CMS better WordPress?
WordPress is no doubt a good CMS, but Drupal and Joomla are among the best CMS you can work with.
34) Which is the best multi-lingual plugin for wordpress?
Keeping all the limitations in mind, WPML would be the best multi-lingual plugin for wordpress .
35) Can you update your own content on the site?
It depends on the type of the site or project, but yes one can update their own content on the site.
36) What are meta-tags?
Meta-tags are keywords and description used to display website or page information.
37) What should one use for plugin development — custom post types or custom database tables?
There is no specific preference for plugin development; it depends on what type of plugin’s one has to develop. Though few recommend custom post type, as it has few benefits comparison to custom database table.
38) Can you host WordPress using Amazon web services such as EC2, RDS, EBS etc?
Yes, you can host using Amazon web services.
39) Is there any way to write series in WordPress?
You can use organize series plugin to write series in wordpress.
40) What are the reasons why one should not hack WordPress core file?
The best reason not to hack the core files is that whatever you might be doing has to be reworked as a patch.
Sunday, 1 February 2015
Types of Post in Wordpress
Source : http://codex.wordpress.org/Post_Types
WordPress can hold and display many different types of content. A single item of such a content is generally called a post, although post is also a specific post type. Internally, all the post types are stored in the same place, in the wp_posts database table, but are differentiated by a column called post_type.
WordPress 3.0 gives you the capability to add your own custom post types and to use them in different ways.
Note that you must call register_post_type() before the admin_menu and after the after_setup_theme action hooks. A good hook to use is the init hook.
Here's a basic example of adding a custom post type:
There are many more arguments you can pass to the register_post_type() function, to do things like set up hierarchy (to behave like pages), show the new post type in searches, change the URLs of the new posts, and hide or show meta boxes in the post edit screen. These parameters are optional, and you can use them to configure your post type on a detailed level.
For example:
Do pay close attention to not having your custom post type identifier exceed 20 characters though, as the post_type column in the database is currently a VARCHAR field of that length.
Also note that using a generic slug like products here can potentially conflict with other plugins or themes that use the same slug, but most people would dislike longer and more obscure URLs like http://example.com/acme_products/foobrozinator and resolving the URL conflict between two plugins is easier simply because the URL structure is not stored persistently in each post's database record the same way custom post type identifiers are stored.
Note: In some cases, the permalink structure must be updated in order for the new template files to be accessed when viewing posts of a custom post type. To do this, go to Administration Panels > Settings > Permalinks, change the permalink structure to a different structure, save the changes, and change it back to the desired structure.
So for the above example, you could create single-acme_product.php and archive-acme_product.php template files for single product posts and their archives.
Alternatively, you can use the is_post_type_archive() function in any template file to check if the query shows an archive page of a given post types(s), and the post_type_archive_title() to display the post type title.
Example:
If you want your custom post type posts to show up on standard archives or include them on your home page mixed up with other post types, use the pre_get_posts action hook.
WordPress can hold and display many different types of content. A single item of such a content is generally called a post, although post is also a specific post type. Internally, all the post types are stored in the same place, in the wp_posts database table, but are differentiated by a column called post_type.
WordPress 3.0 gives you the capability to add your own custom post types and to use them in different ways.
Contents
- 1 Default Post Types
- 2 Custom Post Types
- 3 More Information
Default Post Types
There are five post types that are readily available to users or internally used by the WordPress installation by default :- Post (Post Type: 'post')
- Page (Post Type: 'page')
- Attachment (Post Type: 'attachment')
- Revision (Post Type: 'revision')
- Navigation menu (Post Type: 'nav_menu_item')
Post
Post in WordPress is a post type that is typical for and most used by blogs. Posts are normally displayed in a blog in reverse sequential order by time (newest posts first). Posts are also used for creating the feeds.Page
Page in WordPress is like post, but it lives outside the normal time-based listings of posts. Pages can use different page templates to display them. Pages can also be organized in a hierarchical structure, with pages being parents to other pages, but they normally cannot be assigned categories and tags. If permalinks are enabled, the permalink of a page is always composed solely of the main site URL and the user-friendly and URL-valid names (also referred to as slug) of the page and its parents if they exist. See the Pages article for more information about the differences.Attachment
Attachment is a special post that holds information about a file uploaded through the WordPress media upload system, such as its description and name. For images, this is also linked to metadata information, stored in the wp_postmeta table, about the size of the images, the thumbnails generated from the images, the location of the image files, the HTML alt text, and even information obtained from EXIF data embedded in the images.Revision
Revision is used to hold a draft post as well as any past revisions of a published post. Revisions are basically identical to the published post which they belong to, but have that post set as their parent using the post_parent column of the wp_posts table.Navigation Menu
Navigation Menu is a type that holds information about a single item in the WordPress navigation menu system. These are the first examples of entries in the wp_posts table to be used for something other than an otherwise displayable content on the blog.Custom Post Types
Custom post types are new post types you can create. A custom post type can be added to WordPress via the register_post_type() function. This function allows you to define a new post type by its labels, supported features, availability and other specifics.Note that you must call register_post_type() before the admin_menu and after the after_setup_theme action hooks. A good hook to use is the init hook.
Here's a basic example of adding a custom post type:
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'acme_product',
array(
'labels' => array(
'name' => __( 'Products' ),
'singular_name' => __( 'Product' )
),
'public' => true,
'has_archive' => true,
)
);
}
This creates a post type named Product identified as acme_product. The register_post_type() function receives two major arguments. The first one is labels which define the name of the post type in both plural and singular forms. The second one is public which is a predefined flag to show the post type on the administration screens and to make it show up in the site content itself, if it's queried for.
There are many more arguments you can pass to the register_post_type() function, to do things like set up hierarchy (to behave like pages), show the new post type in searches, change the URLs of the new posts, and hide or show meta boxes in the post edit screen. These parameters are optional, and you can use them to configure your post type on a detailed level.
A word about custom post types as a plugin
In order to avoid breaking a site on theme switching, try to define custom post types as a plugin, or, better as a Must Use Plugins. This way you won't force users into using a certain theme.Naming Best Practices
While it is convenient to use a simple custom post type identifier like product which is consistent with the identifiers of the default post types (post, page, revision, attachment and nav_menu_item), it is better if you prefix your identifier with a short namespace that identifies your plugin, theme or website that implements the custom post type.For example:
- acme_product or aw_product for products post type used by a hypothetical ACMEWidgets.com website.
- eightfold_product or eft_product for products post type provided by a hypothetical EightFold theme.
- ai1m_product for products post type provided by a hypothetical All-in-One Merchant plugin.
Do pay close attention to not having your custom post type identifier exceed 20 characters though, as the post_type column in the database is currently a VARCHAR field of that length.
Reserved Post Type Identifiers
Although the core development team has yet to make a final decision on this, it has been proposed on the wp-hackers mailing list that future core post type identifiers will be namespaced with wp_, i.e. if the core team decides to add an event post type then according to this suggestion they would use the wp_event identifier. Even though this has not been finalized, it will be a good idea to avoid any custom post types whose identifier begins with wp_.Custom Post Type Screens
When a custom post type is created like in the example above, it gets a new top-level administration menu to create and manage posts of that new post type. New administration screens will be accessible from that menu, such as post edit screen where you will have a full post editor and everything that comes along with it according to what features you set that your custom post type should support by the supports argument of the register_post_type() function. You can customize the screens with several action and filter hooks, see this Custom Post Type Snippets post by Yoast for an explanation and code examples on how to change a custom post type overview screen.URLs
A custom post type will also get its own slug within the site URL structure. In the above example, a post of this product custom post type can be displayed at http://example.com/acme_product/%product_name% where acme_product is the slug of your custom post type and %product_name% is the slug of your particular product, so a permalink could be e.g. http://example.com/product/foobrozinator. You can see this permalink appear on the edit post screen for your custom post type, just like with default post types.URLs of Namespaced Custom Post Types Identifiers
When you namespace a custom post type identifier and still want to use a clean URL structure, you need to set the rewrite argument of the register_post_type() function. For example, assuming the ACME Widgets example from above:add_action( 'init', 'create_posttype' );
function create_posttype() {
register_post_type( 'acme_product',
array(
'labels' => array(
'name' => __( 'Products' ),
'singular_name' => __( 'Product' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'products'),
)
);
}
The above will result in post URLs in the form http://example.com/products/%product_name%. Note that we used a plural word for the slug
here which is a form that some people prefer because it implies a more
logical URL for a page that embeds a list of products, i.e. http://example.com/products/.
Also note that using a generic slug like products here can potentially conflict with other plugins or themes that use the same slug, but most people would dislike longer and more obscure URLs like http://example.com/acme_products/foobrozinator and resolving the URL conflict between two plugins is easier simply because the URL structure is not stored persistently in each post's database record the same way custom post type identifiers are stored.
Custom Post Type Templates
The WordPress theme system supports custom templates for custom post types too. A custom template for a single display of posts belonging to a custom post type is supported since WordPress Version 3.0 and the support for a custom template for an archive display was added in Version 3.1.Note: In some cases, the permalink structure must be updated in order for the new template files to be accessed when viewing posts of a custom post type. To do this, go to Administration Panels > Settings > Permalinks, change the permalink structure to a different structure, save the changes, and change it back to the desired structure.
Template Files
In the same way single posts and their archives can be displayed using the single.php and archive.php template files, respectively,- single posts of a custom post type will use single-{post_type}.php
- and their archives will use archive-{post_type}.php
- and if you don't have this post type archive page you can pass BLOG_URL?post_type={post_type}
So for the above example, you could create single-acme_product.php and archive-acme_product.php template files for single product posts and their archives.
Alternatively, you can use the is_post_type_archive() function in any template file to check if the query shows an archive page of a given post types(s), and the post_type_archive_title() to display the post type title.
Querying by Post Type
In any template file of the WordPress theme system, you can also create new queries to display posts from a specific post type. This is done via the post_type argument of the WP_Query object.Example:
$args = array( 'post_type' => 'product', 'posts_per_page' => 10 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); the_title(); echo '<div class="entry-content">'; the_content(); echo '</div>'; endwhile;This simply loops through the latest 10 product posts and displays the title and content of them one by one.
Custom Post Types in the Main Query
Registering a custom post type does not mean it gets added to the main query automatically.If you want your custom post type posts to show up on standard archives or include them on your home page mixed up with other post types, use the pre_get_posts action hook.
// Show posts of 'post', 'page' and 'movie' post types on home page
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
function add_my_post_types_to_query( $query ) {
if ( is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'page', 'movie' ) );
return $query;
}
Navigation menus code in wordpress
source : http://codex.wordpress.org/Navigation_Menus
To complete the code, you can put your extra menu someplace else. Maybe you want a menu on one of your pages, for example, and you might even want it to be jazzed up a little with a containing DIV of a certain class -
You can now use the GUI menu creator on this admin panel to put your menu(s) together. Give them each a name, and then assign a menu to a location with the pull-down options.
(You will see your new navigation choices when you Add a New Menu.)
Navigation Menus
Navigation Menu is a theme feature introduced with Version 3.0. WordPress includes an easy to use mechanism for introducing customised navigation menus into a theme. In order to incorporate menu support into your theme, you need to add a few code segments to your theme files.Function Reference
|
|
Register Menus
Firstly, in your theme's functions.php, you need to write a function to register the names of your menus. (This is how they will appear in the Appearance -> Menus admin screen.) As an example, this menu would appear in the "Theme Locations" box as "Header Menu".function register_my_menu() {
register_nav_menu('header-menu',__( 'Header Menu' ));
}
add_action( 'init', 'register_my_menu' );
And this would make two menu options appear, header menu and extra menu -
function register_my_menus() {
register_nav_menus(
array(
'header-menu' => __( 'Header Menu' ),
'extra-menu' => __( 'Extra Menu' )
)
);
}
add_action( 'init', 'register_my_menus' );
Display Menus on Theme
Once you've done that, your theme will be almost ready. The last preparation step is to tell the theme where you want the menus to show up. You do this in the relevant theme file. So, for example, we might want our header menu to be in header.php. So open up that file in the theme editor, and decide where you want to put your menu. The code to use here is wp_nav_menu which we will need once for each menu location. So, add this code -<?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); ?>All you need to ensure is that the theme_location points to the name you provided for your menu in the functions.php code above. (Note that it's the header-menu being used here rather than Header Menu without a hyphen. header-menu is the name that the code understands, Header Menu is the human-readable version that you see in the admin page.)
To complete the code, you can put your extra menu someplace else. Maybe you want a menu on one of your pages, for example, and you might even want it to be jazzed up a little with a containing DIV of a certain class -
wp_nav_menu( array( 'theme_location' => 'extra-menu', 'container_class' => 'my_extra_menu_class' ) );So you'd put the above into your Page template, and not only would the menu show up wherever you put it, it'd be styled as my_extra_menu_class so that you can work with that in CSS.
Menus Panel
That's all the background work. To finish, you would simply visit the Appearance -> Menus panel in your site admin. Now, instead of seeing some text suggesting that your theme doesn't natively support menus, you'll see some Theme Location options.You can now use the GUI menu creator on this admin panel to put your menu(s) together. Give them each a name, and then assign a menu to a location with the pull-down options.
(You will see your new navigation choices when you Add a New Menu.)
Search Shortcode code in wordpress
Source : http://codex.wordpress.org/Function_Reference/get_search_form
WordPress will render its built-in HTML5 search form:
Example of a custom searchform.php:
A last option is to write a custom function (in your functions.php file) and hook that function to the get_search_form action hook.
Description
Display search form using searchform.php Theme file.Usage
<?php get_search_form( $echo ); ?>
Parameters
- $echo
- (boolean) (optional) true to echo the form; false to return the form as a string.
- Default: true
Return Values
- (string)
- The form's HTML, if the $echo parameter is set to false.
Examples
Default HTML4 Form
If you don't have searchform.php in your Theme, WordPress will render its built-in search form:<form role="search" method="get" id="searchform" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <div> <label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label> <input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" /> <input type="submit" id="searchsubmit" value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" /> </div> </form>The above form is used on HTML4 websites.
Default HTML5 Form
Since WordPress 3.6, If your theme supports HTML5, which happens if it uses:add_theme_support( 'html5', array( 'search-form' ) );
WordPress will render its built-in HTML5 search form:
<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>"> <label> <span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ) ?></span> <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" /> </label> <input type="submit" class="search-submit" value="<?php echo esc_attr_x( 'Search', 'submit button' ) ?>" /> </form>Among the changes is that the form has a class="search-form". Also, the input is type="search" and not type="text". Furthermore there is a placeholder, which displays text when appropriate, which means you don't need javascript to display the placeholder. There are no elements with an id anymore, so you can have multiple searchforms in a valid document.
Theme Form
If you do have searchform.php in your Theme, it will be used instead. Keep in mind that the search form should do a GET to the homepage of your blog. The input text field should be named s and you should always include a label like in the examples above.Example of a custom searchform.php:
<form action="/" method="get"> <fieldset> <label for="search">Search in <?php echo home_url( '/' ); ?></label> <input type="text" name="s" id="search" value="<?php the_search_query(); ?>" /> <input type="image" alt="Search" src="<?php bloginfo( 'template_url' ); ?>/images/search.png" /> </fieldset> </form>The only parameter here that will be submitted is s with the value of the current search query. However, you can refine it in many ways. For example by only showing posts in the search results. This can be done with the next addition to the form above:
<input type="hidden" value="post" name="post_type" id="post_type" />Here we submit the value post. The default value is any, meaning, posts, pages and custom post types. With the input above added to the form it will now only search in posts with the post_type post. There are many additions like this. With a var_dump of the object $wp_query you can see all the default values of the search variables. With a var_dump of $wp_query->query you can see the current query.
A last option is to write a custom function (in your functions.php file) and hook that function to the get_search_form action hook.
function my_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
<div><label class="screen-reader-text" for="s">' . __( 'Search for:' ) . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />
</div>
</form>';
return $form;
}
add_filter( 'get_search_form', 'my_search_form' );
Notes
Please usevalue="<?php echo get_search_query(); ?>" (so a wrapper function for: esc_attr( $s );
and other necessary filters) if you'd like to display currently
searched term in the search field once searching have already occurred.
This is one of the most XSS vulnerable places in themes if not secured.
How to create a dynamic sidebar in wordpress
source : http://codex.wordpress.org/Function_Reference/dynamic_sidebar
The return value should be used to determine whether to display a static sidebar. This ensures that your theme will look good even when the Widgets plug-in is not active.
If your sidebars were registered by number, they should be retrieved by number. If they had names when you registered them, use their names to retrieve them.
Using ID's ( dynamic_sidebar(1) ) is easier in that you don't need to name your sidebar, but they are harder to figure out without looking into your functions.php file or in the widgets administration panel and thus make your code less readable. Note that ID's begin at 1.
If you name your own ID values in the register_sidebar() WordPress function, you might increase readability of the code. The ID should be all lowercase alphanumeric characters and not contain white space. You can also use the - and _ characters. IDs must be unique and cannot match a sidebar name. Using your own IDs can also make the sidebar name translatable.
Description
This function calls each of the active widget callbacks in order, which prints the markup for the sidebar. If you have more than one sidebar, you should give this function the name or number of the sidebar you want to print. This function returns true on success and false on failure.The return value should be used to determine whether to display a static sidebar. This ensures that your theme will look good even when the Widgets plug-in is not active.
If your sidebars were registered by number, they should be retrieved by number. If they had names when you registered them, use their names to retrieve them.
Usage
<?php dynamic_sidebar( $index ); ?>
Parameters
- index
- (integer/string) (optional) Name or ID of dynamic sidebar.
- Default: 1
Return Value
- (boolean)
- True, if widget sidebar was found and called. False if not found or not called.
Examples
Here is the recommended use of this function:<ul id="sidebar">
<?php if ( ! dynamic_sidebar() ) : ?>
<li>{static sidebar item 1}</li>
<li>{static sidebar item 2}</li>
<?php endif; ?>
</ul>
<ul id="sidebar"> <?php dynamic_sidebar( 'right-sidebar' ); ?> </ul>
<?php if ( is_active_sidebar( 'left-sidebar' ) ) : ?> <ul id="sidebar"> <?php dynamic_sidebar( 'left-sidebar' ); ?> </ul> <?php endif; ?>
in the "Twenty Ten" theme (3.0+)
Multiple Sidebars
You can load a specific sidebar by either their name (if given a string) or ID (if given an integer). For example, dynamic_sidebar('top_menu') will present a sidebar registered with register_sidebar(array('name'=>'top_menu',)).Using ID's ( dynamic_sidebar(1) ) is easier in that you don't need to name your sidebar, but they are harder to figure out without looking into your functions.php file or in the widgets administration panel and thus make your code less readable. Note that ID's begin at 1.
If you name your own ID values in the register_sidebar() WordPress function, you might increase readability of the code. The ID should be all lowercase alphanumeric characters and not contain white space. You can also use the - and _ characters. IDs must be unique and cannot match a sidebar name. Using your own IDs can also make the sidebar name translatable.
// See the __() WordPress function for valid values for $text_domain.
register_sidebar( array(
'id' => 'top-menu',
'name' => __( 'Top Menu', $text_domain ),
'description' => __( 'This sidebar is located above the age logo.', $text_domain ),
) );
This allows the use of dynamic_sidebar( 'top-menu' ) which uses an ID and is readable.
Shortcode in wordpress
source = http://codex.wordpress.org/Shortcode_API
The Shortcode API makes it easy to create shortcodes that support attributes like this:
As a quick start for those in a hurry, here's a minimal example of the PHP code required to create a shortcode:
With attributes:
Shortcode names should be all lowercase and use all letters, but numbers and underscores should work fine too. Be wary of using hyphens (dashes), you'll be better off not using them.
The
Three parameters are passed to the shortcode callback function. You can choose to use any number of them including none of them.
Shortcode attributes are entered like this:
In order to help set default values for missing attributes, and eliminate any attributes that are not recognized by your shortcode, the API provides a shortcode_atts() function.
Attribute names are always converted to lowercase before they are passed into the handler function. Values are untouched.
A suggested code idiom for declaring defaults and parsing attributes in a shortcode handler is as follows:
Shortcodes are parsed after wpautop and wptexturize post formatting has been applied (but see the note below about 2.5.0 and 2.5.1 differences). This means that your shortcode output HTML won't automatically have curly quotes applied, p and br tags added, and so on. If you do want your shortcode output to be formatted, you should call wpautop() or wptexturize() directly when you return the output from your shortcode handler.
wpautop recognizes shortcode syntax and will attempt not to wrap p or br tags around shortcodes that stand alone on a line by themselves. Shortcodes intended for use in this manner should ensure that the output is wrapped in an appropriate block tag such as <p> or <div>.
Note: in WordPress 2.5.0, shortcodes were parsed before post formatting was applied, so the shortcode output HTML was sometimes wrapped in p or br tags. This was incorrect behaviour that has been fixed in 2.5.1.
If the shortcode produces a lot of HTML then ob_start can be used to capture output and convert it to a string as follows:-
If a shortcode macro is used to enclose content, its handler function will receive a second parameter containing that content. Users might write shortcodes in either form, so it is necessary to allow for either case by providing a default value for the second parameter to your handler function:
When content is enclosed, the complete shortcode macro including its content will be replaced with the function output. It is the responsibility of the handler function to provide any necessary escaping or encoding of the raw content string, and include it in the output.
Here's a trivial example of an enclosing shortcode:
The shortcode parser uses a single pass on the post content. This means that if the $content parameter of a shortcode handler contains another shortcode, it won't be parsed:
Enclosing shortcodes support attributes in the same way as self-closing shortcodes. Here's an example of the caption_shortcode() improved to support a 'class' attribute:
Only one handler function may exist for a given shortcode. Calling add_shortcode() again with the same $tag name will overwrite the previous handler.
do_shortcode() is registered as a default filter on 'the_content' with a priority of 11.
In future versions of WordPress, it may be necessary for plugins having a nested shortcode syntax to ensure that the wptexturize() processor does not interfere with the inner codes. It is recommended that for such complex syntax, the no_texturize_shortcodes filter should be used on the outer tags. In the examples used here, tag-a should be added to the list of shortcodes to not texturize. If the contents of tag-a or tag-b still need to be texturized, then you can call wptexturize() before calling do_shortcode() as described above.
Take caution when using hyphens in the name of your shortcodes. In the following instance WordPress may see the second opening shortcode as equivalent to the first (basically WordPress sees the first part before the hyphen):
To avoid this, use an underscore or simply no separator:
Full usage of HTML in shortcode attributes was never officially supported, but will be considered as a possible enhancement in future versions.
In a perfect world, any [*] symbol could be handled by the API, but we have to consider the following challenges: Square braces are allowed in HTML and are not always shortcodes, angle braces are allowed inside of shortcodes only in limited situations, and all of this code must run through multiple layers of customizeable filters and parsers before output. Because of these language compatibility issues, square braces can't be magical.
The shortcode syntax uses these general parts:
Each attribute should conform to one of these formats:
Attribute values must never contain the following characters:
HTML characters < and > have only limited support in attributes.
The recommended method of escaping special characters in shortcode attributes is HTML encoding. Most importantly, any user input appearing in a shortcode attribute must be escaped or stripped of special characters.
Note that double quotes are allowed inside of single-quoted values and vice versa, however this is not recommended when dealing with user input.
The following characters, if they are not escaped within an attribute value, will be automatically stripped and converted to spaces:
The enclosing type shortcodes may not use a self-closing marker.
Registered shortcodes are still processed inside of <code> elements. To escape a registered shortcode for display on your website, the syntax becomes:
The Shortcode API
Introduced in WordPress 2.5 is the Shortcode API, a simple set of functions for creating macro codes for use in post content. For instance, the following shortcode (in the post/page content) would add a photo gallery into the page:[gallery]It enables plugin developers to create special kinds of content (e.g. forms, content generators) that users can attach to certain pages by adding the corresponding shortcode into the page text.
The Shortcode API makes it easy to create shortcodes that support attributes like this:
[gallery id="123" size="medium"]The API handles all the tricky parsing, eliminating the need for writing a custom regular expression for each shortcode. Helper functions are included for setting and fetching default attributes. The API supports both self-closing and enclosing shortcodes.
As a quick start for those in a hurry, here's a minimal example of the PHP code required to create a shortcode:
//[foobar]
function foobar_func( $atts ){
return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );
This will create [foobar] shortcode that returns as: foo and bar
With attributes:
// [bartag foo="foo-value"]
function bartag_func( $atts ) {
$a = shortcode_atts( array(
'foo' => 'something',
'bar' => 'something else',
), $atts );
return "foo = {$a['foo']}";
}
add_shortcode( 'bartag', 'bartag_func' );
This creates a "[bartag]" shortcode that supports two attributes:
["foo" and "bar"]. Both attributes are optional and will take on
default options [foo="something" bar="something else"] if they are not
provided. The shortcode will return as foo = {the value of the foo
attribute}.
Overview
Shortcodes are written by providing a handler function. Shortcode handlers are broadly similar to WordPress filters: they accept parameters (attributes) and return a result (the shortcode output).Shortcode names should be all lowercase and use all letters, but numbers and underscores should work fine too. Be wary of using hyphens (dashes), you'll be better off not using them.
The
add_shortcode
function is used to register a shortcode handler. It takes two
parameters: the shortcode name (the string used in a post body), and the
callback function name.
Three parameters are passed to the shortcode callback function. You can choose to use any number of them including none of them.
- $atts - an associative array of attributes, or an empty string if no attributes are given
- $content - the enclosed content (if the shortcode is used in its enclosing form)
- $tag - the shortcode tag, useful for shared callback functions
add_shortcode( 'myshortcode', 'my_shortcode_handler' );When the_content is displayed, the shortcode API will parse any registered shortcodes such as "[myshortcode]", separate and parse the attributes and content, if any, and pass them the corresponding shortcode handler function. Any string returned (not echoed) by the shortcode handler will be inserted into the post body in place of the shortcode itself.
Shortcode attributes are entered like this:
[myshortcode foo="bar" bar="bing"]These attributes will be converted into an associative array like the following, passed to the handler function as its
$atts parameter:
array( 'foo' => 'bar', 'bar' => 'bing' )The array keys are the attribute names; array values are the corresponding attribute values. In addition, the zeroeth entry ($atts[0]) will hold the string that matched the shortcode regex, but ONLY IF that is different from the callback name. See the discussion of attributes, below.
Handling Attributes
The raw $atts array may include any arbitrary attributes that are specified by the user. (In addition, the zeroeth entry of the array may contain the string that was recognized by the regex; see the note below.)In order to help set default values for missing attributes, and eliminate any attributes that are not recognized by your shortcode, the API provides a shortcode_atts() function.
shortcode_atts() resembles the wp_parse_args function, but has some important differences. Its parameters are:
shortcode_atts( $defaults_array, $atts );Both parameters are required.
$defaults_array is an associative array that specifies the recognized attribute names and their default values. $atts is the raw attributes array as passed into your shortcode handler. shortcode_atts() will return a normalized array containing all of the keys from the $defaults_array, filled in with values from the $atts array if present. For example:
$a = shortcode_atts( array(
'title' => 'My Title',
'foo' => 123,
), $atts );
If $atts were to contain array( 'foo' => 456, 'bar' => 'something' ), the resulting $a would be array( 'title' => 'My Title', 'foo' => 456 ). The value of $atts['foo'] overrides the default of 123. $atts['title']
is not set, so the default 'My Title' is used. There is no 'bar' item
in the defaults array, so it is not included in the result.
Attribute names are always converted to lowercase before they are passed into the handler function. Values are untouched.
[myshortcode FOO="BAR"] produces $atts = array( 'foo' => 'BAR' ).
A suggested code idiom for declaring defaults and parsing attributes in a shortcode handler is as follows:
function my_shortcode_handler( $atts, $content = null ) {
$a = shortcode_atts( array(
'attr_1' => 'attribute 1 default',
'attr_2' => 'attribute 2 default',
// ...etc
), $atts );
}
This will parse the attributes, set default values, eliminate any
unsupported attributes, and store the results in a local array variable
named $a with the attributes as keys - $a['attr_1'], $a['attr_2'], and so on. In other words, the array of defaults approximates a list of local variable declarations.
- IMPORTANT TIP - Don't use camelCase or UPPER-CASE for your $atts attribute names
- $atts values are lower-cased during shortcode_atts( array( 'attr_1' => 'attr_1 default', // ...etc ), $atts ) processing, so you might want to just use lower-case.
- NOTE on confusing regex/callback name reference
- The zeroeth entry of the attributes array ($atts[0]) will contain the string that matched the shortcode regex, but ONLY if that differs from the callback name, which otherwise appears as the third argument to the callback function.
- (Appears to always appear as third argument as of 2.9.2.)
add_shortcode('foo','foo'); // two shortcodes referencing the same callback
add_shortcode('bar','foo');
produces this behavior:
[foo a='b'] ==> callback to: foo(array('a'=>'b'),NULL,"foo");
[bar a='c'] ==> callback to: foo(array(0 => 'bar', 'a'=>'c'),NULL,"");
This is confusing and perhaps reflects an underlying bug, but an
overloaded callback routine can correctly determine what shortcode was
used to call it, by checking BOTH the third argument to the callback and
the zeroeth attribute. (It is NOT an error to have two shortcodes
reference the same callback routine, which allows for common code.)
Output
The return value of a shortcode handler function is inserted into the post content output in place of the shortcode macro. Remember to use return and not echo - anything that is echoed will be output to the browser, but it won't appear in the correct place on the page.Shortcodes are parsed after wpautop and wptexturize post formatting has been applied (but see the note below about 2.5.0 and 2.5.1 differences). This means that your shortcode output HTML won't automatically have curly quotes applied, p and br tags added, and so on. If you do want your shortcode output to be formatted, you should call wpautop() or wptexturize() directly when you return the output from your shortcode handler.
wpautop recognizes shortcode syntax and will attempt not to wrap p or br tags around shortcodes that stand alone on a line by themselves. Shortcodes intended for use in this manner should ensure that the output is wrapped in an appropriate block tag such as <p> or <div>.
Note: in WordPress 2.5.0, shortcodes were parsed before post formatting was applied, so the shortcode output HTML was sometimes wrapped in p or br tags. This was incorrect behaviour that has been fixed in 2.5.1.
If the shortcode produces a lot of HTML then ob_start can be used to capture output and convert it to a string as follows:-
function myShortCode() {
ob_start();
?> <HTML> <here> ... <?PHP
return ob_get_clean();
}
Enclosing vs self-closing shortcodes
The examples above show self-closing shortcode macros such as [myshortcode]. The API also supports enclosing shortcodes such as [myshortcode]content[/myshortcode].If a shortcode macro is used to enclose content, its handler function will receive a second parameter containing that content. Users might write shortcodes in either form, so it is necessary to allow for either case by providing a default value for the second parameter to your handler function:
function my_shortcode_handler( $atts, $content = null )is_null( $content ) can be used to distinguish between the self-closing and enclosing cases.
When content is enclosed, the complete shortcode macro including its content will be replaced with the function output. It is the responsibility of the handler function to provide any necessary escaping or encoding of the raw content string, and include it in the output.
Here's a trivial example of an enclosing shortcode:
function caption_shortcode( $atts, $content = null ) {
return '<span class="caption">' . $content . '</span>';
}
add_shortcode( 'caption', 'caption_shortcode' );
When used like this:
[caption]My Caption[/caption]The output would be:
<span class="caption">My Caption</span>Since $content is included in the return value without any escaping or encoding, the user can include raw HTML:
[caption]<a href="http://example.com/">My Caption</a>[/caption]Which would produce:
<span class="caption"><a href="http://example.com/">My Caption</a></span>This may or may not be intended behaviour - if the shortcode should not permit raw HTML in its output, it should use an escaping or filtering function to deal with it before returning the result.
The shortcode parser uses a single pass on the post content. This means that if the $content parameter of a shortcode handler contains another shortcode, it won't be parsed:
[caption]Caption: [myshortcode][/caption]This would produce:
<span class="caption">Caption: [myshortcode]</span>If the enclosing shortcode is intended to permit other shortcodes in its output, the handler function can call do_shortcode() recursively:
function caption_shortcode( $atts, $content = null ) {
return '<span class="caption">' . do_shortcode($content) . '</span>';
}
In the previous example, this would ensure the "[myshortcode]" macro
in the enclosed content is parsed, and its output enclosed by the
caption span:
<span class="caption">Caption: The result of myshortcode's handler function</span>The parser does not handle mixing of enclosing and non-enclosing forms of the same shortcode as you would want it to. For example, if you have:
[myshortcode example='non-enclosing' /] non-enclosed content [myshortcode] enclosed content [/myshortcode]Instead of being treated as two shortcodes separated by the text " non-enclosed content ", the parser treats this as a single shortcode enclosing " non-enclosed content [myshortcode] enclosed content".
Enclosing shortcodes support attributes in the same way as self-closing shortcodes. Here's an example of the caption_shortcode() improved to support a 'class' attribute:
function caption_shortcode( $atts, $content = null ) {
$a = shortcode_atts( array(
'class' => 'caption',
), $atts );
return '<span class="' . esc_attr($a['class']) . '">' . $content . '</span>';
}
[caption class="headline"]My Caption[/caption]
<span class="headline">My Caption</span>
Other features in brief
- The parser supports xhtml-style closing shortcodes like "[myshortcode /]", but this is optional.
- Shortcode macros may use single or double quotes for attribute values, or omit them entirely if the attribute value does not contain spaces. [myshortcode foo='123' bar=456] is equivalent to [myshortcode foo="123" bar="456"]. Note the attribute value in the last position may not end with a forward slash because the feature in the paragraph above will consume that slash.
- For backwards compatibility with older ad-hoc shortcodes, attribute names may be omitted. If an attribute has no name it will be given a positional numeric key in the $atts array. For example, [myshortcode 123] will produce $atts = array( 0 => 123 ). Positional attributes may be mixed with named ones, and quotes may be used if the values contain spaces or other significant characters.
- The shortcode API has test cases. The tests -- which contain a number of examples of error cases and unusual syntax -- can be found at http://svn.automattic.com/wordpress-tests/trunk/tests/shortcode.php
Function reference
The following Shortcode API functions are available:function add_shortcode( $tag, $func )Registers a new shortcode handler function. $tag is the shortcode string as written by the user (without braces), such as "myshortcode". $func is the handler function name.
Only one handler function may exist for a given shortcode. Calling add_shortcode() again with the same $tag name will overwrite the previous handler.
function remove_shortcode( $tag )Deregisters an existing shortcode. $tag is the shortcode name as used in add_shortcode().
function remove_all_shortcodes()Deregisters all shortcodes.
function shortcode_atts( $pairs, $atts )Process a raw array of attributes $atts against the set of defaults specified in $pairs. Returns an array. The result will contain every key from $pairs, merged with values from $atts. Any keys in $atts that do not exist in $pairs are ignored.
function do_shortcode( $content )Parse any known shortcode macros in the $content string. Returns a string containing the original content with shortcode macros replaced by their handler functions' output.
do_shortcode() is registered as a default filter on 'the_content' with a priority of 11.
Limitations
Nested Shortcodes
The shortcode parser correctly deals with nested shortcode macros, provided their handler functions support it by recursively calling do_shortcode():[tag-a]
[tag-b]
[tag-c]
[/tag-b]
[/tag-a]
However the parser will fail if a shortcode macro is used to enclose another macro of the same name:
[tag-a] [tag-a] [/tag-a] [/tag-a]This is a limitation of the context-free regexp parser used by do_shortcode() - it is very fast but does not count levels of nesting, so it can't match each opening tag with its correct closing tag in these cases.
In future versions of WordPress, it may be necessary for plugins having a nested shortcode syntax to ensure that the wptexturize() processor does not interfere with the inner codes. It is recommended that for such complex syntax, the no_texturize_shortcodes filter should be used on the outer tags. In the examples used here, tag-a should be added to the list of shortcodes to not texturize. If the contents of tag-a or tag-b still need to be texturized, then you can call wptexturize() before calling do_shortcode() as described above.
Unregistered Names
Some plugin authors have chosen a strategy of not registering shortcode names, for example to disable a nested shortcode until the parent shortcode's handler function is called. This may have unintended consequences, such as failure to parse shortcode attribute values. For example:[tag-a unit="north"]
[tag-b size="24"]
[tag-c color="red"]
[/tag-b]
[/tag-a]
Starting with version 4.0.1, if a plugin fails to register tag-b and
tag-c as valid shortcodes, the wptexturize() processor will output the
following text prior to any shortcode being parsed:
[tag-a unit="north"]
[tag-b size=”24”]
[tag-c color=”red”]
[/tag-b]
[/tag-a]
Unregistered shortcodes should be considered normal plain text that
have no special meaning, and the practice of using unregistered
shortcodes is discouraged. If you must enclose raw code between
shortcode tags, at least consider using the no_texturize_shortcodes filter to prevent texturization of the contents of tag-a:
add_shortcode( 'tag-a', 'my_tag_a_handler' );
add_filter( 'no_texturize_shortcodes', 'ignore_tag_a' );
function ignore_tag_a( $list ) {
$list[] = 'tag-a';
return $list;
}
Unclosed Shortcodes
In certain cases the shortcode parser cannot correctly deal with the use of both closed and unclosed shortcodes. For instance in this case the parser will only correctly identify the second instance of the shortcode:[tag] [tag] CONTENT [/tag]However in this case the parser will identify both:
[tag] CONTENT [/tag] [tag]
Hyphens
Note: The behavior described below involving shortcodes with hyphens ('-') still applies in WordPress 3+. This could be due to a bug in do_shortcode() or get_shortcode_regex().Take caution when using hyphens in the name of your shortcodes. In the following instance WordPress may see the second opening shortcode as equivalent to the first (basically WordPress sees the first part before the hyphen):
[tag] [tag-a]It all depends on which shortcode is defined first. If you are going to use hyphens then define the shortest shortcode first.
To avoid this, use an underscore or simply no separator:
[tag] [tag_a] [tag] [taga]If the first part of the shortcode is different from one another, you can get away with using hyphens:
[tag] [tagfoo-a]Important: Using hyphens can have implications that you may not be aware of; such as if other installed shortcodes also are use hyphens, the use of generic words with hyphens may cause collisions (if shortcodes are used together within the same request):
// plugin-A [is-logged-in] // plugin-B [is-admin]
Square Brackets
The shortcode parser does not accept square brackets within attributes. Thus the following will fail:[tag attribute="[Some value]"]Tags surrounded by cosmetic brackets are not yet fully supported by wptexturize() or its filters. These codes may give unexpected results:
[I put random text near my captions. [caption]]Note: these limitations may change in future versions of WordPress, you should test to be absolutely sure.
HTML
Starting with version 3.9.3, use of HTML is limited inside shortcode attributes. For example, this shortcode will not work correctly because it contains a '>' character:[tag value1="35" value2="25" compare=">"]Version 4.0 is designed to allow validated HTML, so this will work:
[tag description="<b>Greetings</b>"]The suggested workaround for HTML limitations is to use HTML encoding for all user input, and then add HTML decoding in the custom shortcode handler. Extra API functions are planned.
Full usage of HTML in shortcode attributes was never officially supported, but will be considered as a possible enhancement in future versions.
Formal Syntax
WordPress shortcodes do not use special characters in the same way as HTML. The square braces may seem magical at first glance, but they are not truly part of any language. For example:[gallery]The gallery shortcode is parsed by the API as a special symbol because it is a registered shortcode. On the other hand, square braces are simply ignored when a shortcode is not registered:
[randomthing]The randomthing symbol and its square braces are ignored because they are not part of any registered shortcode.
In a perfect world, any [*] symbol could be handled by the API, but we have to consider the following challenges: Square braces are allowed in HTML and are not always shortcodes, angle braces are allowed inside of shortcodes only in limited situations, and all of this code must run through multiple layers of customizeable filters and parsers before output. Because of these language compatibility issues, square braces can't be magical.
The shortcode syntax uses these general parts:
[name attributes close]
[name attributes]Any HTML or shortcode may go here.[/name]Escaped shortcodes are identical but have exactly two extra braces:
[[name attributes close]]
[[name attributes]Any HTML or shortcode may go here.[/name]]Again, the shortcode name must be registered, otherwise all four examples would be ignored.
Names
Shortcode names must never contain the following characters:- Square braces: [ ]
- Forward slash: /
- Whitespace: space linefeed tab
- Non-printing characters: \x00 - \x20
- Angle braces: < >
- Ampersand: &
- Quotes: ' "
Attributes
Attributes are optional. A space is required between the shortcode name and the shortcode attributes. When more than one attribute is used, each attribute must be separated by at least one space.Each attribute should conform to one of these formats:
attribute_name = 'value'
attribute_name = "value"
attribute_name = value
"value"
valueAttribute names are optional and should contain only the following characters for compatibility across all platforms:
- Upper-case and lower-case letters: A-Z a-z
- Digits: 0-9
- Underscore: _
Attribute values must never contain the following characters:
- Square braces: [ ]
- Quotes: " '
HTML characters < and > have only limited support in attributes.
The recommended method of escaping special characters in shortcode attributes is HTML encoding. Most importantly, any user input appearing in a shortcode attribute must be escaped or stripped of special characters.
Note that double quotes are allowed inside of single-quoted values and vice versa, however this is not recommended when dealing with user input.
The following characters, if they are not escaped within an attribute value, will be automatically stripped and converted to spaces:
- No-break space: \xC2\xA0
- Zero-width space: \xE2\x80\x8B
Self-Closing
The self-closing marker, a single forward slash, is optional. Space before the marker is optional. Spaces are not allowed after the marker.[example /]The self-closing marker is purely cosmetic and has no effect except that it will force the shortcode parser to ignore any closing tag that follows it.
The enclosing type shortcodes may not use a self-closing marker.
Escaping
WordPress attempts to insert curly quotes between the [name] and [/name] tags. It will process that content just like any other. As of 4.0.1, unregistered shortcodes are also "texturized" and this may give unexpected curly quotes:[randomthing param="test"]A better example would be:
<code>[randomthing param="test"]</code>The <code> element is always avoided for the sake of curly quotes.
Registered shortcodes are still processed inside of <code> elements. To escape a registered shortcode for display on your website, the syntax becomes:
[[caption param="test"]]... which will output ...
[caption param="test"]The <code> element is optional in that situation.
Subscribe to:
Comments (Atom)