Showing posts with label wordpress. Show all posts
Showing posts with label wordpress. Show all posts

Saturday, 24 October 2015

How To Display Different Number of Search Results in WordPress

WordPress treats every page/post-listing just about the same. Whether it’s the homepage, a blog category, search results, or even your average page, the same basic logic is used to generate it. This also means that the same settings, including the number of posts displayed per page, are used across the board. However, this is not always desirable.

The Goal 

The basic goal of a site search is to find information quickly; however, it is becoming more and more commonplace to see increasingly stylized post listings. In my eyes, this runs the risk of becoming counter-intuitive to this goal. Because of this, it is my personal preference to simplify my search results and to show more results. Because searches rely on the same setting (found in Settings » Reading » Blog pages show at most) as any other WordPress page when determining the number of listings to show, we have to get a little creative in order to show a different am amount.

How Not to Do It

Most blog posts or WordPress.org forum posts will recommend using the query_posts()function in order to alter the number of search listings shown. They advise inserting something similar before the loop in your themes search.php.

However, this neglects one important fact. WordPress already runs the query once before it even gets to this query_posts() call. This means that you are essentially doubling the number of database calls WordPress needs to do in order to retrieve the correct number of posts. If an efficient, quickly-loading site is important to you (I know it is to me), this should be a concern. This is even more important with the recent news that Google is now incorporating page-load time into its pagerank algorithm.

The Solution

The obvious solution is to alter the original query before it is executed. This is made fairly simple with WordPress filters (noticing a common theme in our WordPress-related posts?). Using the request filter, we can change the query parameters before it is translated into an actual MySQL query. Simply insert the following code into the functions.php file of your theme. It’s so simple, I hope this technique will become more commonplace.

function change_wp_search_size($queryVars) {
if ( isset($_REQUEST['s']) ) // Make sure it is a search page
$queryVars['posts_per_page'] = 10; // Change 10 to the number of posts you would like to show
return $queryVars; // Return our modified query variables
}
add_filter('request', 'change_wp_search_size'); // Hook our custom function onto the request filter

Any function that is hooked into the request filter will automatically be passed an array containing any parameters that intends to use to generate the database query. All we have to do is change the posts_per_page parameter to the number of results we would like to show.

We must first determine if we are even on the search results page. Because, WordPress hasn’t run its initial query yet, it has no idea what page we are on. Therefore, we cannot use the is_search() function to make this determination. Therefore, we test for the s variable which will contain the query entered into a search box.

Then, it’s simply a matter of returning our modified query paramaters to WordPress and letting WordPress do it’s magic. Though this solution may contain a few more lines of code than a query_posts() solution, it is still superior for two reasons.

It is quicker by nearly halving the number of database calls
We separate logic and presentation as much as possible, which should be a ever-present goal in web programming and design

How To Filter WordPress Categories Using an Undocumented Hook

In this article, we will briefly cover WordPress hooks and use an undocumented one in order to manipulate category listings.

After some further digging, while it is not listed on the WordPress filter list, it appears that this “undocumented hook” is mentioned on the get_terms() function reference. So, we’ll call this a somewhat undocumented hook.

Anybody who knows me knows that I love WordPress, if perhaps not more than any man should love a collection of code. I believe there are few projects for which it should not at least be considered.

Recently, I have been adapting WordPress to a large project with multiple authors/contributors. Each user would have a set of capabilities and restrictions. The most important of these was limiting users to certain categories. If this were my only need, the very useful Role Scoper plug-in would have worked wonderfully. However, there were a number of other requirements that Role Scoper did not meet, and the use of multiple plug-ins would likely confuse my not quite tech savvy clients. Therefore, I was forced to create my own solution that included the required category restrictions.

WordPress generally makes it very easy to filter and adjust any data/output before it is sent to the end-user. This is done with Filters. Essentially, you are able to hook in to a number of pre-defined functions and pass the output to your own custom function. The code for achieving this is done so in the following format:

<?php add_filter( $tag, $function_to_add, $priority, $accepted_args ); ?>

Most important here are $tag, the function you want to hook into, and $function_to_add, your custom function that will filter the data provided. The other arguments are optional but more information can be found in the WordPress codex.

