Archive for the ‘Wordpress’ Category


Courtesy:-http://www.excellentwebworld.com/wordpress-interview-question-answer/

WordPress is web software you can use to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time.Now Most of users are started development on WordPress The main reason for its popularity is its admin very easy to use and manage.Its will work on apr. 60 million websites world wide.

So now all IT firm started hiring developer for WordPress but main thing what exact qualification we needed and exactly what knowledge we are looking for.So here is the some basic & Technical question answer that at-least developers knows.

In this blog find some technical Question & Answer of WordPress.

Que 1 How we will pass a variable by value in WordPress.
Ans. Its same like we will work in c,c++
$p = &$s

Que 2 Basic functions then we generally used in WordPress? Why?
Ans: If developer have good knowledge then he/she must know this function name at-least 3-5

1. is_page() :- Condition for check if page is displayed. Its return true or false.
2. wp_nav_menu() :- Enabling WordPress 3.0′s Navigation Menu Feature
3. wp_list_pages() :- Listing All Pages
4. get_excerpt() :- Displays the excerpt of the current post with read more link for display full post.
5. is_category() :- Condition for check if category is displayed. Its return true or false.
6. the_title():- Displays the title of the current post
7. the_content():- Displays the contents of the current post.
8. bloginfo(‘url’) :- Getting the Site’s URL
9. bloginfo(‘template_url’) :- Getting the URL to the Current Theme
10.the_time():- Display the time the post was published (uses PHP date formatting as a parameter):

Que 3 How many tables a default WordPress will have?
Ans If developer work with database then he/she must know how many table install with default wordpress.
A default wordpress will have 11 tables. They are-
1. wp_commentmeta
2. wp_comments
3. wp_links
4. wp_options
5. wp_postmeta
6. wp_posts
7. wp_terms
8. wp_term_relationships
9. wp_term_taxonomy
10.wp_usermeta
11.wp_users

Que 4 Is WordPress good for Google ranking and SEO?
Ans Yes, That is one of the major selling points of using WordPress is that it includes excellent built in search engine optimization (SEO).In Other CMS you have to install SEO extention they either free or Commercial.In WordPress you can also extend SEO feature by using some Nice FREE SEO plugins likes All in one SEO,Yoast These are popular plugins that are known to help your rank on search engines such as Google and Bing.

Que 5 How to hide the top admin bar at the frontend in WordPress.
Ans. Most of developer have no idea about this.
Add the below mentioned code in the theme(active) function.php

(or)
Add the below code in the active theme style.css stylesheet
#wpadminbar {
display: none; visibility: hidden;
}

Que 6 How to hide Directory Browsing in WordPress from server using .htaccess file?

By default when your web server does not find an index file (i.e. a file like index.php or index.html), it automatically displays an index page showing the contents of the directory.SO now if you want to hide this add below code in .htaccess file.

Que 7 What are the custom fields in wordpress? How to display it?
Ans We will add extra information to our post by using custom fields.Custom Fields are a form of meta-data that allows us to store arbitrary information with each WordPress post.
To display the Custom Fields for each post, use the the_meta() template tag.
To fetch meta values use the get_post_meta() function.
For example we use custom fields:-

Que 8 What is the use of loop in Worpdress Where we used it?
Ans. The Loop are php code used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page.check below sample code.

Que 9 How to run database Query in WordPress?
Ans. The $wpdb->query function allows you to execute any SQL query on the WordPress database. It is best to use a more specific function. Check sample code below for SELECT query.

Que 10 How to Change Your Default WordPress Post Category & Post Type?
Ans. Most common issue and most of developer not know this and find hacking(custom coding solution).But it more easy then that.simply navigate to Settings > Writing > and then look for the pull down menu beside “Default Post Categoy.” for change default category selection.

Writing Setting
Below that you can find Default post format for changes post type from standard to image post type or a video post type,chat gallery,link and many more.

Que 11 How to Change the Length of the Default WordPress Excerpt.
Ans The default WordPress excerpt is 55 words long. By modified bit to your functions.php file you can change the length to as you required.Below is the code if we need 60 length.

Que 12 How to add option for open menu item in new tab?
Ans. This is very basic feature but sometime developer never use this so they have no idea and goto code and add manually that links.For add option in menu item for open link in new tab just navigate to “Screen Option” at top right corner in menu select check “link target”. See below screenshot.

Menus

Que 13 What is hooks and types of hooks in wordpress?Where it used?
Ans. Hooks are provided by WordPress to allow your plugin to ‘hook into’ WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two types of hooks used in WordPress are Actions and Filters.

