Sunday, 14 April 2013

Top 10 things wordpress programmer needs to know

1. How to change server details in wordpress file.

Answer : Go to directory where wordpress installed.
         -> Open file name : wp-config.php
       
 ---------------------------------------------------------------
 To change database name -> 
 define('DB_NAME', 'please-enter-data-base-name-here');
----------------------------------------------------------------
 To change database password -> 
 define('DB_PASSWORD', 'please-enter-data-base-password-here');
----------------------------------------------------------------
 To change database user name-> 
 define('DB_USER', 'please-enter-data-base-user-name-here');
----------------------------------------------------------------
 To change language 
 define('WPLANG', '');
 please prefer this link 
----------------------------------------------------------------

2. How to create custom post type in wordpress codex.

Answer :
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.

Example1

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,
		)
	);
}

  

Example2


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,
			'rewrite' => array('slug' => 'products'),
		)
	);
}
  

Function Reference

Post Typesregister_post_type(),


----------------------------------------------------------------


3. How to create shortcode in wordpress theme file or in plugin.



Answer :  
// [bartag foo="foo-value"]
function bartag_func( $atts ) {
	extract( shortcode_atts( array(
		'foo' => 'something',
		'bar' => 'something else',
	), $atts ) );

	return "foo = {$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}
-----------------------------------------------------------------

4. How to create menus by wordpress codex in admin panel.

<?php
/** Step 2 (from text above). */
add_action( 'admin_menu', 'my_plugin_menu' );

/** Step 1. */
function my_plugin_menu() {
	add_options_page( 'My Plugin Options', 'My Plugin', 'manage_options', 'my-unique-identifier', 'my_plugin_options' );
}

/** Step 3. */
function my_plugin_options() {
	if ( !current_user_can( 'manage_options' ) )  {
		wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
	}
	echo '<div class="wrap">';
	echo '<p>Here is where the form would go if I actually had options.</p>';
	echo '</div>';
}
?>

Inserting the Pages

Here is an example of a WordPress plugin that inserts new menus into various places:
<?php
/*
Plugin Name: Menu Test
Plugin URI: http://codex.wordpress.org/Adding_Administration_Menus
Description: Menu Test
Author: Codex authors
Author URI: http://example.com
*/

// Hook for adding admin menus
add_action('admin_menu', 'mt_add_pages');

// action function for above hook
function mt_add_pages() {
    // Add a new submenu under Settings:
    add_options_page(__('Test Settings','menu-test'), __('Test Settings','menu-test'), 'manage_options', 'testsettings', 'mt_settings_page');

    // Add a new submenu under Tools:
    add_management_page( __('Test Tools','menu-test'), __('Test Tools','menu-test'), 'manage_options', 'testtools', 'mt_tools_page');

    // Add a new top-level menu (ill-advised):
    add_menu_page(__('Test Toplevel','menu-test'), __('Test Toplevel','menu-test'), 'manage_options', 'mt-top-level-handle', 'mt_toplevel_page' );

    // Add a submenu to the custom top-level menu:
    add_submenu_page('mt-top-level-handle', __('Test Sublevel','menu-test'), __('Test Sublevel','menu-test'), 'manage_options', 'sub-page', 'mt_sublevel_page');

    // Add a second submenu to the custom top-level menu:
    add_submenu_page('mt-top-level-handle', __('Test Sublevel 2','menu-test'), __('Test Sublevel 2','menu-test'), 'manage_options', 'sub-page2', 'mt_sublevel_page2');
}

// mt_settings_page() displays the page content for the Test settings submenu
function mt_settings_page() {
    echo "<h2>" . __( 'Test Settings', 'menu-test' ) . "</h2>";
}

// mt_tools_page() displays the page content for the Test Tools submenu
function mt_tools_page() {
    echo "<h2>" . __( 'Test Tools', 'menu-test' ) . "</h2>";
}

// mt_toplevel_page() displays the page content for the custom Test Toplevel menu
function mt_toplevel_page() {
    echo "<h2>" . __( 'Test Toplevel', 'menu-test' ) . "</h2>";
}

// mt_sublevel_page() displays the page content for the first submenu
// of the custom Test Toplevel menu
function mt_sublevel_page() {
    echo "<h2>" . __( 'Test Sublevel', 'menu-test' ) . "</h2>";
}

// mt_sublevel_page2() displays the page content for the second submenu
// of the custom Test Toplevel menu
function mt_sublevel_page2() {
    echo "<h2>" . __( 'Test Sublevel2', 'menu-test' ) . "</h2>";
}

?>

Sample Menu Page

Note: See the Settings API for information on creating settings pages.
The example above contains several dummy functions, such as mt_settings_page, as placeholders for actual page content. We need to turn them into real menu pages. So, let's assume that our plugin has an option called mt_favorite_color, and that we want to allow the site owner to type in his/her favorite color via a Settings page. The mt_options_page function will need to put a data entry form on the screen to enable this, and also process the entered data. Here is a function that does this:
// mt_settings_page() displays the page content for the Test settings submenu
function mt_settings_page() {

    //must check that the user has the required capability 
    if (!current_user_can('manage_options'))
    {
      wp_die( __('You do not have sufficient permissions to access this page.') );
    }

    // variables for the field and option names 
    $opt_name = 'mt_favorite_color';
    $hidden_field_name = 'mt_submit_hidden';
    $data_field_name = 'mt_favorite_color';

    // Read in existing option value from database
    $opt_val = get_option( $opt_name );

    // See if the user has posted us some information
    // If they did, this hidden field will be set to 'Y'
    if( isset($_POST[ $hidden_field_name ]) && $_POST[ $hidden_field_name ] == 'Y' ) {
        // Read their posted value
        $opt_val = $_POST[ $data_field_name ];

        // Save the posted value in the database
        update_option( $opt_name, $opt_val );

        // Put an settings updated message on the screen

?>
<div class="updated"><p><strong><?php _e('settings saved.', 'menu-test' ); ?></strong></p></div>
<?php

    }

    // Now display the settings editing screen

    echo '<div class="wrap">';

    // header

    echo "<h2>" . __( 'Menu Test Plugin Settings', 'menu-test' ) . "</h2>";

    // settings form
    
    ?>

<form name="form1" method="post" action="">
<input type="hidden" name="<?php echo $hidden_field_name; ?>" value="Y">

<p><?php _e("Favorite Color:", 'menu-test' ); ?> 
<input type="text" name="<?php echo $data_field_name; ?>" value="<?php echo $opt_val; ?>" size="20">
</p><hr />

<p class="submit">
<input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Save Changes') ?>" />
</p>

</form>
</div>

<?php
 
}
A few notes:
  • The WordPress functions such as add_menu_page and add_submenu_page take a capability which will be used to determine whether the top-level or sub-level menu is displayed.
  • The function which is hooked in to handle the output of the page must check that the user has the required capability as well.
  • The WordPress administration functions take care of validating the user login, so you don't have to worry about it in your function.
  • The function example above has been internationalized -- see the Internationalization section of Writing a Plugin for more information.
  • The function processes any entered data before putting the data entry form on the screen, so that the new values will be shown in the form (rather than the values from the database).
  • You don't have to worry about this working the first time, because the WordPress update_option function will automatically add an option to the database if it doesn't already exist.
  • These admin-menu-adding procedures are parsed every single time you navigate to a page in Admin. So if you are writing a plugin which has no options page, but add one later, you can just add it using the instructions above and re-upload, and tweak until you're happy with it. In other words, menus are not "permanently added" or put into a database upon activating a plugin. They're parsed on the fly, so you can add or subtract menu items at will, re-upload, and the change will be reflected right away.

Page Hook Suffix

Every function that adds a new administration menu (add_menu_page()add_submenu_page() and its specialized versions such as add_options_page()) returns a special value called Page Hook Suffix. It can be used later as a hook to which an action called only on that particular page can be registered.
One such action hook is load-{page_hook}, where {page_hook} is the value returned by one of these add_*_page() functions. This hook is called when the particular page is loaded. In the example below, it is used to display the "Plugin is not configured" notice on all admin pages except for plugin's options page:
<?php
add_action('admin_menu', 'my_plugin_menu');

// Here you can check if plugin is configured (e.g. check if some option is set). If not, add new hook. 
// In this example hook is always added.
add_action( 'admin_notices', 'my_plugin_admin_notices' );

function my_plugin_menu() {
	// Add the new admin menu and page and save the returned hook suffix
	$hook_suffix = add_options_page('My Plugin Options', 'My Plugin', 'manage_options', 'my-unique-identifier', 'my_plugin_options');
	// Use the hook suffix to compose the hook and register an action executed when plugin's options page is loaded
	add_action( 'load-' . $hook_suffix , 'my_load_function' );
}

function my_load_function() {
	// Current admin page is the options page for our plugin, so do not display the notice
	// (remove the action responsible for this)
	remove_action( 'admin_notices', 'my_plugin_admin_notices' );
}

function my_plugin_admin_notices() {
	echo "<div id='notice' class='updated fade'><p>My Plugin is not configured yet. Please do it now.</p></div>\n";
}

function my_plugin_options() {
	if (!current_user_can('manage_options'))  {
		wp_die( __('You do not have sufficient permissions to access this page.') );
	}
	echo '<div class="wrap">';
	echo '<p>Here is where the form would go if I actually had options.</p>';
	echo '</div>';
}
?>

----------------------------------------------

5. How to create menus location in theme function.php.

Answer : <?php wp_nav_menu$args ); ?> 

