Monday, 5 January 2015

Get custom field value

custom field name - test
value - abc

$mykey_values = get_post_custom_values( 'test' );

  echo $mykey_values[0];

result - abc

Sunday, 4 January 2015

tips to hooks in wordpress

Below is a simple example of using an action hook by creating an action:

<?php
add_action( 'wp_head', 'my_actionhook_example' );
function my_actionhook_example() {
echo '<meta name="description" content="Hello world. This meta description was created using my action hook example." />' . "\n";
} // The end of my_actionhook_example()
?>
The above code is something which you might place in your theme or child-theme’s functions.php file and when it is executed it will simply echo a meta tag inside the head portion of a WordPess page.

The add_action line registers (or hooks) your action (called my_actionhook_example) to the action hook which is called wp_head.

If you recall from earlier we said that an action is a customized function which you create and in the example above you can see the function definition and the code for the function which simply adds some meta data.

Filter Hooks
Filter hooks are another type of WordPress hook and these deal with the manipulation of text and other output.
A filter hook can be identified by either of the following pieces of code:

apply_filters( $tag, $value );
apply_filters_ref_array( $tag, $args );
For example in the WordPress core you will find a line of code like the following:

$title = apply_filters('wp_title', $title, $sep, $seplocation);

The above example shows the creation of the wp_title filter hook. This hook allows you to manipulate a page’s title before it is displayed in the browser.

As for the action hooks, filter hooks follow a similar pattern. The $tag represents the name of the hook and there are also parameters which are passed to filters which are registered to the hook.

Unlike the do_action hook, the apply_filters hook will always pass a parameter to the filter (which is the customized function you write) and your filter in turn must always return the $value parameter back to WordPress.

To create and register a filter you will use a similar approach to creating an action. For example you will write a function (known as the filter) which does something and you will also register your filter to a particular hook using a command such as:

add_filter ( 'hook_name', 'your_filter', [priority], [accepted_args] );

where:

hook_name = name of the hook you want register to
your_filter = the name of your filter (or function)
priority = (optional) integer which represents the order your filter should be applied. If no value is added, it defaults to 10.
accepted_args = (optional) integer argument defining how many arguments your function can accept (default 1) because your filter must accpet at least one parameter which will be returned.
Let’s look at a simple example of creating and registering a filter.
The code below shows something you might add in your customized theme functions.php file to append the site name to a page’s title:

<?php

add_filter( ‘wp_title’, ‘mytest_add_sitename_to_title’, 10, 2 );

mytest_add_sitename_to_title( $title, $sep ) {

/* Retrieve site name. */

$name = get_bloginfo( ‘name’ );

/* Append site name to $title. */

$title .= $sep . ‘ ‘ . $name;

/* Return the title. */

return $title;

}

?>

We can see from this example that we are registering our filter which is called mytest_add_sitename_to_title to the wp_title filter hook and we are assigning a priority of 10 and specifying that our filter function will accept 2 arguments.

link : https://www.tipsandtricks-hq.com/wordpress-action-hooks-and-filter-hooks-an-introduction-4163

custom taxonamy plugin files

my-custom-taxonomies.php
<?php
/**
 * My Custom Taxonomies
 *
 * Demonstrates how to create custom taxonomies using the WordPress API.
 * Showcases both hierarchical and non-hierarchical taxonomies.
 *
 * @link              http://code.tutsplus.com/series/the-beginners-guide-to-wordpress-taxonomies--cms-706
 * @since             1.0.0
 * @package           Custom_Taxonomies
 *
 * @wordpress-plugin
 * Plugin Name:       My Custom Taxonomies
 * Plugin URI:        http://example.com/plugin-name-uri/
 * Description:       Demonstrates how to create custom taxonomies using the WordPress API.
 * Version:           1.0.0
 * Author:            Tom McFarlin
 * Author URI:        http://tommcfarlin.com/
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 */
/** Loads the custom taxonomy class file. */
require_once( dirname( __FILE__ ) . '/class-my-custom-taxonomies.php' );

/**
 * Creates an instance of the My_Custom_Taxonomies class
 * and calls its initialization method.
 *
 * @since    1.0.0
 */