1)Actions Run During a Typical Request.for example A developer may want to add code to the footer of a Theme. This could be accomplished by writing new function, then Hooking it to the wp_footer Action.
has_action()
add_action()
do_action()
do_action_ref_array()
did_action()
remove_action()
remove_all_actions()
2)Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen.
has_filter()
add_filter()
apply_filters()
apply_filters_ref_array()
current_filter()
remove_filter()
remove_all_filters()
Que 14 What is child theme? Why we used it?
Ans A WordPress child theme is a WordPress theme that inherits its functionality from its parent WordPress theme.Child themes are often used when you want to customize or tweak an existing WordPress theme without losing the ability to upgrade that theme.
Advantage is child theme is Safe Updates,Easy to Extend,Fallback Safe

Que 15 What is the Basic Difference Between Posts vs. Pages.
Ans. Posts are timely vs. Pages are timeless.
Posts are social vs. Pages are NOT.
Posts can be categorized vs. Pages are hierarchical.
Posts are included in RSS feed vs. Pages are not.
Pages have custom template feature vs. Posts do not.


1. what is WordPress.
Wordpress is a CMS (Content Management System) based on php and mysql. Its free and open source blogging tool. Its now most popular blogging tool on internet network.

The main reason for its popularity is the administrator panel is very user friendly, easy to use and manageable for the layman user.

2. What is current version of wordpress.
The wordpress 3.8 version released in 12 December 2013.

3. What are the features of wordpress.

  1. Simplicity, make wordpress very easy to use for everyone.
  2. Free open source.
  3. Easy to install.
  4. There are lots of free as well as paid theme to use.
  5. Extends with plugins, we can extends the functionality of wordpress using thousands of free plugins or will create any plugin according to your requirements.
  6. Multilingual, wordpress is available on more than 70 languages.
  7. Multisite, create a child website along with the parent site with the same URL and admin panel.
  8. Flexibility, with wordpress you will create any type of blog or website.
  9. Comment, the built in comment system also make wordpress popular as you can comment your views on website.
  10. Full standards compliance, XML-RPC interface, easy importing, cross-blog communication tools.

4. What is the default prefix of wordpress tables.

By default prefix of wordpress is wp_ . But for security reasons it is highly recommend to use different prefix.

5. How can you backup or import your WordPress content from admin panel.

For import content from wordpress admin panel goes to:-

WordPress admin -> Tools -> Import

This will create a xml file for your posts, comments, category etc.

6. Tell some commonly used functions in wordpress.
Wordpress have lot of inbuilt functions. some of commonly used function in wordpress are:-

  1. wp_nav_menu()  :- Displays a navigation menu.
  2. is_page() :- Condition for check if page is displayed. Its return true or false only.
  3. get_the_excerpt() :- Copy the excerpt of the post into a specified variable.
  4. in_category() :- Tests if the specified post is assigned to any of the specified categories or not.
  5. the_title():- Displays the title of the post.
  6. the_content():-  Displays the contents of the post.

for more functions, click here

7. What are hooks in wordpress.
Wordpress hooks allows user to create or modify wordpress theme / plugin with shortcode without changing the original files. There are two types of hooks:

  1. Action Hooks
  2. Filter Hooks

Action Hooks :-  Action hooks are points in wordpress core where its possible for outside resources to insert additional code.

For example- wp_head() , the_post(), get_sidebar() is an action hook which is used by most of themes. To hook an action, create an hook in your function file and hook it using add_action() function.

<?php

add_action( 'wp_head', 'head_func' );

function head_func () {

echo "<div>This is test</div>";

}

?>

Filter Hooks :- Filter hooks are used to handle output like using it you will add an text or content at end of content of your post. You will add an filter using add_filter() function. There are various filter used in wordpress as the_title(), wp_title(), get_the_excerpt(), get_to_ping(), attachment_icon().

For example:- Using these filter we will add content add end of posts.

<?php add_filter( 'the_content', 'webs_expert' );

function head_func( $content ) {

if ( is_single() ) {

$content .= '<div>This is test</div>' . " ";

}

return $content;

}

?>

8. What is file structure in wordpress.
The main files used in wordpress are:-

  1. index.php :- for index page.
  2. single.php :- for single post page.
  3. page.php :- display the static pages.
  4. category.php :-  Display the category page.
  5. archive.php :- For archive page display.
  6. tag.php :- For display the tags page.
  7. author.php :- For display author page.
  8. search.php :- For display the search result page.
  9. 404.php :- For display 404 error page.
  10. taxonomy.php :- For display the taxonomy archive.
  11. attachment.php :- For managing the single attachments page.
  12. header.php :- For managing top part of page.
  13. footer.php :- For manage bottom part of pages.

9. What are the template tags in wordpress.
A template tag is code that instructs WordPress to “do” or “get” something. Like in header.php  we will use the tag bloginfo(‘name’) to get information from user profile.

The the_title() template tag is used to display the post title.