Usage (Showing Default Values)

<?php

$defaults = array(
	'theme_location'  => '',
	'menu'            => '',
	'container'       => 'div',
	'container_class' => '',
	'container_id'    => '',
	'menu_class'      => 'menu',
	'menu_id'         => '',
	'echo'            => true,
	'fallback_cb'     => 'wp_page_menu',
	'before'          => '',
	'after'           => '',
	'link_before'     => '',
	'link_after'      => '',
	'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
	'depth'           => 0,
	'walker'          => ''
);

wp_nav_menu( $defaults );

?>

Examples


Default example

<div class="access">
  <?php wp_nav_menu(); ?>
</div>

Targeting a specific Menu

<?php wp_nav_menu( array('menu' => 'Project Nav' )); ?>

Used in the Twenty Ten theme

<div id="access" role="navigation">

    <?php /*

    Allow screen readers / text browsers to skip the navigation menu and
    get right to the good stuff. */ ?>

    <div class="skip-link screen-reader-text">
        <a href="#content" title="<?php esc_attr_e( 'Skip to content', 'twentyten' ); ?>">
        <?php _e( 'Skip to content', 'twentyten' ); ?></a>
    </div>

    <?php /*

    Our navigation menu.  If one isn't filled out, wp_nav_menu falls
    back to wp_page_menu.  The menu assigned to the primary position is
    the one used.  If none is assigned, the menu with the lowest ID is
    used. */

    wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?>