function custom_taxonomies_run() {

    $custom_tax = new My_Custom_Taxonomies();
    $custom_tax->init();

}
custom_taxonomies_run();

?>
----------------------------------File 2 --------------------------------------------------------
this is a class file name of file is - class-mycustom-taxonomies.php
<?php

/**
 * The core plugin class file
 *
 * Defines the functions necessary to register our custom taxonomies with
 * WordPress.
 *
 * @link       http://code.tutsplus.com/series/the-beginners-guide-to-wordpress-taxonomies--cms-706
 * @since      1.0.0
 *
 * @package    Custom_Taxonomies
 * @author     Tom McFarlin <tom@tommcfarlin.com>
 */
class My_Custom_Taxonomies {

    /**
     * Initializes the plugin by registering the hooks necessary
     * for creating our custom taxonomies within WordPress.
     *
     * @since    1.0.0
     */
    public function init() {

 add_action( 'init', array( $this, 'init_photographs' ) );
      add_action( 'init', array( $this, 'init_videos' ) );
 add_action( 'init', array( $this, 'init_film_type' ) );

    }
/**
 * Creates the Photographs taxonomy that appears on all Post dashboard
 * pages.
 *
 * @since    1.0.0
 */
public function init_photographs() {

    $labels = array(
        'name'          => 'Photographs',
        'singular_name' => 'Photograph',
        'edit_item'     => 'Edit Photograph',
        'update_item'   => 'Update Photograph',
        'add_new_item'  => 'Add New Photograph',
        'menu_name'     => 'Photographs'
    );

    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'rewrite'           => array( 'slug' => 'photograph' )
    );

    register_taxonomy( 'photograph', 'post', $args );

}
/**
 * Creates the Videos taxonomy that appears on all Post dashboard
 * pages.
 *
 * @since    1.0.0
 */
public function init_videos() {

    $labels = array(
        'name'          => 'Videos',
        'singular_name' => 'Video',
        'edit_item'     => 'Edit Video',
        'update_item'   => 'Update Video',
        'add_new_item'  => 'Add New Video',
        'menu_name'     => 'Videos'
    );

    $args = array(
        'hierarchical'      => false,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'rewrite'           => array( 'slug' => 'video' )
    );

    register_taxonomy( 'video', 'post', $args );

}



/**
 * Creates the Film Type taxonomy that appears on all Post dashboard
 * pages.
 *
 * @since    1.0.0
 */
public function init_film_type() {

    $labels = array(
        'name'          => 'Film Type',
        'singular_name' => 'Film Type',
        'edit_item'     => 'Edit Film Type',
        'update_item'   => 'Update Film Type',
        'add_new_item'  => 'Add New Film Type',
        'menu_name'     => 'Film Type'
    );

    $args = array(
        'hierarchical'      => false,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'rewrite'           => array( 'slug' => 'film-type' )
    );

    register_taxonomy( 'film-type', 'post', $args );

}

}

The basics - hooks, actions and filters

 There are two types of hooks: 
1. actions   and
2. filters.

Actions and filters allow you add your own functionality or modify your site’s behaviour by hooking a callback function onto a specific tag in the core code, setting priorities and using parameters and arguments passed to the callback function.

ACTION AND FILTERS DIFFERENCE :-


  • Actions allow you to add extra functionality at a specific point in the processing of the page—for example, you might want to add extra widgets or menus, or add a promotional message to your page.
  • Filters allow you to intercept and modify data as it is processed—for example, you might want to insert another CSS class in a WordPress HTML element, or modify some of Customizr’s page blocks.
In brief: actions do stuff; filters change stuff.

Getting down to details

When Gill comes by, tell her to go to the store to get some paint. When Jack comes by bragging about how great he is, get him to say that Gill is better.
Wait, what? I thought this was an article about actions, filters and hooks? Instead, we’re talking about arrogant home-improvers? Well yes. These are ways of understanding what’s going on when you use actions and filters.
Let’s look at actions and filters in turn.

Actions:

When Gill comes by, tell her to go to the store to get some paint.
We can do this by hooking onto an action hook. That is, we can use the  add_action function (written  add_action()) to add functionality—do stuff—at a particular point.
Sending Gill to the store to get paint might look like this in PHP:

