Prevent script injection

For protect your WordPress blog from script injection, and unwanted code of _REQUEST and /or GLOBALS. I found this code on wprecipes. Simple copy and paste the code below to your .htaccess in the root which helps is script injection.

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]

Blocking Search Engine Spiders from Indexing the Admin Section

Search engine spiders crawl over your entire WordPress site and index every content. For stop hacking sensitive information We can disallow search engines to index the admin section which contains all the sensitive information. The easiest way to prevent the crawlers from indexing the admin directory, is to create a robots.txt file in your root directory. Then place the following code in the file:

#
User-agent: *
Disallow: /cgi-bin
Disallow: /wp-admin
Disallow: /wp-includes
Disallow: /wp-content/plugins/
Disallow: /wp-content/cache/
Disallow: /wp-content/themes/
Disallow: */trackback/
Disallow: */feed/
Disallow: /*/feed/rss/$
Disallow: /category/*

Not So in wordpress site. We can disallow crawler for any type of project. Simply write “Disallow: / directoryname” in robot.txt and upload the file in root of the project.

Join relation with post and texnomony using wordpress query

How to write a query for creating relationship with post and taxonomy. Before writing query dont forgot to define global $wpdb variable. $wpdb is a global variable which instantiate of the wpdb class defined in /wp-includes/wp-db.php. See below example.

global $wpdb;

$cat_id = 14; // The category id to select
$pop = $wpdb->get_results("SELECT p.id, p.post_title, p.comment_count
FROM $wpdb->posts p
JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id)
JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
JOIN $wpdb->terms t ON (tt.term_id = t.term_id)
WHERE p.post_type='post'
AND p.post_status = 'publish'
AND tt.taxonomy = 'category'
AND t.term_id = $cat_id
ORDER BY comment_count DESC LIMIT 9");  	      

foreach ($pop as $post): setup_postdata($post); 
 echo $post->ID; // Post Id
 
the_title();  //post title

endforeach;
wp_reset_postdata();

Similarly we provide another example for fetching records of post and post meta.

    global $wpdb;
    $querystr = "
    SELECT $wpdb->posts.* 
    FROM $wpdb->posts, $wpdb->postmeta
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
    AND $wpdb->postmeta.meta_key = 'tag' 
    AND $wpdb->postmeta.meta_value = 'email' 
    AND $wpdb->posts.post_status = 'publish' 
    AND $wpdb->posts.post_type = 'post'
    AND $wpdb->posts.post_date < NOW()
    ORDER BY $wpdb->posts.post_date DESC
 ";

 $pageposts = $wpdb->get_results($querystr, OBJECT); 

This will result an array. Print information using foreach loop.

How to create customize mysql query in wordpress instead of using hooks

Hello guys some time we are facing problem for making logical relation which is not possible by using word press predefined functions. In this article I guide how to write query in wordpress.

WordPress defines a class called wpdb, which contains a set of functions used to interact with a database. Its primary purpose is to provide an interface with the WordPress database, but can be used to communicate with any other appropriate database

Using the $wpdb Object

$wpdb is a global variable using the global keyword.Which is an instantiation of the wpdb class defined in /wp-includes/wp-db.php.

// 1st Method - Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object

global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );

SELECT a Variable

The get_var function returns a single variable from the database. Though only one variable is returned, the entire result of the query is cached for later use. Returns NULL if no result is found.

<?php $wpdb->get_var( 'query', column_offset, row_offset ); ?>

query 
(string) The query you wish to run. Setting this parameter to null will return the specified variable from the cached results of the previous query.
column_offset 
(integer) The desired column (0 being the first). Defaults to 0.
row_offset 
(integer) The desired row (0 being the first). Defaults to 0.

Examples

Retrieve and display the number of users.

<?php  $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" );  echo "<p>User count is {$user_count}</p>";  ?>  

SELECT a Row

<?php $wpdb->get_row('query', output_type, row_offset); ?>
query 
(string) The query you wish to run.
output_type 
One of three pre-defined constants. Defaults to OBJECT.

  • OBJECT – result will be output as an object.
  • ARRAY_A – result will be output as an associative array.
  • ARRAY_N – result will be output as a numerically indexed array.

Example

$mylink = $wpdb->get_row( "SELECT * FROM $wpdb->links WHERE link_id = 10" );

INSERT row

Insert a row into a table.

<?php $wpdb->insert( $table, $data, $format ); ?> 

table
(string) The name of the table to insert data into.
data
(array) Data to insert (in column => value pairs). Both $data columns and $data values should be “raw” (neither should be SQL escaped).
format
(array|string) (optional) An array of formats to be mapped to each of the values in $data. If string, that format will be used for all of the values in $data. If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.

Examples

Insert two columns in a row, the first value being a string and the second a number:

$wpdb->insert( 
	'table', 
	array( 
		'column1' => 'value1', 
		'column2' => 123 
	), 
	array( 
		'%s', 
		'%d' 
	) 
);

REPLACE row

Replace a row in a table if it exists or insert a new row in a table if the row did not already exist.

<?php $wpdb->replace( $table, $data, $format ); ?> 

table
(string) The name of the table to replace data in.
data
(array) Data to replace (in column => value pairs). Both $data columns and $data values should be “raw” (neither should be SQL escaped).
format
(array|string) (optional) An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.

Examples

Replace a row, the first value being the row id, the second a string and the third a number:

$wpdb->replace( 
	'table', 
	array( 
                'indexed_id' => 1,
		'column1' => 'value1', 
		'column2' => 123 
	), 
	array( 
                '%d',
		'%s', 
		'%d' 
	) 
);

UPDATE rows

Update a row in the table. Returns false if errors, or the number of rows affected if successful.

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

table 
(string) The name of the table to update.
data 
(array) Data to update (in column => value pairs). Both $data columns and $data values should be “raw” (neither should be SQL escaped). This means that if you are using GET or POST data you may need to use stripslashes() to avoid slashes ending up in the database.
where 
(array) A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be “raw”.
format 
(array|string) (optional) An array of formats to be mapped to each of the values in $data. If string, that format will be used for all of the values in $data.
where_format 
(array|string) (optional) An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where.

Possible format values: %s as string; %d as integer (whole number) and %f as float.

Return values: This function returns the number of rows updated, or false if there is an error. Keep in mind that if the $data matches what is already in the database, no rows will be updated, so 0 will be returned. Because of this, you should probably check the return with false === $result

Examples

Update a row, where the ID is 1, the value in the first column is a string and the value in the second column is a number:

$wpdb->update(   	
'table',   	
array(   		
'column1' => 'value1', // string  		
'column2' => 'value2' // integer (number)   	
),   	array( 'ID' => 1 ),   	
array(   		
'%s',	// value1  		
'%d'	// value2  	
),   	
array( '%d' )   ); 
 

Attention: %d can’t deal with comma values – if you’re not using full numbers, use string/%s.

DELETE Rows

The delete function was added in WordPress 3.4.0, and can be used to delete rows from a table. The usage is very similar to update and insert. It returns the number of rows updated, or false on error.

Usage

 <?php $wpdb->delete( $table, $where, $where_format = null ); ?> 

Parameters

$table
(string) (required) Table name.

Default: None

$where
(array) (required) A named array of WHERE clauses (in column -> value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be ‘raw’.

Default: None

$where_format
(string/array) (optional) An array of formats to be mapped to each of the values in $where. If a string, that format will be used for all of the items in $where. A format is one of ‘%d’, ‘%f’, ‘%s’ (integer, float, string; see below for more information). If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types.

Default: null

Examples

// Default usage.
$wpdb->delete( 'table', array( 'ID' => 1 ) );

// Using where formatting.
$wpdb->delete( 'table', array( 'ID' => 1 ), array( '%d' ) );

Source

How to create add to cart button for variable type product

There’s a WooCommerce builtin shortcode to add a product to cart, by default the shortcode works only for simple product, not for variable products, as when using this shortcode you can’t define variations. You can use these two shortcodes [add_to_cart id=’XX’] and [add_to_cart_url id=’XX’] for simple products.

But what if you want to create a “add to cart” button for variable products? Let’s say you want to create a add to cart button for adding X product with Y Size?

Well, you need to add variable product to cart using the URL and create a url similar to this:

http://mysite.com/cart/?add-to-cart=PRODUCT_ID&variation_id=VARIATION_ID&attribute_size=ATTRIBUTE_SLUG

How can you use it?
Best and easy example:

<a href="http://mysite.com/cart/?add-to-cart=9499&variation_id=9561&attribute_size=X">Add To Cart</a>

You can use it by another way

<form action="<?php echo bloginfo('url')?>/cart/" method="get">
<input type="hidden" name="add-to-cart" value="9499" />
<input type="hidden" name="variation_id" value="9561" />
<input type="hidden" name="attribute_size" value="XL">
<button type="submit" class="single_add_to_cart_button button alt">Add To Cart</button>
</form>

WordPress – Header May Not Contain More Than a Single Header

The following error is caused by a space after the site or home URL in the WordPress database:

Warning: Header may not contain more than a single header, new line detected.

To fix this error, you can make changes to the site or home URL from within the WordPress Dashboard or through the WordPress installation’s database.

Fix URLs within the WordPress Dashboard (Recommended)

To fix the home and site URLs from within the WordPress Dashboard:

  1. Log into your WordPress Dashboard.
  2. In the left-hand menu, go to Settings > General.
  3. In the WordPress address (URL) and Site address (URL) fields, make sure there are no spaces after the URLs .
  4. Click Save Changes.

Fix URLs within phpMyAdmin

Option 1: Manually Edit Database

To manually edit the site and home URLs within your WordPress database:

  1. Log into cPanel.
  2. In the Databases section, click on the phpMyAdmin icon.
  3. From the left menu, select the database for your WordPress installation.
  4. From the left menu, select wp_options.
  5. Find and edit the records for siteurl and home, ensuring that there are no spaces after the domain name.

Option 2: Run an SQL Query

As an alternative to manually editing the database as described above, you can run an SQL query in phpMyAdmin to update both fields (site and home) at one time. To do this:

  1. Log into cPanel.
  2. In the Databases section, click on the phpMyAdmin icon.
  3. From the left menu, select the database for your WordPress installation.
  4. From the top menu, click on the SQL tab.
  5. In the text box, enter the following query, replacing www.domain.com with your domain:
    UPDATE `wp_options` SET option_value='http://www.domain.com' WHERE option_name='siteurl' OR option_name='home';
  6. Click Go.

Create Social Sharing Links in less than 5 minute

Create Facebook share links, Twitter “tweet this” links, Google Plus share links, LinkedIn share links, Pinterest “pin this” links and email “mailto” links that will work anywhere — even inside emails!

Facebook Share Link

URL Only

https://www.facebook.com/sharer/sharer.php?u=http://linkloops.in

HTML Link

<a href="https://www.facebook.com/sharer/sharer.php?u=http://linkloops.in">Share on Facebook</a>

Twitter Share Link

URL Only

https://twitter.com/home?status=http://linkloops.in

HTML Link

<a href="https://twitter.com/home?status=http://linkloops.in">Share on Twitter</a>

 

Google Plus Share Link

URL Only

https://plus.google.com/share?url=http://linkloops.in

HTML Link

<a href="https://plus.google.com/share?url=http://linkloops.in">Share on Google+</a>

 

LinkedIn Share Link

URL Only

https://www.linkedin.com/shareArticle?mini=true&url=http://linkloops.in&title=&summary=&source=

HTML Link

<a href="https://www.linkedin.com/shareArticle?mini=true&url=http://linkloops.in&title=&summary=&source=">Share on LinkedIn</a>

 

Pinterest Share Link

URL Only

https://pinterest.com/pin/create/button/?url=&media=http://linkloops.in&description=

 

HTML Link

<a href="https://pinterest.com/pin/create/button/?url=&media=http://linkloops.in&description=">Pin on Pinterest</a>

 

Email

URL Only

mailto:info@linkloops.in?&cc=sknirbhay10gmail.com&subject=Share ink&body=testing%20body%20

 

HTML Link

<a href="mailto:info@linkloops.in?&cc=sknirbhay10gmail.com&subject=Share ink&body=testing%20body%20">Send Email</a>

Creating Custom Front End Registration for wordpress

Front end registration form that allow your users to signup without ever leaving your main site, you provide a much more consistent and comfortable environment. Registration form has basic following fields.

  • Username
  • Email
  • First Name
  • Last Name
  • Password

Processing Our Registration Form Data

$fname=$_POST['first_name'];
	$lname=$_POST['last_name'];
	$user_name=$_POST['username'];
	$email=$_POST['email'];
	$pass=$_POST['password'];
	$userdata = array(
			'user_login' => $user_name,
			'user_email' => $email,
			'user_pass' =>$pass,
			'first_name' =>$fname,
			'last_name' =>$lname,
);
$user_id = wp_insert_user( $userdata ) ;
if($user_id) {
wp_new_user_notification($user_id);
wp_setcookie($user_name, $pass, true);
wp_set_current_user($user_id, $user_name);	
do_action('wp_login', $user_name);
$url=get_bloginfo('url')."/pagename";
wp_redirect($url);
	exit();
}

1. Make sure that a username has been entered and that the nonce verifies, to confirm the form has been submitted from the correct location.

2. Each of the posted variables (username, email, password, etc) will be assigned to a variable.

3. The core registration.php file will be loaded into our function. Without it, we cannot perform many of the validation checks needed.

4. The entered username will be compared against the database to make sure it has not already been registered by a different user.

5. The entered username will be checked to make sure it is valid, in terms of characters used, length, etc.

6. The entered username is checked to make sure it is not blank.

7. The entered email is checked to ensure it is a valid email.

8. The entered email is checked against the database to ensure it is not already registered.

9. The entered password is checked to ensure it is now blank.

10. The entered password is checked against the confirm password to ensure the user has entered their password correctly.