wp_list_cats() are  for display categories.

get_header() for getting header.

get_sidebar() for display the sidebar on page.

get_footer() for get the footer content on page.

10. What are the custom fields in wordpress.
We will add extra information to your post by using custom fields. Custom Fields are a form of meta-data that allows you to store arbitrary information with each WordPress post.

Meta-data is handled with key/value pairs. The key is the name of the meta-data element. The value is the information that will appear in the meta-data list on each individual post that the information is associated with.

To display the Custom Fields for each post, use the the_meta() template tag.

To fetch meta values use the get_post_meta() function.

For example we use custom fields:-

<?php echo get_post_meta($post->ID, ‘key’, true); ?>

11. What are meta tags.
Meta tags keywords and description are used to display information about website or page.The commonly used meta tags are:-

<meta name="resource-type" content="document" />
<meta http-equiv="content-type" content="text/html; charset=US-ASCII" />
<meta http-equiv="content-language" content="en-us" />
<meta name="author" content="siddharth" />
<meta name="contact" content="" />
<meta name="copyright" content="" />
<meta name="description" content="" />
<meta name="keywords" content="" />

Coutesy:-http://blogbysid.wordpress.com/2013/05/31/wordpress-interview-questions-and-answers/

12. Can WordPress use cookies.
Yes, wordpress use cookies. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users.

Custom Controls in WP Admin

Posted: March 30, 2013 in Php, Wordpress

Introduction

WordPress 3.4 has a fucking cool new feature on the themes page. Next to each theme theres a preview or a customize link that pops up a new overlay that lets the user live edit their themes. Adding extra theme options has been constant a pain the arse since I started developing themes all those few years ago. To make things easier for myself I even created a theme admin plugin. I was never that happy with the plugin however and always too busy to make it work so the new theme customizer seems like a good timesaver for me and I decided to take a look at how to implement it.

The first thing I found was that as with all new WP features no-one has written any documentation for customising (Hey WP core developers, customise is spelled with a damn s!) it yet. All I could find was this description of the beta version. Also there doesn’t seem to be an API yet, it must be coming in a future release. However, there is an object called $wp_customize that you can add your custom theme settings to.

Getting Started

On loading up my starter theme in the preview I was suprised in seeing a half built menu already there. This is because WordPress is pulling the options for custom headers, backgrounds that you’ve added using the add_theme_support() function. It also pulls some core options like site title and displays them there.

Custom Options

Time for custom options. Going through the blog post I found I saw that the first thing you need to do is hook a function to the customize_register action like this:

1
2
3
4
function themename_customize_register($wp_customize){
    //STUFF IN HERE
}
add_action('customize_register', 'themename_customize_register');

All your custom options go into there.

Adding a Section

This is simple enough as far as I can tell. You add one using the following:

1
2
3
4
$wp_customize->add_section('themename_color_scheme', array(
    'title' => __('Color Scheme', 'themename'),
    'priority' => 120,
));

So you pass through a unique slug and an array of arguments to the add_section method. I’m not 100% sure of all the arguments to pass through in the array, all I passed was the title and the priority. The priority is where you want the section to appear in the menu order. 1 is on the top and 120 seems to be the bottom.

Adding options

There are two methods you need to call to add an option. One to tell WordPress that an option exists and one to display whatever input box it needs. This is similar how the add_option()/update_option()/get_option() API works and it should be because it uses those functions to save the settings as far as I can tell/be bothered to check.

The first option type I’m going to show you is a standard text input box then I’ll breeze through the other types. You need to first call the add_setting() method to tell WP that you wish to save some new data. You do that like this:

1
2
3
4
5
$wp_customize->add_setting('themename_theme_options[text_test]', array(
    'default'        => 'Arse!',
    'capability'     => 'edit_theme_options',
    'type'           => 'option',
));

Similar to the add_section() method you pass through a slug and an array of args. You need to pass through a unique slug to this as the first parameter and it also allows you to pass the slug as an array index. The advantages of this is all your options are then available in the template in the one array keeping things nice and neat. The args I’ve found are:

  • Default: The default value for the input.
  • Capability: This is the user role that is capable of editing these settings, I assume you would always set it to ‘edit_theme_options’.
  • Type: The way you want to store the data in WordPress, you can set it to ‘option’ or ‘theme_mod’. I’ve always used option for saving theme preferences but if you prefer using theme mod then you can set it to save those here.

Next you want to display your option in your custom section:

1
2
3
4
5
$wp_customize->add_control('themename_text_test', array(
    'label'      => __('Text Test', 'themename'),
    'section'    => 'themename_color_scheme',
    'settings'   => 'themename_theme_options[text_test]',
));

