PHP, Wordpress

Useful .htaccess Tricks for WordPress

PHP Developers and WordPress developers some times comes across .htacess file.
this file is configuration file for for security and performance. here i will show few usefull tricks to do with .htacess file. This file is located at root of your website (/public_html/)

Before we start lets grab the .htacess file from FTP and keep one backup (Just for fail safe).
if you dont have any .htacess file in your root folder under public_html.

Protect

  1. Protect wp-config.php file
    1. It was most important to protect your wp-config file because it has all the information about your database. if anyone get this file they can easily connect to our data base. Here  is the code for protecting wp-config.php file
      <files wp-config.php>
      order allow,deny
      deny from all
      </files>
    2.  Protect wp-admin folder
      you can easly genarate login protect for wp-admin folder here is the link how to do it
      http://www.htaccesstools.com/htpasswd-generator/

Read More...

Wordpress

Common WordPress Errors and How to Fix

  1. Syntax errors

This error usually occurs when you are trying to add code snippets into WordPress and have accidentally missed something or the code has incorrect syntax. This will result into a PHP parse error and you will see a notice like:

Parse error - syntax error, unexpected $end in /public_html/site1/wp-content/themes/my-theme/functions.php on line 278

To fix this issue you will have to correct the syntax. Most of the time it is a missing bracket, or some unexpected character in the code.

2. internal server error

WordPress  users may come across is “Internal Server Error”, or sometimes “500 Internal Server Error”. This error usually happens when there is something wrong, but the server is unable to idefntify where the problem is. Since the error message does not indicate where you should look for the error, it pretty much up to you to figure this out. We have compiled a list of solutions that you can try and one of them will help you resolve it.

3. Error Establishing a Database Connection in WordPress

This  error message is clear that your website is unable to connect to the database. However solving this error can be tricky for beginners. Usually this occurs when a user has entered or modified their database credentials.

4. WordPress white screen

This error usually results into a plain white screen with no error message which makes it the most puzzling because you have no clue where to look and what to fix. Most of the time it is caused when a script exhausts PHP memory limit.

5. WordPress Posts Returning 404 Error

The symptoms of this error is that when a user visits a single post on their site they get a 404 page – not found error. The user can browse all other sections of their site including the admin area. The most common cause of this issue is permalink settings in WordPress.

 

Read More...

Wordpress, WordPress

WordPress FAQ

Q. What are the types of hooks in WordPress
a. There are two types of hooks 1) Action hooks 2) Filter hooks

Q. What is custom field in wordpress?
a. Custom field is a meta-data that allows you to store arbitrary information to the wordpress post.

Q. What is the prefix of wordpress tables by default ?
a. By default, wp_ is the prefix for wordpress.

Q. What is WordPress Loop
a. To display post WordPress use PHP code, this code is known as loop.

Q. Why widget does not show up in the sidebar?
a. 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.

Q. What are meta-tags?
a. Meta-tags are keywords and description used to display website or page information.

Q. What are the reasons why one should not hack WordPress core file?
a. The best reason not to hack the core files is that whatever you might be doing has to be reworked as a patch.

Q. How to hide the top admin bar at the frontend in WordPress?
a. Add below line in function.php
add_filter('show_admin_bar', '__return_false');

Q. How to hide Directory Browsing in WordPress from server?
a. Add following code in htaccess file
Options -Indexes

Q. How to display custom field in wordpress?
a. echo get_post_meta($post->ID, 'keyName', true);

Read More...

Wordpress

Create change password Page

to create a change password page for user in WordPress

just save the code into your current theme directory

Create new page in wp-admin/page name it as change

select template “change password”

publish it. thats all its done .

 

code 