/ Send Gill to get paint
add_action( 'after_gill_arrives' , 'send_gill_to_get_paint', 10 , 2 );
function send_gill_to_get_paint( $gill_has_keys, $gill_has_car ) {

// If $gill_has_keys and $gill_has_car are both true
if ( $gill_has_keys && $gill_has_car ) {
echo 'Gill, please go to the store and get some paint. Thank you!';
}
}

In simple terms,  add_action() tells WordPress to do something when it arrives at the specified  do_action() hook.

But we can only use our  add_action() in the example above if we know that the  'after_gill_arrives' action hook exists in our theme/plugin. Our theme/plugin needs to have something like this in it:
do_action( 'after_gill_arrives' , $gill_has_keys = true , $gill_has_car = true );



Filters:

// Cut Jack's boasting
add_filter( 'jacks_boast' , 'cut_the_boasting');
function cut_the_boasting($boast) {
// Replace "best" with "second-best"
$boast = str_replace ( "best" , "second-best" , $boast );
// Append another phrase at the end of his boast
$boast = $boast . ' However, Gill can outshine me any day.';
return $boast;
}


What did we just do there?


  • We looked for a particular thing that we wanted to change—Jack’s boast that he’s the best; in programming terms the  'jacks_boast' filter;
  • When we found it, we changed it—we changed “best” to “second-best” and we added another phrase on the end; in programming terms, we filtered the output by calling the  cut_the_boasting() function, which replaced part of the string and appended another string (the “.” character concatenates two PHP strings);
  • We used the  $boast argument (in this case a string that says something like “I’m the best!”) as the basis for our changes.
  • We returned a string at the end of the function. This is very important. If you don’t return a string in a filter, you might disrupt the functioning of a program (in this case, we would simply silence Jack … which may not be a bad thing).

How did it work?

In simple terms,  add_filter() tells WordPress to swap its data with ours when it arrives at the  'jacks_boast' filter hook. Neat!
But we can only use our  add_filter() filter in the example above if we know that the  'jacks_boast' filter hook exists in our theme/plugin. (If the hook doesn’t exist, our function will simply never be called.) Behind the scenes, the theme/plugin has to have something like this in it:
echo apply_filters('jacks_boast',"I'm the best in the world.");
This tells WordPress to create a hook called  'jacks_boast', apply any filters that are attached to this hook, and pass those filters the string “I’m the best in the world.”. If there are no filters attached to the hook, then the  apply_filters() function will simply return the string “I’m the best in the world.”: effectively a default.
// Change url that is linked from logo
add_filter( 'tc_logo_link_url', 'change_site_main_link' );
function change_site_main_link() {
return 'http://example.com';
}


Why use hooks?

  • Change almost anything in WordPress—even quite fundamental things—because a lot of WordPress’s core functions use actions and filters;
  • Make changes easily: once you’ve understood the concepts, you can make some incredibly complex changes very quickly;
  • Change Customizr’s behaviour at the source, rather than trying to retro-fit an inappropriate solution with HTML and CSS;
  • Make your own changes easy to understand and easier to debug, because your code is reduced to a minimum;
  • Enable and disable your changes easily because each piece of code is a small unit in your functions.php;
  • Make your changes relatively upgrade-proof because you no longer need to edit or copy WordPress’s or Customizr’s core files;
  • Share your knowledge and swap code snippets with others.

Friday, 2 January 2015

all wordpress functions used to plugin and post types and short codes

######Show post on the home page ######

<?php query_posts('p=id'); ?> /// example query_posts('p=21') 21 is post id //
<?php while (have_posts()) : the_post(); ?>
<h4><?php the_title(); ?></h4>
<?php the_content(); ?>
<?php endwhile;?>


#########activate plugin create table and deactive delete table ##########
<?php

function myplugin_activate()

{
global $wpdb;

$tablename = 'user_file';

$table = $wpdb->prefix . $tablename;

$sql= "CREATE TABLE $table
(fileID INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
userID INT( 7 ) NOT NULL ,
userName VARCHAR(250),
fileDescription MEDIUMTEXT NULL ,
fileName VARCHAR( 250 ) NULL ,
fileUploadedOn DATETIME NOT NULL )";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);

}