</div><!-- #access -->

Removing the Navigation Container

In order to remove navigation container, theme location specified in functions.php and used among arguments in function wp_nav_menu ( eg. 'theme_location' => 'primary-menu' ) must have a menu assigned to it in administration! Otherwise argument 'container' => 'false' is ignored.
<?php
function my_wp_nav_menu_args( $args = '' )
{
	$args['container'] = false;
	return $args;
} // function

add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
?>
OR
<?php wp_nav_menu( array( 'container' => '' ) ); ?>

Removing the ul wrap

This example will remove the ul around the list items.
<?php wp_nav_menu( array( 'items_wrap' => '%3$s' ) ); ?>

Adding a Word at the Beginning of the Menu

This example will allow you to add the word of your choice to the beginning of your menu as a list item. In this example, the word "Menu:" is added at the beginning. You may want to set an id on the list item ("item-id" in this example) so that you can use CSS to style it.
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'items_wrap' => '<ul><li id="item-id">Menu: </li>%3$s</ul>' ) ); ?>
----------------------------------------------------------------

6. what is wp_head and wp_footer. what is the need of both of functions in theme development.  

Answers :
The newer versions of WordPress require this in your theme's footer.php file before the </body> tag:
<?php wp_footer();?>
You should also have this in the <head> section of your theme's header.php file:
<?php wp_head();?>
It's worth checking to make sure they are there, especially if your theme was released prior to the release of WordPress v.2.8. If either or both of them are missing, you may have conflicts with plugins not working properly.

------------------------------------------------------------------------------------------------------------------------------------------------------------

7. How to create meta data and update meta data.

Answers: 

Function Reference

Add/Delete Metadata
Get/Update Metadata

Database Requirements

This function assumes that a dedicated MySQL table exists for the $meta_type you specify. Some desired $meta_types do not come with pre-installed WordPress tables, and so they must be created manually.

Default Meta Tables