<?php
/* Template Name: change password */
global $current_user;
get_currentuserinfo();
require_once( ABSPATH . WPINC . '/registration.php' );
if ( !empty($_POST) && !empty( $_POST['action'] ) && $_POST['action'] == 'update-user' ) {
	/* Update user password */
	if ( !empty($_POST['current_pass']) && !empty($_POST['pass1'] ) && !empty( $_POST['pass2'] ) ) {
		if ( !wp_check_password( $_POST['current_pass'], $current_user->user_pass, $current_user->ID) ) {
			$error = 'Your current password does not match. Please retry.';
		} elseif ( $_POST['pass1'] != $_POST['pass2'] ) {
			$error = 'New passwords do not match. Please retry.';
		} elseif ( $_POST['pass1'] = $_POST['current_pass'] ) {
			$error = 'New passwords and old Password should not be same.';
		}elseif ( strlen($_POST['pass1']) < 6 ) {
			$error = 'New Password has to be minimum 6 characters';
		} elseif ( false !== strpos( wp_unslash($_POST['pass1']), "\\" ) ) {
			$error = 'Password may not contain the character "\\" (backslash).';
		} else {
			$error = wp_update_user( array( 'ID' => $current_user->ID, 'user_pass' => esc_attr( $_POST['pass1'] ) ) );
			if ( !is_int($error) ) {
				$error = 'An error occurred while updating your profile. Please retry.';
			} else {
				$error = false;
			}
		}
		if ( empty($error) ) {
			do_action('edit_user_profile_update', $current_user->ID);
			wp_redirect( site_url('/change/') . '?success=1' );
			
		}
		
	}
}
?>

<?php get_header(); ?>
<div class="leftContent">


	<?php while ( have_posts() ) : the_post(); ?>
				<div class="post" id="<?php the_ID(); ?>">
                    <div class="postHead">
                        <h2><?php the_title(); ?></h2>
					<div class="postMeta">
					</div>
				</div>
     <div class="postContent">
				<?php if ( !empty($_GET['success']) ): ?>
                            <div class="message-box message-success">
                                <span class="icon-thumbs-up"></span>
                                Profile updated successfully!
                               
                            </div>
                <?php endif; ?>
                
                <?php if ( !empty($error) ): ?>
                            <div class="message-box message-error">
                                <span class="icon-thumbs-up"></span>
                                <?php echo $error; ?>
                            </div>
                <?php endif; ?>

				<form method="post" id="adduser" action="">

					<table>
                    <tr>
                        <td>
                            <label for="current_pass">Current Password</label>
                        </td>
                        <td>
                            <input class="text-input" name="current_pass" type="password" id="current_pass">
                        </td>
                     </tr>

					<tr>
                        <td>
                    	<label for="pass1">New Password</label>
                        </td>
                        <td>
						<input class="text-input" name="pass1" type="password" id="pass1">
						 </td>
                     </tr>
					<tr>
                        <td>
                    	<label for="pass2">Confirm Password</label>
                        </td>
                        <td>
						<input class="text-input" name="pass2" type="password" id="pass2">
						 </td>
                     </tr>
                     </table>

<?php
// action hook for plugin and extra fields
do_action('edit_user_profile_update', $current_user);
?>
					<p class="form-submit">
						<input name="updateuser" type="submit" id="updateuser" class="submit button" value="Update profile">
						<input name="action" type="hidden" id="action" value="update-user">
					</p>
				</form>

	<?php endwhile; ?>

	</div><!-- .main-column -->
</div>
</div>
	<?php get_sidebar(); ?>


<?php get_footer(); ?>

 

 

Read More...

Wordpress

Change WordPress default email

Every time someone submitted a comment on your blog, signed up as a user or did anything that required WordPress to generate and send an e-mail, by default the “From Name” in that message appeared as “WordPress” and “From” address was “wordpress@your-domain.com”.
if you want to change this, just copy the below code to your functions.php
/** changing default wordpres email settings */
 
add_filter('wp_mail_from', 'new_mail_from');
add_filter('wp_mail_from_name', 'new_mail_from_name');
 
function new_mail_from($old) {
 return 'your email address';
}
function new_mail_from_name($old) {
 return 'your name or your website';
}

 

Read More...

Wordpress

WordPress post formats

WordPress allows you to switch on different post formats from a set list. You don’t have to use all of them, you simply have to pick which formats suit your site best. At the moment, this list consists of:

  • Aside: Similar to a quick note. Use these for posts like quick updates or custom status’.
  • Gallery: A post containing a gallery of images.
  • Image: A single image, rather than a gallery.
  • Video: A post that has one, or several, videos. The WordPress codex also points out that a single URL may indicate the source of a video, rather than an embedded video.
  • Audio: An audio file or playlist.
  • Link: A simple link to an external site.
  • Quote: A quoted block of text, usually with attribution to a quote’s author.
  • Status: Similar to aside, but much more about a simple one-line status.
  • Chat: A full chat transcript.

In your Functions.php add this code

 

function add_post_formats() {
    add_theme_support( 'post-formats', array( 'gallery', 'quote', 'video', 'aside', 'image', 'link' ) );
}
 