This code can be placed in the file for your custom plug-in or in the functions.php for your theme. For example, if you wanted the name of your blog to be red every time it appears in a post you could use the following code.

<?php
add_filter('the_content', 'styleBlogName');
function styleBlogName($content) {
$blogTitle = get_bloginfo('name');
$content = str_replace($blogTitle, '<span style="color: Red;">' . $blogTitle . '</span>', $content);
return $content;
}
?>

Here, we’ve added a filter to that will be called every time a theme calls the_content(), which outputs the content of a post. WordPress then passes the current content of the post to ourstyleBlogName() function. We use str_replace() to replace any instances of our blog title with a new version wrapped in a span we can style. Lastly, you have to remember to return the new value of $content, or WordPress will assume the post is blank. Pretty simple.

Every hook that we can attach to has different arguments. You can find a semi-complete list of these hooks in the codex.

WordPress is a huge project with an expansive code base. Unfortunately, there are a number of things that are not yet covered in the available documentation. And some of the things that are covered have been deprecated. During a sleepless night, while doing research on the project I described above, I was digging through the WordPress code and stumbled upon an undocumented filter hook, get_terms.

get_terms hooks into the function that retrieves all information about categories and is called in a large number of places throughout the WordPress code. For example, it is called whenever a theme calls the wp_list_categories() function, when listing the categories in the sidebar of the Edit Post screen in the admin panel, and many other places.

When hooking into this filter, WordPress will pass your callback function an array of objects, each object containing information about an individual category. To get a good idea of the data structure, insert the following code into the functions.php file of your current theme, visit a page of your blog that lists the categories, and view the source code.

add_filter('get_terms', 'restrict_categories');
function restrict_categories($categories) {
echo "<!-- \n";
print_r($categories);
echo "//-->\n";
return $categories;
}

Now that we understand the data structure, we can proceed to process it some way. There are limitless possibilities, so I’m going to keep my example simple and leave you to your own imagination. Imagine that you have a WordPress installation with one Admin and multiple Authors. You have a category called “Site News” that you only want the Admin to be able to post to. Therefore you don’t want the Authors to even be able to see it in the category checklist when composing a new post. Here is how you would achieve that by hooking intoget_terms.

<?php
// add_filter('get_terms', 'restrict_categories');
function restrict_categories($categories) {

// If we are in the new/edit post page and not an admin, then restrict the categories
$onPostPage = (strpos($_SERVER['PHP_SELF'], 'post.php') || strpos($_SERVER['PHP_SELF'], 'post-new.php'));
if (is_admin() && $onPostPage && !current_user_can('level_10')) {
$size = count($categories);
for ($i = 0; $i < $size; $i++) {
if ($categories[$i]->slug != 'site_news')
unset($categories[$i]);
}
}

return $categories;
}
?>

We begin by checking that we are in the admin panel (so the ‘Site News’ category shows up on the main site), on the Add Post or Edit Post page, and are not an admin. If all these conditions are met, we iterate through the array of objects and check each category slug. If the slug is equal to ‘site_news’, we simply remove the object from the array. Return our new$categories variable and we’re done. You’ve now done something that many WordPress theme and plug-in developers aren’t even aware of. Way to go you.

WordPress is ridiculously powerful and makes developing websites much simpler than was previously possible. While it has evolved into something far beyond your typical blog software, sometimes you have to get your hands dirty and dig through the code to truly unleash its power. While sites like Adam Brown’s hook reference have attempted to further document all the hooks available to theme/plug-in developers, there is still a lot to discover.

Good luck and happy hunting!

Monday, 19 October 2015

How To Add FTP Details automatically in Wordpress

On some web server, we need to put username, password and server address when we need to enable automatically update our WordPress, plugin or themes. This is really bad if we must input this field each time updated.


Now I will show you How To Automatically added FTP detail on WordPress.

All need to do is put all parameters in our wp-config.php and all the field will be automatically passed by Web Server. Follow this guide how to do it.

Open your wp-config.php via FTP Client or cPanel and use you favorite editor to edit it
Add this code