function myplugin_deactivate()

{
global $wpdb;

$tablename = 'user_file';

$table = $wpdb->prefix . $tablename;

$wpdb->query("DROP TABLE IF EXISTS ".$table);

}
register_activation_hook( __FILE__, 'myplugin_activate' );
register_deactivation_hook( __FILE__, 'myplugin_deactivate');



?>

##### show plugin in the widget  ######
<?php
function viral_video()
{
  echo "<h2>viral video voodoo</h2>";
}

function widget_viral_video($args) {
  extract($args);
  echo $before_widget;
  echo $before_title;?>My Widget Title<?php echo $after_title;
viral_video();
  echo $after_widget;
  echo "hello"; ###### show msg on the front end ####
  }
 function viral_video_init()
{
  register_sidebar_widget(__('viral video voodoo'), 'widget_viral_video');    
}
add_action("plugins_loaded", "viral_video_init");

?>
### create short code of the plugin #####
<?php

 //[foobar]
function foobar_func()
{
echo "hellooooo";
 }

 add_shortcode( 'foobar', 'foobar_func' ); // foobar is short code and  foobar_func is function name

 ?>

<?php  add_filter( 'widget_text', 'do_shortcode' ); // this code use in function.php to execute short code in the widget

  echo do_shortcode( '[shortcode title here]' ); // this code short code execute in the template file or anywhere in the site
  ?>

 ###### create custom post #####
 <?

 function manager_install() {
 manager_create_post_type();
}
add_action( 'init', 'manager_create_post_type' );
 function manager_create_post_type() {
register_post_type( 'manager',
array(
'labels' => array(
'name' => __( 'manager' ),
'singular_name' => __( 'manager' ),
'add_new' => __('Add New', 'manager'),
'add_new_item' => __('Add New manager'),
'edit_item' => __('Edit manager'),
'new_item' => __('New manager')
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'products'),
'supports' => array(
  'title',
  'thumbnail',
  'comments',
  'editor')
)
);
}
 ?>

  UPDATE wp_posts SET guid = REPLACE (guid, 'http://www.oldsiteurl.com', 'http://www.newsiteurl.com');





the constructor method

The __constructor() function is used to initialize the object when we want to load an ACL. It is called automatically when we call new ACL();. It is then passed a single, optional argument of the user to load the ACL for. Inside the constructor, we check to see if a user ID was passed in. If no ID was passed, we assume that we will load the ACL for the currently logged in user; so we read in the session variable for that. Alternatively, if we pass in a user ID, it allows us to read and edit the ACL for a user other than the one logged in (useful for your admin page).


After we read in the user ID, we call getUserRoles() to generate an array of the roles the user is assigned to and store it in the $userRoles class variable. At the end of the constructor, we call buildACL() to generate the actual ACL. The method named ACL()is a crutch for PHP4 installs. When you call new ACL() in PHP5, the PHP interpreter runs the __constructor() method. However, when you run the same code in PHP4, the interpreter runs ACL(). By providing a method named the same as the class, we make the class PHP4 compatible.
Any time we create a new ACL object by passing in a user ID, that object will hold the permissions for the user who was passed in.

Now, lets add some more helper methods to the same class file. These methods will provide support to the other methods by performing specialized tasks:

ob_start and ob_end_flush meaning dscribed

 we call session_start(); we will not actually use the session variables but you will need it as part of the user login system. Then, we call ob_start() to create an output buffer. Typically, when PHP generates the page, it is sent to the browser as it is generating. By using ob_start(), the page and headers aren't sent to the browser until they've loaded completely, or until we call ob_end_flush(). By buffering the page, we are able to redirect using PHP at any point on the page, instead of just at the top. After the headers are sent, our only redirect option is with JavaScript. An enterprising hacker could easily turn JavaScript off, and then see our unsecured page in all it's glory. This one line allows us to deny the user access at any point in the page if needed.

Lines 4-8 set up our variables. $hasDB is a boolean used to determine if we are connected. $server, $user, $pass, and $db are the connection arguments for the server. Line 9 connects to the server, while line 10 determines if the connection was successful. If it was, we select the database to use; if it wasn't, we display an error message using die().