add_action( 'after_setup_theme', 'add_post_formats', 20 );

 

Read More...

Wordpress

WordPress Cheat sheet

This WordPress Cheat Sheet should be enough to get you started developing or tweaking WordPress themes.

Basic Template Files
style.css Style sheet file
index.php Home Page file
single.php Single post page file
archive.php Archive or Category file
searchform.php Search form file
search.php Search content file
404.php Error page file
comments.php Comments template file
footer.php Footer content file
header.php Header content file
sidebar.php Sidebar content file
page.php Single page file
PHP Snippets for Header
bloginfo(‘name’); Title of the site
wp_title(); Title of the specific post or page
get_stylesheet_directory_uri(); The style.css file’s location
bloginfo(‘pingback_url’); Pingback URL for this site
bloginfo(‘template_url’); Location for the site’s theme files
bloginfo(‘version’); WordPress version for the site
bloginfo(‘atom_url’); Atom URL for the site
bloginfo(‘rss2_url’); RSS2 URL for the site
get_site_url(); Exact URL for the site
bloginfo(‘name’); Name of the site
bloginfo(‘html_type’); HTML version of the site
bloginfo(‘charset’); Charset parameter of the site
PHP Snippets for Templates
the_content(); Content of the posts
if(have_posts()): Check if there are posts
while(have_posts()): the_post(); Shows posts if posts are available
endwhile; Closes the ‘while’ PHP function
endif; Closes the ‘if’ PHP function
get_header(); Header.php file’s content
get_sidebar(); Sidebar.php file’s content
get_footer(); Footer.php file’s content
the_time(‘m-d-y’); The date in ’08-18-07′ format
comments_popup_link(); Link for the comments on the post
the_title()’; Title of a specific post or page
the_permalink(); URL of a specific post or page
the_category(); Categor of a specific post or page
the_author(); Author of a specific post or page
the_ID(); ID of a specific post or page
edit_post_link(); Link to edit a specific post or page
get_links_list(); Links from the blogroll
comments_template(); Comment PHP file’s content
wp_list_pages(); List of pages of the site
wp_list_cats(); List of categories for the site
next_post_link(‘%link’); URL to the next post
previoust_post_link(‘%link’); URL to the previoust post
get_calendar()’ The built-in calendar
wp_get_archives(); List of archives for the site
posts_nav_link(); Next and previous post links
bloginfo(‘description’); Site’s description
Navigation menu
Category Based Navigation
<ul id=”menu”>
<li <?php if(is_home()) { ?> class=”current-cat” <?php } ?> >
<a href=”<php bloginfo(‘home’); ?>”>Home</a></li>
<?php wp_list_categories(‘title_li=&orderby=id’); ?>
</ul>
Pages based Navigation
<ul id=”menu”>
<li <?php if(is_home()) { ?> class=”current_page_item” <?php } >>>
<a href=”<php bloginfo(‘home’); ?>”>Home</a></li>
<?php wp_list_pages(‘sort_column=menu_order&depth=1&title_li=’); ?>
</ul>
Extra stuff
/%postname%/ Custom permalinks
include(TEMPATEPATH . ‘/x’); Include any file
the_search_query(); Value for search form
_e(‘Message’); Prints out message
wp_register(); Displays the register link
wp_loginout(); Displas the login/logout link
<!–next page–> Divides the content into pages
<!–more–> Cuts off the content and adds a read more link
wp_meta(); Meta for administrators
timer_stop(1); Time to load the page
echo get_num_queries(); Queries to load the page
The Loop
<php if(have_posts()): ?>
<php while(have_posts()): the_post(); ?>
// Post content here (Custom HTML & PHP code)
<php else; ?>
<php endif; ?>
The Loop
    <php if(have_posts()): ?>
         <php while(have_posts()): the_post(); ?>
    // Post content here (Custom HTML     & PHP code)
      <php else; ?> 
    <php endif; ?>

 

Read More...

Wordpress

Extend User Contact Fieds in WordPress

We can add lots of contact information, depending upon your needs. To extend user contact info, open the files and add in this code

<?php
function my_new_contactmethods( $contactmethods ) {
    // Add Twitter
    $contactmethods['twitter'] = 'Twitter';
    //add Facebook
    $contactmethods['facebook'] = 'Facebook';
 
    return $contactmethods;
}
add_filter('user_contactmethods','my_new_contactmethods',10,1);
?>

 

This is only a basic example and you can make it more complicated depending on your creative needs