Assuming a prefix of wp_, WordPress's included meta tables are:
wp_commentmeta 
Metadata for specific comments.
wp_postmeta 
Metadata for pages, posts, and all other post types.
wp_usermeta 
Metadata for users.

Meta Table Structure

To store data for meta types not included in the above table list, a new table needs to be created. All meta tables require four columns...
meta_id 
BIGINT(20)unsignedauto_incrementnot null, primary key.
object_id 
BIGINT(20)unsignednot null. Replace object with the singular name of the content type being used. For instance, this column might be named post_id or term_id. Although this column is used like a foreign key, it should not be defined as one.
meta_key 
VARCHAR(255)
meta_value 
LONGTEXT
--------------------------------------------------------------------------











8. Some useful wordpress inbuild functions.

Answers: 

  1. REMOVING THE AUTO CAPITALISATION OF ‘WORDPRESS’

    When version  3.0 was released a fairly simple filter appeared called capital_P_dangit. This was committed to the core by Matt Mullenweg for the purposes of brand reinforcement. Suffice to say many in the community weren’t thrilled by this passive-aggressive pedantry for a multitude of very good reasons but that’s another story (you can read all about it in Justin Tadlock’s article on the subject).
    // remove capital_P_dangit
    foreach( array( 'the_content', 'the_title', 'comment_text' ) as $filter )
        remove_filter( $filter, 'capital_P_dangit' );
  2. CHANGE EXCERPT LENGTH

    The default excerpts in WordPress are reasonable but rarely fit with the design you are working to. Alter the number of characters returned in an excerpt with the following snippet.
    function theme_excerpt_length( $length ) {
        return 80; // 80 words long
    }
    add_filter('excerpt_length', 'theme_excerpt_length');
  3. CHANGE THE EXCERPT TRUNCATION TEXT

    You can alter the text that appears at the point of truncation, ie. ‘[...]‘, to anything you want, including a useful link to the post page.
    function theme_excerpt_more( $more ) {
        global $post;
        return '&hellip; <a class="read-more" href="'. get_permalink($post->ID) . '">' . __('Continue reading') . '</a>';
    }
    add_filter('excerpt_more', 'theme_excerpt_more');
  4. ADDING CONTACT METHODS TO THE USER PROFILE

    On every recent project we have had there has been a need for extra user data, such as Twitter username, FaceBook URL and so on. The user profile screen can be edited using a combination of action hooks but WordPress also has a very simple way to add extra contact methods.
    function more_contactmethods( $contactmethods ) {
        $contactmethods['twitter'] = 'Twitter username';
        $contactmethods['facebook'] = 'Facebook URL';
        return $contactmethods;
    }
    add_filter( 'user_contactmethods', 'more_contactmethods' );
  5. REMOVING THE INLINE STYLESHEET FROM GALLERIES

    By default WordPress spits out an inline stylesheet whenever the gallery shortcode is used within a post. The reasoning is that users can control the number of columns each gallery has and the sizes of the images within them as well as a few other options. While it is a noble quest to give users more power over their images it also allows them to screw things up in new and exciting ways when using a custom theme. Adding style tags within the body of an HTML document is also invalid markup.
    Thanks to Safirul Alredha for this code:
    // remove gallery shortcode styling
    add_filter('gallery_style',
        create_function(
            '$css',
            'return preg_replace("#<style type=\'text/css\'>(.*?)</style>#s", "", $css);'
        )
    );
  6. REPLACING THE GALLERY SHORTCODE HANDLER

    While the above snippet does a good enough job in many cases I still find the built in gallery shortcode function to be questionable. For example you can change what HTML tags the gallery outputs with (the default being a semantically poor series of definition lists) but there is no way to set theme defaults without parsing post/page content and adding the attributes to the shortcode programmatically. This is a bad idea for general use themes because it will screw up peoples sites if they switch to another theme in future.
    The shortcode can be rescued however by simply removing it and replacing it with your own callback:
    // replace gallery shortcode
    remove_shortcode('gallery');
    add_shortcode('gallery', 'theme_gallery_shortcode');
    
    function theme_gallery_shortcode( $attr ) {
        global $post, $wp_locale;
        // create your own gallery output...
    }
    You can alternatively use the built in shortcode’s internal filter ‘post_gallery’ to change the output and handling of the standard shortcode attributes.
  7. ADDING CUSTOM POST TYPES TO SEARCH RESULTS

    Hopefully any custom post types that are set as publicly queryable will be included in the search results by default in future releases of WordPress but for now you can use the following code:
    function search_post_types( $query ) {
        if ( $query->is_search )
            $query->set( 'post_type', get_post_types( array( 'publicly_queryable' => 1 ) ) );
        return $query;
    }
    add_filter( 'the_search_query', 'search_post_types' );
  8. ADDING CUSTOM POST TYPES TO THE MAIN RSS FEED

    This can make sense for some sites if you want an amalgamated feed of all your content. We use an array filter in this case to get only those post types that have taxonomies so page-like content is ignored.
    function feed_post_types( $vars ) {
        if ( isset($vars['feed']) && !isset($vars['post_type']) )
            $vars['post_type'] = array_filter( get_post_types( array( 'publicly_queryable' => 1 ) ), 'get_object_taxonomies' );
        return $vars;
    }
    add_filter( 'request', 'feed_post_types' );
  9. ENABLE POST THUMBNAILS

    This is one is pretty straightforward. Make use of WordPress 3.0′s post thumbnail feature in your theme.
    add_theme_support( 'post-thumbnails' );
  10. ENABLE SHORTCODES IN THE TEXT WIDGET

    This little trick makes the text widget into a much more powerful tool. It’s used on this site to add an author list to the widget space in the footer, avoiding the need to code a specific author list widget.
    add_filter( 'widget_text', 'do_shortcode' );