define('FTP_HOST', 'Your_FTP_Hosting');
define('FTP_USER', 'Your_FTP_Username');
define('FTP_PASS', 'Your_FTP_Password);
//If you use SSL connection, set this to true
define('FTP_SSL', false);

Done, now you are ready to auto update your plugins and themes

How To Add External RSS Feeds in WordPress 2015

Sometimes we have another useful resource about our blog and we need to put the content in the Sidebar. With a little bit of code and a slight tweak, we can do it on our WordPress.

How To Display External RSS Feeds in our WordPress is easy.

There are so many methods to display External Feeds, we can use the RSS Widget, or write our own code. In this tip, we use some WordPress functions.

The first thing is open sidebar.php (if you want to display external RSS content on your sidebar) and write this code below

<?php
require_once (ABSPATH . WPINC . '/rss-functions.php');
// here's where to insert the feed address
$rss = @fetch_rss('http://feeds2.feedburner.com/WPGPL');
if ( isset($rss->items) && 0 != count($rss->items) ) {
?>
<?php
// here's (5) where to set the number of headlines
$rss->items = array_slice($rss->items, 0, 30);
foreach ($rss->items as $item ) {
?>
          <li> <a href='<?php echo wp_filter_kses($item['link']); ?>'> <?php echowp_specialchars($item['title']); ?></a> <spanclass="sdate"><?php echowp_specialchars($item['description']); ?></span> </li>
          <?php } ?>
<?php } ?>

Please note, you need replace RSS feed source with your own resource and then check on your own blogs. In our example, you can check on our sidebar, don’t forget to subscribe to our posts.

If you have little bit of knowledge on CSS and XHTML you can make it a more fancy layout..

How To Easily Manage Wordpress Slidebar Using jQuery

I recently finished a project that pushed WordPress farther than I have ever before. Essentially, each of the 18 categories was a micro-site with its own styling and two widgetized areas.

That means 36 different widgetized sections!

When viewing the Widget page in the WordPress Dashboard, the list of widget areas extended quite a bit below the fold. This made adding and managing the widgets extremely cumbersome. The obvious solution was to display only one widget area at a time.

Before writing any code, I like to flesh out the basics to my solution on paper. Some simple brainstorming lead me to the following goals:

  1. Create an array of all the widget areas available
  2. Hide all the listed widget areas besides the first
  3. Insert into the Widget page a drop-down box containing a list of the widget areas in our array
  4. Whenever a user selects a widget area from the drop-down box, show that one and hide the rest.



We’ll begin by creating a file named widget-admin.js. Save this file somewhere in your theme directory. I prefer to keep all my JavaScript files in the js/ sub-directory. We only want this code to be loaded if we are on the Widgets page of the WordPress dashboard. To achieve this, add the following code to your functions.php file.

// Custom Admin Sidebar Switcher
function sidebar_switcher() {
global $pagenow;

if ($pagenow == 'widgets.php')
wp_enqueue_script('fca_admin', get_bloginfo('template_url').'/js/widget-admin.js');
}
add_action('admin_print_scripts', 'sidebar_switcher');

By latching onto WordPress’s admin_print_scripts hook, our sidebar_switcher() function will only be run when we are in the dashboard. The sidebar_switcher() function checks if we are on the Widgets page. If we are, it tells WordPress to queue up our widget-admin.js file.

The following code goes into the widget-admin.js that we created earlier. The comments should make it self-explanatory.

jQuery("document").ready(function(){
var sidebars = new Array(); // Create array to hold our list of widget areas
var selectorHTML, name; // Declaring variables isn't necessary in JavaScript, but it's good practice

jQuery('.widget-liquid-right .sidebar-name h3').each(function(index) {
name = jQuery(this).html(); // Get the name of each widget area
name = name.replace(/\s*<span>.*<\/span>/,''); // Remove extra <span> block from name
sidebars.push(name); // Add the name to our array
});

jQuery('.widget-liquid-right .widgets-holder-wrap').hide(); // Hide all the widget areas in list
jQuery('.widget-liquid-right .widgets-holder-wrap:first').show(); // Show the first

// Start <select> block. Position to the right of the "Widgets" heading.
selectorHTML = "<select id=\"sidebarSelector\" style=\"position: absolute; left: 400px; top: 68px;\">\n";

var count = 0;
for ( var i in sidebars ) // Add option for each widgetized area
selectorHTML = selectorHTML + "<option value=\"" + count++ + "\">" + sidebars[i] + "</option>\n"; // Store the index of the widget area in the 'value' attribute

selectorHTML = selectorHTML + "</select>"; // Close the <select> block

jQuery('div.wrap').append(selectorHTML); // Insert it into the DOM

jQuery('#sidebarSelector').change(function(){ // When the user selects something from the select box...
index = jQuery(this).val(); // Figure out which one they chose
jQuery('.widget-liquid-right .widgets-holder-wrap').hide(); // Hide all the widget areas
jQuery('.widget-liquid-right .widgets-holder-wrap:eq(' + index + ')').show(); // And show only the corresponding one
});
});

When pushing WordPress to it’s limit, it may occasionally be necessary to enhance its user interface. With the power of jQuery and WordPress’s action and filter hooks, the sky is the limit.

How to exclude Categories from Navigation in WordPress ?

Sometimes We want to exclude Specific Categories from navigation. Depending on the condition, some have too many categories to show in one navigation bar so they show the very important one in navigation rest in Sidebar widgets mostly. In other cases, some just don’t want to show the “Un-categorized” (default) category in their navigation bar.

This simple edit in the code will help you do so.

The Default Code:
<?php wp_list_categories(’title_li=&exclude=’ . $ex_aside) ?>


  • Now if you want to un-show some categories or want to show only those you want. Just do these simple steps.
  • Find the above code in Header.php of your theme file.

Replace it with this code:
<?php wp_list_categories(’title_li=&include=3,5,7,12?);?>


  • In the above code, 3, 5, 7 and 12 are the IDs of your categories. Only add IDs of those you want to show in navigation. Rest will be excluded.

Sunday, 20 September 2015

How to Installing a WordPress theme by using the built-in installer

Installing a WordPress theme can be easy or difficult, depending on the theme and it’s availability (or lack thereof) in the WordPress themes directory.

The automatic installation process comes very handy with published themes, but sometimes things fail or themes are not available, and one must resort to the old fashioned files upload, either via WordPress or via the old fashioned FTP.  This tutorial describes all three methods.

Automatic Installation

Installing a WordPress theme using the built-in installer is quite easy:
1. From your WordPress dashboard, navigate to the Appearance > Themes menu.

2. Click on the Install Themes button.

3. Type the name of your desired theme in the input field and click Search.

4. WordPress will display all found results. Click the Install Now link under the desired theme.

5. WordPress will display the status of the install and present you with some options. Click the Activate     link to set the newly installed theme as your site theme.





Friday, 18 September 2015

How to Migrate your Blog from Blogger to WordPress

Youur blog (abc.blogspot.com) is hosted on Blogger and you would now like to move the blog from Blogger to WordPress (self-hosted) with a personal domain name like abc.com. What is the easiest way to switch from Blogger to WordPress without losing Google search traffic, page rank and your existing feed subscribers?

WordPress provides an easy one-click option for importing blog posts and reader comments from Blogger into a new WordPress blog but there’s more to migration than just transferring content. For instance:

Some of your articles on the old blogspot blog could be ranking very high in search engines for certain keywords but once you move these articles to a new WordPress blog, you will lose the organic search traffic since the permalinks (or URLs) of your blog posts will change.
People come to your blog through search engines, browser bookmarks and referrals from other web sites that have linked to your blog pages. If you migrate to WordPress, Blogger will not automatically redirect these visitors to your new website.
When you switch from Blogger to WordPress, existing readers who are subscribed to your Blogger RSS Feed may be lost forever if they don’t manually subscribe to your new WordPress feed address (and most won’t).
The Importer tool available inside WordPress will only transfer content from Blogger to WordPress but if would also like to take care of the various issues listed above, follow this step-by-step tutorial. It takes less than 5 minutes to complete and you’ll also be able to transfer all the Google Juice from the old blogspot.com address to your new WordPress blog.



How to Move your Blog from Blogger to WordPress


Before you start the migration, it may be a good idea to backup your Blogger blog including the XML template, blog posts and comments just to be on the safe side.

If you need assistance with the Blogger to WordPress migration, please get in touch with me using the contact form at ctrlq.org. This is a paid option.

Register a new web domain, buy web hosting and install WordPress on your new domain.
Open your WordPress Admin Dashboard and under Tools -> Import, select the Blogger* option. Authorize WordPress to access your Blogger Account, select your blogspot.com blog and within minutes, all your Blogger blog posts and comments will be available on the new WordPress site.
Open the WordPress themes editor under Appearance -> Editor and open the functions.php file for editing. Most WordPress themes include a functions.php file or you can upload it manually into your WordPress themes folder through cPanel or FTP. Copy-paste the following snippet of code inside your functions.php file (at the beginning of the file) and click the “Update File” button to save your changes.

<?php

function labnol_blogger_query_vars_filter( $vars ) {
  $vars[] = "blogger";
  return $vars;
}

add_filter('query_vars', 'labnol_blogger_query_vars_filter');

function labnol_blogger_template_redirect() {
  global $wp_query;
  $blogger = $wp_query->query_vars['blogger'];
  if ( isset ( $blogger ) ) {
    wp_redirect( labnol_get_wordpress_url ( $blogger ) , 301 );
    exit;
  }
}

add_action( 'template_redirect', 'labnol_blogger_template_redirect' );

function labnol_get_wordpress_url($blogger) {
  if ( preg_match('@^(?:https?://)?([^/]+)(.*)@i', $blogger, $url_parts) ) {
    $query = new WP_Query ( 
      array ( "meta_key" => "blogger_permalink", "meta_value" => $url_parts[2] ) );
    if ($query->have_posts()) { 
      $query->the_post();
      $url = get_permalink(); 
    } 
    wp_reset_postdata(); 
  } 
  return $url ? $url : home_url();
}

?>

  1. Open your Blogger Dashboard and choose Templates. Scroll down the templates page and choose the “Revert to Classic Templates” option to switch from the XML-based Blogger templates to the classic Tag based templates.
  2. Copy-paste the following snippet into your Blogger template editor but before you do that, replace all occurrences of labnol.org with your new WordPress site URL. For instance, if your WordPress site is located at example.com, replace labnol.org with example.com and paste the modified snippet in the Blogger template editor. Save the changes.  

<html>
 <head>
  <title><$BlogPageTitle$></title>
  <script>
    <MainOrArchivePage>
      window.location.href="http://labnol.org/"
    </MainOrArchivePage>
    <Blogger><ItemPage>
      window.location.href="http://labnol.org/?blogger=<$BlogItemPermalinkURL$>"
    </ItemPage></Blogger>
  </script>
   <MainPage>
    <link rel="canonical" href="http://labnol.org/" />
   </MainPage>
   <Blogger>
    <ItemPage>
     <link rel="canonical" href="http://labnol.org/?blogger=<$BlogItemPermalinkURL$>" />
    </ItemPage>
   </Blogger>
 </head>
 <body>
  <MainOrArchivePage>
    <h1><a href="http://labnol.org/"><$BlogTitle$></a></h1>
  </MainOrArchivePage>
  <Blogger>
   <ItemPage>
    <h1><a href="http://labnol.org/?blogger=<$BlogItemPermalinkURL$>"><$BlogItemTitle$></a></h1>
    <$BlogItemBody$>
   </ItemPage>
  </Blogger>
 </body>
</html>

We are almost done. Open any page on your old Blogger blog and it should redirect you to the corresponding WordPress page. We are using a permanent 301 redirect on the WordPress side and therefore all the Google Juice and PageRank should pass to your new WordPress pages. (video)

The above method works for regular blogspot.com URLs and also country-specific Blogger domains like blogspot.co.uk, blogspot.com.au or blogspot.in.

The Blogger Import tool moves only posts and comments from Blogger to WordPress but not images. And that should be fine because the image URLs in your imported WordPress posts are still pointing to blogspot.com (where the images were originally hosted) and therefore nothing would break.

Also See:  Move Blogger on Custom Domain to WordPress

Switch RSS Feed from Blogger to WordPress


When you move from Blogger to WordPress, the URL of your RSS feed will change as well. Go to Blogger -> Settings -> Other and choose Post Feed Redirect URL under Site Feed. Here you can type the web address of your new WordPress RSS feed here and the existing RSS subscriber will automatically move to your new feed.

If you are using FeedBurner, just replace the source from Blogger RSS feed to your new WordPress feed.