Again this works similarly to add_setting() and add_section() you pass a unique slug (Don’t really know why here as it’s only used as the list item css id) and an array of args. Some of the args are used for every input and some differ depending on the input element you want to display. The universal ones are:

  • label: The form items label.
  • section: The section in which you want the form item to appear.
  • type: The type of form item you want. These are text, radio, checkbox and select. And are standard form elements. Textareas and HTML5 input types aren’t supported.
  • settings: This is the setting you want to use to save the values from the file input. You put in the unique slug of of the setting you want to use.
  • choices: These are only needed for radio buttons and dropdowns and contain the different options you want to display.

You can also add options to the sections created by the WordPress core by passing their slug in the section arg. The ones I found are:

  • Colors: colors
  • Header Image: header_image
  • Background Image: background_image
  • Static Front Page: static_front_page
  • Site Title & Tagline: title_tagline
  • Navigation: nav

Standard Input Types

These are just standard form items.

Radio

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
$wp_customize->add_setting('themename_theme_options[color_scheme]', array(
    'default'        => 'value2',
    'capability'     => 'edit_theme_options',
    'type'           => 'option',
));
$wp_customize->add_control('themename_color_scheme', array(
    'label'      => __('Color Scheme', 'themename'),
    'section'    => 'themename_color_scheme',
    'settings'   => 'themename_theme_options[color_scheme]',
    'type'       => 'radio',
    'choices'    => array(
        'value1' => 'Choice 1',
        'value2' => 'Choice 2',
        'value3' => 'Choice 3',
    ),
));

Checkbox

To be honest, I think I’m missing something here. It’s acting a bit wonkey. Maybe it’s broken?

01
02
03
04
05
06
07
08
09
10
11
$wp_customize->add_setting('themename_theme_options[checkbox_test]', array(
    'capability' => 'edit_theme_options',
    'type'       => 'option',
));
$wp_customize->add_control('display_header_text', array(
    'settings' => 'themename_theme_options[checkbox_test]',
    'label'    => __('Display Header Text'),
    'section'  => 'themename_color_scheme',
    'type'     => 'checkbox',
));

Select Box

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
$wp_customize->add_setting('themename_theme_options[header_select]', array(
    'default'        => 'value2',
    'capability'     => 'edit_theme_options',
    'type'           => 'option',
));
$wp_customize->add_control( 'example_select_box', array(
    'settings' => 'themename_theme_options[header_select]',
    'label'   => 'Select Something:',
    'section' => 'themename_color_scheme',
    'type'    => 'select',
    'choices'    => array(
        'value1' => 'Choice 1',
        'value2' => 'Choice 2',
        'value3' => 'Choice 3',
    ),
));

Page Dropdown

This displays a list of your pages. I guess you could allow the user to set pages for something custom. It’s weird that this is in there but not a category dropdown option.

01
02
03
04
05
06
07
08
09
10
11
12
$wp_customize->add_setting('themename_theme_options[page_test]', array(
    'capability'     => 'edit_theme_options',
    'type'           => 'option',
));
$wp_customize->add_control('themename_page_test', array(
    'label'      => __('Page Test', 'themename'),
    'section'    => 'themename_color_scheme',
    'type'    => 'dropdown-pages',
    'settings'   => 'themename_theme_options[page_test]',
));

You can hack in a category dropdown like this however:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$categories = get_categories();
$cats = array();
$i = 0;
foreach($categories as $category){
    if($i==0){
        $default = $category->slug;
        $i++;
    }
    $cats[$category->slug] = $category->name;
}
$wp_customize->add_setting('themename_theme_options[header_select]', array(
    'default'        => $default,
    'capability'     => 'edit_theme_options',
    'type'           => 'option',
));
$wp_customize->add_control( 'example_select_box', array(
    'settings' => 'themename_theme_options[header_select]',
    'label'   => 'Select Something:',
    'section' => 'themename_site_options',
    'type'    => 'select',
    'choices' => $cats,
));

Fancy Input Types

These are custom input types and use javascript to work. They also all vary slightly from the others in that a new object needs to be created for each control.

Image Upload

Image upload is a file input type and allows users to upload an image. Handy for letting them set their logo.

01
02
03
04
05
06
07
08
09
10
11
$wp_customize->add_setting('themename_theme_options[image_upload_test]', array(
    'default'           => 'image.jpg',
    'capability'        => 'edit_theme_options',
    'type'           => 'option',
));
$wp_customize->add_control( new WP_Customize_Image_Control($wp_customize, 'image_upload_test', array(
    'label'    => __('Image Upload Test', 'themename'),
    'section'  => 'themename_color_scheme',
    'settings' => 'themename_theme_options[image_upload_test]',
)));

File Upload

Adds a custom file input. Good for allowing the end user to upload files I guess. Maybe a custom favicon would use this?