---------------------------------------------------------------

9. How to create template in wordpress theme codex.









Answers :   Theme Stylesheet

In addition to CSS style information for your theme, style.css provides details about the Theme in the form of comments. The stylesheet must provide details about the Theme in the form of comments. No two Themes are allowed to have the same details listed in their comment headers, as this will lead to problems in the Theme selection dialog. If you make your own Theme by copying an existing one, make sure you change this information first.
The following is an example of the first few lines of the stylesheet, called the stylesheet header, for the Theme "Twenty Ten":
/*
Theme Name: Twenty Ten
Theme URI: http://wordpress.org/
Description: The 2010 default theme for WordPress.
Author: wordpressdotorg
Author URI: http://wordpress.org/
Version: 1.0
Tags: black, blue, white, two-columns, fixed-width, custom-header, custom-background, threaded-comments, sticky-post, translation-ready, microformats, rtl-language-support, editor-style, custom-menu (optional)

License:
License URI:

General comments (optional).
*/
NB: The name used for the Author is suggested to be the same as the Theme Author's wordpress.org username, although it can be the author's real name as well. The choice is the Theme Author's.


Thanks 

Saturday, 13 April 2013

Joomla code that you should know.

HOW TO GET LOGIN ID

<?php
$user=& JFactory::getuser();
$id2=$user->get('id');
if($id2>0){

}else{
 $mainframe =& JFactory::getApplication('site');
 $mainframe->redirect($indexpath."/index.php");
}
?>

HOW TO GET USER INFO
function  getUserValue($id,$field){

  $db   =& JFactory::getDBO();
  $query="SELECT $field from #__users Where id=".$id;
  $db->setQuery($query);
  $result=$db->loadObject($field);
  
  return str_replace("<br />","\n",$result->$field);

}/*How to show the function data*/
<?php echo getUserValue($this->user->get('id'),'address');?>"
<?php echo getUserValue($id1,'homepage');?>

how to call the function :-

Joomla is an award-winning content management system (CMS), which enables you to build Web sites and powerful online applications.Best of all, Joomla is an open source solution that is freely available to everyone.


1.  Month ,  Date , Year User define Function.


 Html Code

<tr height="20">
            <td align="right" class="normaltext">&nbsp;</td>
            <td align="right" class="normaltext"><div align="left">Date Of Birth :</div></td>
            <td align="left"><select name="month" id="month"  style="width:80px" class="whiteselectsmall">
                <?php echp "month_opt(get_month($uid))"; ?>
              </select>
              <select name="day" id="day" style="width:40px" class="whiteselectsmall">
                <?= set_day($uid) ?>
              </select>
              <span class="normaltext">
              <select name="year" id="day" style="width:80px" class="whiteselectsmall">
              <?=set_year($uid);?>
              </select>
              </span> </td>
          </tr>