Wordpress Notes

10
Template tags for post. the_ID() the_title() the_permalink() the_content() the_author() the_author_posts_link(); -returns the author url(http://localhost/wordpress/author/admin) the_date()-It will be printed once in a page the_time(get_option("date_format")) - It will be printed in all posts the_time() the_tags(',') the_category() the_post_thumbnail() comments_number('No comments','One Comment','% Comments'); -returns number of comments wp_list_comments() Calling files within theme folder. get_header() -header.php get_footer() -footer.php get_sidebar() -sidebar.php get_sidebar('page') -sidebar-page.php Get blog information’s. bloginfo('name') bloginfo('description') bloginfo('stylesheet_url')-returns style.css in current theme directory bloginfo('charset') bloginfo('template_directory')- returns the current theme directory bloginfo('url')-returns site root folder User login logout information’s: wp_loginout(redirect_url,true) - wp_register() is_user_logged_in() We can get current logged in user information by this function: get_currentuserinfo() To use this declare a global variable $current_user Access user’s info: Echo $current_user->ID; Username: user_login, User first name: user_firstname, User last name: user_lastname, User ID: user_ID,

Transcript of Wordpress Notes

Page 1: Wordpress Notes

Template tags for post.

the_ID() the_title() the_permalink() the_content() the_author() the_author_posts_link(); -returns the author url(http://localhost/wordpress/author/admin) the_date()-It will be printed once in a page the_time(get_option("date_format")) - It will be printed in all posts the_time() the_tags(',') the_category() the_post_thumbnail() comments_number('No comments','One Comment','% Comments'); -returns number of comments wp_list_comments()

Calling files within theme folder.

get_header() -header.php get_footer() -footer.php get_sidebar() -sidebar.php get_sidebar('page') -sidebar-page.php

Get blog information’s.

bloginfo('name') bloginfo('description') bloginfo('stylesheet_url')-returns style.css in current theme directory bloginfo('charset') bloginfo('template_directory')- returns the current theme directory bloginfo('url')-returns site root folder

User login logout information’s:

wp_loginout(redirect_url,true) - wp_register() is_user_logged_in() We can get current logged in user information by this function: get_currentuserinfo() To use this declare a global variable $current_user Access user’s info: Echo $current_user->ID; Username: user_login, User first name: user_firstname, User last name: user_lastname, User ID: user_ID,

Page 2: Wordpress Notes

User Email: user_email)

Useful functions.

posts_nav_link() -navigation link to next and previous post. wp_get_archives('type=monthly')-returns monthly archive wp_get_archives('type=yearly')-returns yearly archive wp_get_archives('type=daily')-returns daily archive wp_list_pages() -Will list all pages present in the blog get_search_form() get_comments_number() previous_post_link() next_post_link() get_template_part('slug','name')

Ex:get_template_part( 'loop', 'index' ); will do a PHP require() for the first file that exists among these, in this priority: wp-content/themes/twentytenchild/loop-index.php wp-content/themes/twentytenchild/loop.php

get_the_term_list( $id, $taxonomy, $before, $sep, $after ) - Helps to fetch custom tag or category

Ex: get_the_term_list($post->ID,’category’,’Category: ’,’, ‘,’’);-It will fetch current post categories.

get_the_term_list($post->ID,’post_tag’,’Tags: ’,’, ‘,’’);-It will fetch current post tags.

Fetching Datas

Getting single post

Simple plugin

<?php

/*

Plugin Name: Contact Form

Version:0.1

Author:Karthik

Author URI:http://techpointt.wordpress.com

Plugin URI:http://techpointt.wordpress.com

Description: Contact form helps user's to register for your blog. Admin can view and edit the details of

user's who have registered

*/

function signature(){

global $current_user;

return "<h2>".$current_user->display_name."</h2><br /><code><i>".$current_user-

>user_email."</i></code>";

Page 3: Wordpress Notes

}

add_shortcode('sign','signature');

?>

We can access this plugin with the help of shortcode [sign].

Adding CSS and JavaScript in admin page:

add_action('admin_init','add_stylesheet');

function add_stylesheet(){

wp_register_style('cf-style',plugins_url('cf-style.css',__FILE__));

wp_enqueue_style('cf-style');

wp_register_script('my-script',plugins_url('my-script.js',__FILE__));

wp_enqueue_script('my-script');

}

function scriptsAndStyles(){

wp_register_script('jquery-1.7.1.min',plugins_url('jquery-1.7.1.min.js',__FILE__));

wp_enqueue_script('jquery-1.7.1.min');

wp_register_script('cf_validation',plugins_url('cf_validation.js',__FILE__));

wp_enqueue_script('cf_validation');

}

add_action('wp_print_scripts', 'scriptsAndStyles');

function add_google_jquery() {

if ( !is_admin() ) {

wp_deregister_script('jquery');

wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"), false);

wp_enqueue_script('jquery');

}

}

add_action('wp_print_scripts ', 'add_google_jquery');

Adding styles

add_action('admin_head','tfStylesAndScripts');

function tfStylesAndScripts(){

wp_register_style('tf-style-css',plugins_url('tf-style.css',__FILE__));

wp_enqueue_style('tf_style-css',plugins_url('tf-style.css',__FILE__));

}

Database interaction

select

Global $wpdb;

Page 4: Wordpress Notes

Get_var()-get single value from a table;

Get_row(query,ARRAY_A)-get a row from a table in Array() format

$a = $wpdb->get_results("select * from wp_options limit 0,30",ARRAY_A); //fetches all matches

foreach ($a as $b){

echo "<br>".$b['option_name'];

}

Insert

$wpdb->insert(

‘table_name’,

array(

‘filed’=>’value’

),

Array(

‘%s’//refers that is first inserting data is string %d for number

)

);

Fetch last inserted row id:

$wpdb->insert_id;

Update:

$wpdb->update( $table, $data, $where, $format = null, $where_format = null );

SQL Error:

$wpdb->show_errors();

$wpdb->hide_errors();

$wp_query->found_posts(); //will return number of fetched posts

Plugin Functions:

register_activation_hook( __FILE__, array( 'YourPluginNameInit', 'on_activate' ) );

-this hook will be called during activation of plugin

register_deactivation_hook( __FILE__, array( 'YourPluginNameInit', 'on_deactivate' ) );

-this hook will be called during deactivation of plugin

register_uninstall_hook( __FILE__, array( 'YourPluginNameInit', 'on_uninstall' ) );

-this hook will be called during uninstall.

__FILE__- results current file path

Page 5: Wordpress Notes

Interacting with WP_Option table

add_option()

-add_option(‘variable’,array(‘values’))

Ex:add_option(‘my_details’,array(‘name’=>’karthi’,’email’,’[email protected]’))

get_option()

-retrieve data’s from the table

-get_option(‘variable’)

Ex:get_option(‘date_formate’)

Update_option()

-update_option(‘variable’,’value to be updated’);

Ex: update_option('my_details',array('name'=>’sam’,'email'=>’[email protected]’));

Delete_option()

-delete_option(‘variable’);

Ex:delete_option(‘my_details’);

Interacting with wp_post table

get_posts( $args );

<?php $args = array(

'numberposts' => 5,

'offset' => 0,

'category' => ,

'orderby' => 'post_date',

'order' => 'DESC',

'include' => ,

'exclude' => ,

'meta_key' => ,

'meta_value' => ,

'post_type' => 'post',

'post_mime_type' => ,

'post_parent' => ,

'post_status' => 'publish' ); ?>

Example:

<ul>

<?php

$args = array( 'numberposts' => 5, 'orderby' => 'rand' );

$rand_posts = get_posts( $args );

foreach( $rand_posts as $post ) : ?>

<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

<?php endforeach; ?>

Page 6: Wordpress Notes

</ul>

Including external files

if (is_admin()) {

// we're in wp-admin/

require_once(dirname(__FILE__).'/includes/admin.php');

}

Conditional Tags

Tag Returns True If User is Viewing is_home Blog home page

is_admin Administration interface

is_single Single post page

is_page Blog page

is_category Archives by category

is_tag Archives by tag

is_date Archives by date

is_search Search results

Shortcode

function showTechForm($atts,$content=null){

extract(shortcode_atts(array('id'=>''),$atts));

//return $id;

global $wpdb;

$form = $wpdb->get_row("select * from ".$wpdb->prefix."tForm where

tform_id=".$id,ARRAY_A);

return json_decode(stripslashes($form['tform_form']),JSON_HEX_TAG);

}

add_shortcode(‘TechForm’,’showTechForm’);

Usage: [TechForm id=1]

Page 7: Wordpress Notes

Ajax

$.ajax({

type:"POST",

url:formUrl,

data:formData,

beforeSend:function(){

$('.cf_error').html('<b style="color:#FF0000">Form is being submitted</b>');

},

success:function(data){

$('.cf_error').html('<b style="color:#FF0000">Thank you!! We have received your

form</b>');

},

complete:function(){

//$('#add_details').hide();

$('#add_details').each(function(){

this.reset();

});

}

});

Fetch particular category posts

query_posts(“cat=40&showposts=5”);

while(the_posts()):the_post();

the_title();

endwhile;

wp_reset_query();

query_posts('category_name=technology-science&showposts=7');

We must reset the query after completing our loop.

args:

category_name -category slug

cat - category id.

Showposts -Fetches 5 recent posts from the category.

Login Form

<?php if (!(current_user_can('level_0'))){ ?>

<h2>Login</h2>

Page 8: Wordpress Notes

<form action="<?php echo htmlentities(get_option('home').'/wp-login.php');?>" method="post">

<input type="text" name="log" id="log" value="<?php echo

wp_specialchars(stripslashes($user_login), 1) ?>" size="20" />

<input type="password" name="pwd" id="pwd" size="20" />

<input type="submit" name="submit" value="Send" class="button" />

<p>

<label for="rememberme"><input name="rememberme" id="rememberme"

type="checkbox" checked="checked" value="forever" /> Remember me</label>

<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI'];

?>" />

</p>

</form>

<a href="<?php echo get_option('home'); ?>/wp-login.php?action=lostpassword">Recover

password</a>

<?php } else { ?>

<h2>Logout</h2>

<a href="<?php echo wp_logout_url(htmlentities($_SERVER['REQUEST_URI'])); ?>">logout</a><br />

<a href="http://XXX/wp-admin/">admin</a>

<?php } ?>

Remove particular post category from home page

add_action('pre_get_posts', 'block_cat_query' );

function block_cat_query() {

global $wp_query;

if( is_home() ) {

$wp_query->query_vars['cat'] = '-98';

}

}

Show Related post based on post tags

<?php //for use in the loop, list 5 post titles related to first tag on current post

$backup = $post; // backup the current object

$tags = wp_get_post_tags($post->ID);

$tagIDs = array();

if ($tags) {

$tagcount = count($tags);

for ($i = 0; $i < $tagcount; $i++) {

$tagIDs[$i] = $tags[$i]->term_id;

}

$args=array(

'tag__in' => $tagIDs,

'post__not_in' => array($post->ID),

Page 9: Wordpress Notes

'showposts'=>5,

'caller_get_posts'=>1

);

$my_query = new WP_Query($args);

if( $my_query->have_posts() ) {

while ($my_query->have_posts()) : $my_query->the_post(); ?>

<h3><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title();

?></a></h3>

<?php endwhile;

} else { ?>

<h2>No related posts found!</h2>

<?php }

}

$post = $backup; // copy it back

wp_reset_query(); // to use the original query again

?>

Pagination

//Pagination

function pagination($prev = '«', $next = '»') {

?>

<style type="text/css">

.page-numbers { font-size: 14px; width:30px; display:inline-block; border:1px solid #999999; text-

align:center}

.page-numbers.current { color: #222; }

.page-numbers .dots { letter-spacing: 1px }

a.page-numbers { font-size: 14px; color: #3888ff; }

</style>

<?php

global $wp_query, $wp_rewrite;

$wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;

$pagination = array(

'base' => @add_query_arg('paged','%#%'),

'format' => '',

'total' => $wp_query->max_num_pages,

'current' => $current,

'prev_text' => __($prev),

'next_text' => __($next),

'type' => 'plain'

);

if( $wp_rewrite->using_permalinks() )

$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) .

'page/%#%/', 'paged' );

if( !empty($wp_query->query_vars['s']) )

$pagination['add_args'] = array( 's' => get_query_var( 's' ) );

Page 10: Wordpress Notes

echo paginate_links( $pagination );

};

Usage:To use this pagination, call pagination(‘prev’,’next’) inside the loop;

Adding dashboard widget

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');

function my_custom_dashboard_widgets() {

global $wp_meta_boxes;

wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'custom_dashboard_help');

}

function custom_dashboard_help() {

echo '<p>Welcome to Custom Blog Theme! Need help? Contact the developer <a

href="mailto:[email protected]">here</a>. For WordPress Tutorials visit: <a

href="http://www.wpbeginner.com" target="_blank">WPBeginner</a></p>';

}

Useful function links

http://codex.wordpress.org/Function_Reference/get_the_term_list

http://codex.wordpress.org/Function_Reference/get_terms

http://www.wpbeginner.com/wp-tutorials/25-extremely-useful-tricks-for-the-wordpress-functions-

file/

http://codex.wordpress.org/Function_Reference/register_taxonomy

http://codex.wordpress.org/Developer_Documentation

http://codex.wordpress.org/Function_Reference/add_meta_box

http://codex.wordpress.org/Function_Reference/bloginfo

http://codex.wordpress.org/Function_Reference/get_post

http://codex.wordpress.org/Function_Reference/get_category

http://codex.wordpress.org/Function_Reference/get_page

http://codex.wordpress.org/Function_Reference

http://codex.wordpress.org/Category:Functions