01
02
03
04
05
06
07
08
09
10
11
12
$wp_customize->add_setting('themename_theme_options[upload_test]', array(
    'default'           => 'arse',
    'capability'        => 'edit_theme_options',
    'type'           => 'option',
));
$wp_customize->add_control( new WP_Customize_Upload_Control($wp_customize, 'upload_test', array(
    'label'    => __('Upload Test', 'themename'),
    'section'  => 'themename_color_scheme',
    'settings' => 'themename_theme_options[upload_test]',
)));

Color Picker

Displays a colour picker. Gives the user the option to destroy your theme with their bad taste. This input seems to have a hex colour callback for sanitizing the value.

01
02
03
04
05
06
07
08
09
10
11
12
13
$wp_customize->add_setting('themename_theme_options[link_color]', array(
    'default'           => '000',
    'sanitize_callback' => 'sanitize_hex_color',
    'capability'        => 'edit_theme_options',
    'type'           => 'option',
));
$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'link_color', array(
    'label'    => __('Link Color', 'themename'),
    'section'  => 'themename_color_scheme',
    'settings' => 'themename_theme_options[link_color]',
)));

Displaying these options in your theme.

Displaying this stuff is easy. Depending on if you set your setting_type() to option or theme_mod you can display it in the two following ways:

Option:

1
<?php $options = get_option('themename_theme_options'); echo $options['input_name']; ?>

Theme Mod:

1
<?php $options =  get_theme_mod('themename_theme_options'); echo $options['input_name']; ?>

In Closing

Thats as far as I got in a couple of hours research (fucking about), you can download a working gist of the examples that you can copy straight into your themes functions.php file below and have a fiddle with it yourself. Please feel free to correct whatever I have wrong up there as I made quite a few assumtions and have probably made a mistake or two.

Download the code

Courtesy:-abandon.ie/exploring-wordpress-theme-customizer/


Let’s create a logo uploader using the new Theme Customizer, which was released with WordPress 3.4. This will allow users to place an image in our theme’s header; if no logo has been uploaded, we’ll fall back to displaying the site title and description instead.

For a more in-depth description of the Theme Customizer, including practical examples, code and more, see Otto’s excellent tutorials. If you are completely new to the Theme Customizer, I highly recommend at least scanning through them, to better understand the methods we’ll be calling in our code.

When working with the Theme Customizer, we should be creating sections, settings and controls within a function being fired on the customize_register hook. Create this function in your theme’s functions.php. The next three code blocks will go within this function.

1
2
3
4
function themeslug_theme_customizer( $wp_customize ) {
    // Fun code will go here
}
add_action('customize_register', 'themeslug_theme_customizer');

First, we’ll create a new section for our logo upload. Note that the description will not be displayed when using the Theme Customizer; it is simply used for the section heading’s title attribute.

1
2
3
4
5
$wp_customize->add_section( 'themeslug_logo_section' , array(
    'title'       => __( 'Logo', 'themeslug' ),
    'priority'    => 30,
    'description' => 'Upload a logo to replace the default site name and description in the header',
) );

Next, we register our new setting. It doesn’t get any easier than this:

1
$wp_customize->add_setting( 'themeslug_logo' );

Lastly, we tell the Theme Customizer to let us use an image uploader for setting our logo:

1
2
3
4
5
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'themeslug_logo', array(
    'label'    => __( 'Logo', 'themeslug' ),
    'section'  => 'themeslug_logo_section',
    'settings' => 'themeslug_logo',
) ) );

That wraps up our work in functions.php.

To output our new logo to the screen, we’ll need to call our setting with get_theme_mod somewhere in our theme’s header (I’ll be working in my theme’s header.php template file). However, if the user hasn’t set a logo, we’ll want to output the site title and description instead.

1
2
3
4
5
6
7
8
9
10
<?php if ( get_theme_mod( 'themeslug_logo' ) ) : ?>
    <div class="site-logo">
        <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><img src="<?php echo get_theme_mod( 'themeslug_logo' ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>"></a>
    </div>
<?php else : ?>
    <hgroup>
        <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
        <h2 class="site-description"><?php bloginfo( 'description' ); ?></h2>
    </hgroup>
<?php endif; ?>

Style your logo container as desired, and you’re done! For an example of the above code in action, check out my Debut starter theme on GitHub.

Courtesy /Source:- http://kwight.ca/blog/adding-a-logo-uploader-to-your-wordpress-site-with-the-theme-customizer/


If you are looking for php code or a plugin for your WordPress that takes a post ID and returns the database record for that post then read on. This is very helpful when you want to show a specific post on your homepage or other pages to get more attention. It allows you to design your homepage or a page with the post(s) that you want to be shown on the page rather than the 10 recent posts that the WordPress automatically chooses for you.

PHP Code Example to Query a WordPress Post