Read More...

Wordpress

How to Display any External RSS Feed on Your WordPress Site

Do you know how bloggers who display their other blog’s feed on their site. You want to do it too for extra promotion and traffic. Well here is the tutorial for you. Simply paste the following code in anywhere in your theme:

<?php include_once(ABSPATH.WPINC.'/feed.php');
$rss = fetch_feed('http://feeds.feedburner.com/wpbeginner');
$maxitems = $rss->get_item_quantity(5);
$rss_items = $rss->get_items(0, $maxitems);
?>
<ul>
<?php if ($maxitems == 0) echo '<li>No items.</li>';
else
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<li>
<a href='<?php echo $item->get_permalink(); ?>'
title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
<?php echo $item->get_title(); ?></a>
</li>
<?php endforeach; ?>
</ul>

 

 

Read More...

Wordpress

Taxonomy filter for admin area

While working on custom post everybody struggles while sorting the posts by custom taxonomy,

if you add a code for each taxonomy then it will be lengthy. so here is the code for  sort by all taxonomies.

Add it on your functions.php then sorting will be available on all posts screen of your custom post type.

 

add_action( 'restrict_manage_posts', 'my_restrict_manage_posts' );

function my_restrict_manage_posts() {
    global $typenow, $post, $post_id;

	if( $typenow != "page" && $typenow != "post" ){
		//get post type
		$post_type=get_query_var('post_type'); 
	
		//get taxonomy associated with current post type
		$taxonomies = get_object_taxonomies($post_type);
	
		//in next loop add filter for tax
		if ($taxonomies) {
			foreach ($taxonomies as $tax_slug) {
				$tax_obj = get_taxonomy($tax_slug);
				$tax_name = $tax_obj->labels->name;
				$terms = get_terms($tax_slug);
				echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
				echo "<option value=''>Show All $tax_name</option>";
				foreach ($terms as $term) { 
					$label = (isset($_GET[$tax_slug])) ? $_GET[$tax_slug] : ''; // Fix
					echo '<option value='. $term->slug, $label == $term->slug ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>';
				}
				echo "</select>";
			}
		}
	}
}

 

Read More...

Wordpress

Creating custom Post Type In WordPress

WordPress big advantage while comparing with other CMS is Custom Post type mechanism.
Custom post type allows to create large variety of content.
Lets have a look at how to create a custom post type
Custom post types are available from WordPress 2.9.
Custom post type is nothing more than a regular post.
You could create custom post types for books, movies, reviews, Books and so on.

Creating custom post type

To create custom Post type we have a plenty of plugins but we can achieve this by simple script.
Lets create a custom post type for books.
Below is the script for creating custom post type.

function Books() {
$labels = array(
'name' => _x( 'Books', 'post type general name' ),
'singular_name' => _x( 'Book', 'post type singular name' ),

'add_new' => _x( 'Add New', 'book' ),

'add_new_item' => __( 'Add New Book' ),

'edit_item' => __( 'Edit Book' ),

'new_item' => __( 'New Book' ),

'all_items' => __( 'All Books' ),

'view_item' => __( 'View Book' ),

'search_items' => __( 'Search Books' ),

'not_found' => __( 'No Books found' ),

'not_found_in_trash' => __( 'No Books found in the Trash' ),

'parent_item_colon' => '',

'menu_name' => 'Books'

);

$args = array(

'labels' => $labels,

'description' => 'Holds our Books and Book specific data',

'public' => true,

'menu_position' => 5,

'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),

'has_archive' => true,

);

register_post_type( 'Book', $args );

}

add_action( 'init', 'Books' );

Now lets’s discuss about the parameters
labels
Label Option is an array for different labels for our custom post type
description 

A small explanation about the custom Post type.

public

All to do with Visibiity

menu_positions

To define the position of the custom post type in admin menu.

supports

to get default WordPress controls in edit sections

has_archive

To create the URL rewrite

 

Read More...

Wordpress

Correcting wp-admin 404 error for wordpress under IIS

If your server is on IIS  and   running WordPress and experiencing an issue where navigating to /wp-admin results in either a blank page or a 404 error, you may need an additional rule in your .htaccess file. Generally you’ll find that, assuming you’re set up properly, you can reach the admin section by appending /index.php to the URL, but who wants to do that every time?

The rule necessary tells the standard permalink rules to ignore the wp-admin directory when performing rewrites. Simply add the following condition to your .htaccess file:

Here is the .htacess file just upload it into wordpress root folder
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_URI} !^/(wp-admin|wp-admin/.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

 

Read More...

Wordpress

WordPress Trends Infographic

Interesting story about WordPress on elegant themes

 

WordPress Trends Infographic

 

Read More...

Wordpress

How to Move a WordPress Site from One Server to Another

Step 1: Make a Local Copy of the Existing WordPress Site Files

The first thing to do is connect to the FTP server which provides access to the files for the existing WordPress installation. Getting an entire site is time consuming and, with any decent FTP client, it’s automated, so I make this step one. Just connect via FTP and sync a directory on your local disk to the document root which contains your live WordPress install. Now, with files, we can move on to other steps.

Step 2: Get a Dump of Your Current WordPress Database

The easiest tool to use here is going to be PHPmyadmin All hosting providers offer this service to their users. Follow these steps to get your existing database exported:

  • Connect to the instance of phpMyAdmin which provides access to the database for your current site. Enter your credentials to log in to the management interface.
  • Select the database for your existing WordPress installation from the list on the left. (in this case my present database name is “craniumstorm”)

1

Click ‘Export’ at the top of the window

2

Ensure that the radio button for the ‘Quick’ export method is selected. Click the ‘Go’ button to download a .sql file containing a dump of your current database table structure along with all of your existing data.

3

Step 3: Change database name and new domain name

Make a copy of downloaded database file and Open the sql file in a text editor like notepad

  1. Find the old database name and replace it with your new database name.
  2. Find your old domain name and replace it with your new domain name.

Save the file.

 

Step 4: Import Your Database

Now you have to reverse the export process to populate your new database.

  1. Log in to the phpMyAdmin interface for the new database.
  2. Select the new database from the list on the left (see Fig. 1, above).
  3. This time, click the ‘Import’ tab at the top of the window.
  4. Now you’ll have to select the file you just downloaded containing your database dump so that you can upload it here. Click the ‘Choose File’ button and locate the .sql file which you have edited with new details.

4

All that’s left for this step is to click the ‘Go’ button to import your data.

Login to your admin panel with your old server Privileges and check is everything is ok.

Step 5: Upload the WordPress Site and Edit Your Configuration

Uploading the entire WordPress site is the next logical step here.

  1. When you’re ready, connect to the FTP host for the new site.
  2. Upload the entire contents of the site to its new home.
  3. Edit your /wp-config.php file to include the correct information for your new database:
    1. // ** MySQL settings – You can get this info from your web host ** //
    2. /** The name of the database for WordPress */
    3. define(‘DB_NAME’, ‘databasename’);
    4. /** MySQL database username */
    5. define(‘DB_USER’, ‘username’);
    6. /** MySQL database password */
    7. define(‘DB_PASSWORD’, ‘somePass’);
    8. /** MySQL hostname */
    9.  define(‘DB_HOST’, ‘localhost’);

This has come up a couple of times now, so I’m going to say here in advance that you should try logging into the admin panel in the new location at this point. If you get in without any problems, go to Settings > Permalinks and click ‘Update Permalinks’ to make sure WordPress updates the .htaccess file.

Read More...

FAQ, PHP, PHP

PHP interview questions and answers

1)    What does a special set of tags <?= and ?> do in PHP?

2)    What’s the difference between include and require?

3)    I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?

4)    Would I use print “$a dollars” or “{$a} dollars” to print out the amount of dollars in this example?

5)    How do you define a constant?

6)    How do you pass a variable by value?

7)    Will comparison of string “10” and integer 11 work in PHP?

8)    When are you supposed to use endif to end the conditional statement?

9)    Explain the ternary conditional operator in PHP?

10) How do I find out the number of parameters passed into function?

11) If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?

12) What’s the difference between accessing a class method via -> and via ::?

13) Are objects passed by value or by reference?

14) How do you call a constructor for a parent class?

15) What’s the special meaning of __sleep and __wakeup?

16) Why doesn’t the following code print the newline properly?

17) Would you initialize your strings with single quotes or double quotes?

18) How come the code <?php print “Contents: $arr[1]”; ?> works, but <?php print “Contents: $arr[1][2]”; ?> doesn’t for two-dimensional array of mine?

19) What is the difference between characters 23 and x23?

20) With a heredoc syntax, do I get variable substitution inside the heredoc contents?

 

 Just press Like button to download Answers

 

Read More...