Example 1

The following code will Query the post with post id 26 and Show the title and the content.

<?php
$post_id = 26;
$queried_post = get_post($post_id);
$title = $queried_post->post_title;
echo $title;
echo $queried_post->post_content;
?>

Example 2

The following style could be more useful as it lets the user customise the font easily.

<?php
$post_id = 26;
$queried_post = get_post($post_id);
?>
<h2><?php echo $queried_post->post_title; ?></h2>
<?php echo $queried_post->post_content; ?>

Example 3

Using an Array… The following code will query every post number in ‘thePostIdArray’ and show the title of those posts.

<?php $thePostIdArray = array("28","74", "82", "92"); ?>
<?php $limit = 4 ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); $counter++; ?>
<?php if ( $counter < $limit + 1 ): ?>
<div id="post-<?php the_ID(); ?>">
<?php $post_id = $thePostIdArray[$counter-1]; ?>
<?php $queried_post = get_post($post_id); ?>
<h2><?php echo $queried_post->post_title; ?></h2>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>

How to Display the Post Content Like WordPress

When you retrieve the post content from the database you get the unfiltered content. If you want to achieve the same output like WordPress does in its’ posts or pages then you need to apply filter to the content. You can use the following code:

<?php
$post_id = 26;
$queried_post = get_post($post_id);
$content = $queried_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
echo $content;
?>

For a range of all the returned fields that you can use, check the WordPress site here.

Query X Number of Recent Posts

You can use the “wp_get_recent_posts” function to retrieve X number of recent posts and then display them however you want to. Here is an example:

<?php
//Query 5 recent published post in descending order
$args = array( 'numberposts' => '5', 'order' => 'DESC','post_status' => 'publish' );
$recent_posts = wp_get_recent_posts( $args );
//Now lets do something with these posts
foreach( $recent_posts as $recent )
{
    echo 'Post ID: '.$recent["ID"];
    echo 'Post URL: '.get_permalink($recent["ID"]);
    echo 'Post Title: '.$recent["post_title"];
    //Do whatever else you please with this WordPress post
}
?>

Using a Plugin to List all Posts Alphabetically

You can also use the WP Alphabetic Listing WordPress plugin to list all your posts.
Courtesy:-http://www.tipsandtricks-hq.com/query-or-show-a-specific-post-in-wordpress-php-code-example-44

10 Useful wordpress security tweaks

Posted: February 4, 2013 in Wordpress

Security has always been a hot topic. Offline, people buy wired homes, car alarms and gadgets to bring their security to the max. Online, security is important, too, especially for people who make a living from websites and blogs. In this article, we’ll show you some useful tweaks to protect your WordPress-powered blog.

1. Prevent Unnecessary Info From Being Displayed

The problem
When you fail to log into a WordPress blog, the CMS displays some info telling you what went wrong. This is good if you’ve forgotten your password, but it might also be good for people who want to hack your blog. So, why not prevent WordPress from displaying error messages on failed log-ins?

The solution
To remove log-in error messages, simply open your theme’s functions.php file, and paste the following code:

1 add_filter('login_errors',create_function('$a', "return null;"));

Save the file, and see for yourself: no more messages are displayed if you fail to log in.

Please note that there are several functions.php files. Be sure to change the one in your wp-content directory.

Code explanation
With this code, we’ve added a simple hook to overwrite the login_errors() function. Because the custom function that we created returns only null, the message displayed will be a blank string.

Source

2. Force SSL Usage

The problem
If you worry about your data being intercepted, then you could definitely use SSL. In case you don’t know what it is, SSL is a cryptographic protocol that secures communications over networks such as the Internet.

Did you know that forcing WordPress to use SSL is possible? Not all hosting services allow you to use SSL, but if you’re hosted on Wp WebHost or HostGator, then SSL is enabled.

The solution
Once you’ve checked that your Web server can handle SSL, simply open your wp-config.php file (located at the root of your WordPress installation), and paste the following:

1 define('FORCE_SSL_ADMIN', true);

Save the file, and you’re done!

Code explanation
Nothing hard here. WordPress uses a lot of constants to configure the software. In this case, we have simply defined the FORCE_SSL_ADMIN constant and set its value to true. This results in WordPress using SSL.

Source

3. Use .htaccess To Protect The wp-config File

The problem
As a WordPress user, you probably know how important the wp-config.php file is. This file contains all of the information required to access your precious database: username, password, server name and so on. Protecting the wp-config.php file is critical, so how about exploiting the power of Apache to this end?

The solution
The .htaccess file is located at the root your WordPress installation. After creating a back-up of it (it’s such a critical file that we should always have a safe copy), open it up, and paste the following code:

1 <files wp-config.php>
2 order allow,deny
3 deny from all
4 </files>

Code explanation
.htaccess files are powerful and one of the best tools to prevent unwanted access to your files. In this code, we have simply created a rule that prevents any access to the wp-admin.php file, thus ensuring that no evil bots can access it.

Source

4. Blacklist Undesired Users And Bots

Screenshot

The problem
This is as true online as it is in real life: someone who pesters you today will probably pester you again tomorrow. Have you noticed how many spam bots return to your blog 10 times a day to post their annoying comments? The solution to this problem is quite simple: forbid them access to your blog.

The solution
Paste the following code in your .htaccess file, located at the root of your WordPress installation. As I said, always back up the .htaccess file before editing it. Also, don’t forget to change 123.456.789 to the IP address you want to ban.

1 <Limit GET POST PUT>
2 order allow,deny
3 allow from all
4 deny from 123.456.789
5 </LIMIT>

Code explanation
Apache is powerful and can easily be used to ban undesirable people and bots from your website. With this code, we’re telling Apache that everyone is allowed to visit our blog except the person with the IP address 123.456.789.

To ban more people, simply repeat line 4 of this code on a new line, using another IP address, as shown below:

1 <Limit GET POST PUT>
2 order allow,deny
3 allow from all
4 deny from 123.456.789
5 deny from 93.121.788
6 deny from 223.956.789
7 deny from 128.456.780
8 </LIMIT>

Source

5. Protect Your WordPress Blog From Script Injections

The problem
Protecting dynamic websites is especially important. Most developers always protect their GET and POST requests, but sometimes this is not enough. We should also protect our blog against script injections and any attempt to modify the PHP GLOBALS and _REQUEST variables.

The solution
The following code blocks script injections and any attempts to modify the PHP GLOBALS and _REQUEST variables. Paste it in your .htaccess file (located in the root of your WordPress installation). Make sure to always back up the .htaccess file before modifying it.

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

Code explanation
Using the power of the .htaccess file, we can check requests. What we’ve done here is check whether the request contains a <script> and whether it has tried to modify the value of the PHP GLOBALS or _REQUEST variables. If any of these conditions are met, the request is blocked and a 403 error is returned to the client’s browser.

Sources

6. Fight Back Against Content Scrapers

The problem
If your blog is the least bit known, people will no doubt try to use your content on their own websites without your consent. One of the biggest problems is hot-linking to your images, which saps your server’s bandwidth.

The solution
To protect your website against hot-linking and content scrapers, simply paste the following code in your .htaccess file. As always, don’t forget to back up when modifying the .htaccess file.

1 RewriteEngine On
2 #Replace ?mysite\.com/ with your blog url
3 RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
4 RewriteCond %{HTTP_REFERER} !^$
5 #Replace /images/nohotlink.jpg with your "don't hotlink" image url
6 RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

Once you’ve saved the file, only your website will be able to link to your images, or, to be more correct, no one would link to your images, because it would be way too complicated and time-consuming. Other websites will automatically display the nohotlink.jpg image. Note that you can also specify a non-existent image, so websites that try to hot-link to you would display a blank space.

Code explanation
With this code, the first thing we’ve done is check the referrer to see that it matches our blog’s URL and it is not empty. If it doesn’t, and the file has a JPG, GIF, BMP or PNG extension, then the nohotlink image is displayed instead.

Source

7. Create A Plug-In To Protect Your Blog From Malicious URL Requests

Screenshot

The problem
Hackers and evil-doers often use malicious queries to find and attack a blog’s weak spots. WordPress has good default protection, but enhancing it is possible.

The solution
Paste the following code in a text file, and save it as blockbadqueries.php. Once you’ve done that, upload it to your wp-content/plugins directory and activate it as you would any other plug-in. Now your blog is protected against malicious queries.

01 <?php
02 /*
03 Plugin Name: Block Bad Queries
05 Description: Protect WordPress Against Malicious URL Requests
07 Author: Perishable Press
08 Version: 1.0
09 */
10
11 global $user_ID;
12
13 if($user_ID) {
14   if(!current_user_can('level_10')) {
15     if (strlen($_SERVER['REQUEST_URI']) > 255 ||
16       strpos($_SERVER['REQUEST_URI'], "eval(") ||
17       strpos($_SERVER['REQUEST_URI'], "CONCAT") ||
18       strpos($_SERVER['REQUEST_URI'], "UNION+SELECT") ||
19       strpos($_SERVER['REQUEST_URI'], "base64")) {
20         @header("HTTP/1.1 414 Request-URI Too Long");
21     @header("Status: 414 Request-URI Too Long");
22     @header("Connection: Close");
23     @exit;
24     }
25   }
26 }
27 ?>

Code explanation
What this code does is pretty simple. It checks for excessively long request strings (more than 255 characters) and for the presence of either the eval or base64 PHP functions in the URI. If one of these conditions is met, then the plug-in sends a 414 error to the client’s browser.

Source

8. Remove Your WordPress Version Number… Seriously!

The problem
As you may know, WordPress automatically displays the version you are using in the head of your blog files. This is pretty harmless if your blog is always up to date with the latest version (which is certainly what you should be doing anyway). But if for some reason your blog isn’t up to date, WordPress still displays it, and hackers will learn this vital piece of information.

The solution
Paste the following line of code in the functions.php file of your theme. Save it, refresh your blog, and voila: no more WordPress version number in the header.

1 remove_action('wp_head', 'wp_generator');

Code explanation
To execute certain actions, WordPress uses a mechanism called “hooks,” which allow you to hook one function to another. The wp_generator function, which displays the WordPress version, is hooked. We can remove this hook and prevent it from executing by using the remove_action() function.

Source

9. Change The Default “Admin” Username

Screenshot

The problem
Brute force is one of the easiest ways to break a password. The method is simple: try as many different passwords as possible until the right one is found. Users of the brute force method use dictionaries, which give them a lot of password combinations.

But knowing your username certainly makes it easier for them to guess the right combination. This is why you should always change the default “admin” username to something harder to guess.

Note that WordPress 3.0 let you choose your desired username by default. Therefore, this tip is still usefull if you still use the old “admin” account from older WordPress versions.

The solution
If you haven’t changed the “admin” username yet, simply run the following SQL query to your database to change it for good. Don’t forget to specify your desired username.

1 UPDATE wp_users SET user_login = 'Your New Username' WHERE user_login = 'Admin';

Code explanation
Usernames are stored in the database. To change one, a simple UPDATE query is enough. Note that this query will not transfer posts written by “admin” to your new username; the source post below shows you how to easily do that.

Source

10. Prevent Directory Browsing

The problem
By default, most hosts allow directory listing. So, if you type http://www.yourblog.com/wp-includes in the browser’s address bar, you’ll see all of the files in that directory. This is definitely a security risk, because a hacker could see the last time that files were modified and access them.

The solution (Updated)
Just add the following to the Apache configuration or your .htaccess file:

1 Options -Indexes

Code explanation
Please note that it’s not enough to update the blog’s robots.txt file with Disallow: /wp*. This would prevent the wp-directory from being indexed, but will not prevent users from seeing it.

Source

18 WordPress Security Plug-ins and Tips to Secure Your Blog

Courtesy: http://wp.smashingmagazine.com/2010/07/01/10-useful-wordpress-security-tweaks/


As a blogger, the URL field in the WordPress comments form is a constant pain – either spammers are using it to drop shady links, or readers feel compelled to fill it with garbage just to fill in the field. Either way, it’s a nuisance. But how do you get rid of it?

Well, I spent a long time searching for the solution to this problem last night, and I’ve written up a solution for removing the URL field that takes into account a number of different scenarios you might encounter!

Obligatory warning! Never apply these types of changes to a production site – I keep a copy of my website themes on a testing server and make changes there. I suggest you do the same!

Before we begin

Most of the changes we’ll be making will be in your WordPress theme. In my experience, there are a few different scenarios that we need to be aware of:

1. Your WordPress theme doesn’t have a comments.php file

If your WordPress theme is missing the comments.php file, WordPress will use the default template, located in /wp-includes/theme-compat/comments.php. This is all well and fine, but the fix detailed below requires the comments.php file to exist in the theme directory.

To overcome this, copy the comments.php file from the folder above into your theme folder. Once you’ve done this, follow the next step:

2. Your WordPress theme has the comment fields inserted manually

Most modern themes will use the <?php comment_form(); ?> code snippet at the bottom of the comments.php file. If this isn’t present in your comments.php file, then you should look for a line of HTML/PHP code that refers to a ‘URL’ field. Simply delete that line and your WordPress comments form should now be missing the website field!

In this scenario, you don’t need to progress to the more advanced solution detailed below – you’re all done!

3. Your theme’s comments.php calls comment_form()

OK – so your comments.php file contains:

<?php comment_form(); ?>

And comments.php is located inside your theme directory? You’ve come to the right place! Step this way…

Remove the Website URL field

OK, open up your theme’s functions.php file and add the following code to the end of the file:


add_filter('comment_form_default_fields', 'url_filtered');
function url_filtered($fields)
{
if(isset($fields['url']))
unset($fields['url']);
return $fields;
}

This code snippet is from TechHacking. However, they talk about implementing it as a plugin. It’s easier if you just add the code to functions.php in your theme.

Now, refresh your blog pages and the URL field should be missing from the comment form. (Aside: if the changes don’t appear right away, make sure you’re not running a caching plugin, and if you are, be sure to flush the cache!)