Wordpress Code & Research

Icon

All things about wordpress

Removing Category Base from WordPress URLs

I received the following from James, basically requesting information on how to remove the /category/ base from WordPress urls.

Hey, man. Spent quite a while on the site and i’m still having an issue with this, so i’ll give it a go with you. We’re using WP as a CMS with pages and posts. Done a bit of customization, so it looks sweet. Problem – i have some child categories that throw 404 when the category redirect is in place. How did you remove the category base from the url structure in wordpress? This has really got me going… thanks for being accessible!
This was one of the first hacks I figured out for WordPress, so if anyone has an improvement…

WordPress Modifications ^

It’s very important that you replace all the links on your site to /category/slug/ to /slug/ or you will have problems. These steps should only take you a few minutes.

Removing /category/ Automatically ^

This is the main hack to make it work automatically throughout your site. You can place this code in your themes functions.php folder, or you can stick it in a plugin file.

function fix_slash( $string, $type )
{
global $wp_rewrite;
if ( $wp_rewrite->use_trailing_slashes == false )
{
if ( $type != ‘single’ && $type != ‘category’ )
return trailingslashit( $string );

if ( $type == ‘single’ && ( strpos( $string, ‘.html/’ ) !== false ) )
return trailingslashit( $string );

if ( $type == ‘category’ && ( strpos( $string, ‘category’ ) !== false ) )
{
$aa_g = str_replace( “/category/”, “/”, $string );
return trailingslashit( $aa_g );
}
if ( $type == ‘category’ )
return trailingslashit( $string );
}
return $string;
}

add_filter( ‘user_trailingslashit’, ‘fix_slash’, 55, 2 );
category.php Theme Modifications ^

Here’s one way to fix the url in the category.php file of your wordpress theme.

<h1><a href=”http://www.askapache.com/&lt;?php echo str_replace(‘ ‘,’-‘,strtolower(single_cat_title(“”, false)));?>/”><?php echo single_cat_title(“”, false);?></a></h1>

.htaccess Modifications ^

The below .htaccess code illustrates 2 different ways to redirect any request for /category/slug/ to /slug/. You should only redirect after applying the php hacks described earlier, otherwise you could end up creating a loop.

RedirectMatch 301 ^/category/(.+)$ http://www.askapache.com/$1
# OR
RewriteRule ^category/(.+)$ http://www.askapache.com/$1 [R=301,L]
That’s it!

Filed under: Uncategorized

Thesis theme code snippets

Custom Posts & Pages
Archive page information box

remove_action( ‘thesis_hook_archive_info’, ‘thesis_default_archive_info’ );
Custom Homepage Template

remove_action( ‘thesis_hook_custom_template’, ‘thesis_custom_template_sample’ );
Default 404 Title

remove_action( ‘thesis_hook_404_title’, ‘thesis_404_title’ );
Default 404 Content

remove_action( ‘thesis_hook_404_content’, ‘thesis_404_content’ );

Header
Custom Header

remove_action( ‘thesis_hook_header’, ‘thesis_default_header’ );
add_action( ‘thesis_hook_header’, ‘custom_header’ );
/**
* Build custom header
*
* @author Greg Rickaby
* @since 1.0.0
*/
function custom_header() { ?>
<p id=”logo”><a href=”<?php bloginfo(‘url’); ?>”><?php bloginfo(‘name’); ?></a<>/p>
<h1 id=”tagline”><?php bloginfo(‘description’); ?></h1>
<?php }
Remove Header Default Header

remove_action( ‘thesis_hook_header’, ‘thesis_default_header’ );

Navigation
Nav Menu

remove_action( ‘thesis_hook_before_header’, ‘thesis_nav_menu’ );

Content
Search Box

add_action( ‘thesis_hook_before_header’, ‘thesis_search_form’ );
Post Tags

remove_action( ‘thesis_hook_after_post’, ‘thesis_post_tags’ );
Post Navigation

remove_action( ‘thesis_hook_after_content’, ‘thesis_post_navigation’ );
Previous/next post navigation

remove_action( ‘thesis_hook_after_content’, ‘thesis_prev_next_posts’ );

Comments
Comment Link

remove_action( ‘thesis_hook_after_post’, ‘thesis_comments_link’ );
Subscribe to Comments plugin compatibility

remove_action( ‘thesis_hook_comment_form’, ‘show_subscription_checkbox’ );

Footer
Thesis Attribution (Developer license only)

remove_action( ‘thesis_hook_footer’, ‘thesis_attribution’ );
Footer scripts

remove_action( ‘thesis_hook_after_html’, ‘thesis_footer_scripts’ );
How To Use These Snippets
If you wanted to move the Thesis Nav Menu below the Header:

First, remove the Nav from the hook, “Before Header”

remove_action( ‘thesis_hook_before_header’, ‘thesis_nav_menu’ );
Now, add it back to the hook, “After Header”

add_action( ‘thesis_hook_after_header’, ‘thesis_nav_menu’ );
The final syntax in custom_functions.php would look like this:

remove_action(‘thesis_hook_before_header’, ‘thesis_nav_menu’);
add_action(‘thesis_hook_after_header’, ‘thesis_nav_menu’);

Filed under: Thesis

Permalink trong wordpress, để permalink hoạt động trên localhost

Trong viết blog hay website người ta lun coi trong việc sử dụng permalink (URL thân thiện) và nó là một điểm đáng lưu tâm của người làm SEO. Hôm nay chúng ta sẽ kích hoạt nó chạy được trên localhost.
Permalink là gì?

Permalink là một tính năng của WordPress nó giúp ta tối ưu địa chỉ của trang web (URL). Một url thân thiện, gợi nhớ sẽ rất tốt cho người dùng cũng như các công cụ tìm kiếm đễ dàng hơn trong việc hình dung ra nội dung của trang web bạn mún nói gì. Thay vì phải truyền truy vấn như: http://bcdonline.net/?p=1 thì bây giờ có thể sẽ dễ thương hơn khi có URL: http://bcdonline.net/bancamden/.
Sử dụng Permalink trong WordPress

Để có một URL thân thiện bạn nên không để tiếng Việt có dấu trên url của mình, vì có nhiều lý do, dễ dàng nhầm lẫn, làm phức tạp chuỗi địa chỉ, không trong sáng… để làm điều này trong WordPress cũng hỗ trợ cho bạn.

Khi post bài bạn sẽ custom lại chuổi url của mình bằng cách như sau:
Permalink new post

Permalink new post

Bạn nhìn thấy trên hình, nhập vào chuổi địa chỉ bạn muốn hiển thị vào OK.

Bây giờ chúng ta sẽ sử dụng tính năng Permalink, bạn vào admin control của WordPress trong menu settings chọn vào permalink. Và thực hiện như sau:
Sử dụng tính năng permalink trong wordpress

Sử dụng tính năng permalink trong wordpress

Đến phần quan trong rồi đây trong này có nhiều vấn đề cần nói. Kiểu mặc định của nó là giá trị nguyên thủy bao gồm ID mà thôi, kiểu thứ hai cho phép hiển thị ngày tháng năm vào kèm theo là ten của bài viết, Kiểu thứ ba là năm tháng rồi tên bài viết, kiểu thứ tư là tên bài viết đến ID.

Tiếp đến kiểu thứ năm là tùy chọn, cho phép bạn nhập chuỗi hiển thị, trong WordPress cung cấp cho chúng ta có các chuỗi hiển thị như sau:

/%postname%/: hiển thị url bao gồm tên mà thôi ví dụ: http://bcdonline.net/lien-he/. Blog mình cũng đang xài kiểu này.
/%postname%.html: bạn cũng có thể thêm vào sau đó là đuôi .html hay một đuôi mở rộng nào đó tùy ý. Ví dụ: http://localhost/wordpress/bcdonline.html
/%category%/%postname%/: tên thể loại và sau đó là tên bài viết thuộc thể loại đó. Ví dụ: http://localhost/wordpress/bcdonline-net/bcdonline/
Và còn nhiều thành phần khác nữa.

Ngoài ra bạn cũng thấy ở hình trên có hai thành phần nữa là category base và tag base.

category base: Qui định hiển thị tên chung của thể loại hay chủng loại gì đó, mặc định là category.
tag base: Qui đinh hiển thị tên chung của từ khóa, mặc định là tag.

Để Permalink làm việc trên localhost

Sau khi đã làm các công việc trên đối với những ai xài appser hay wamp thì vẫn chưa xong đâu vì chạy trang index dc nhưng click vào các trang chi tiết bài post thì báo lỗi 404 (Not Found).

Để khắc phục tình trạng này bạn thực hiện như sau: Vào trong thư mục của E:\AppServ\Apache2.2\conf\httpd.conf tùy vào địa chỉ bạn vài đặt nha! mở file đó lên tìm đến dòng có chữ:
1

#LoadModule rewrite_module modules/mod_rewrite.so

Bạn bỏ dấu # ở trước đó đi, với wamp thì bạn tìm thêm dòng:
1

# Controls who can get stuff from this server.

Bạn tiến hành khởi động lại Apache của server lại và test thử.

Kết luận: Vậy là mình đã giới thiệu cho các bạn cách sử dụng permalink và custom permalink trong wordpress và phương pháp để nó hoạt động trên localhost. Chúc thành công!

Filed under: WP settings

10 Image and Gallery Lightbox Solutions for WordPress – Plugins

The easiest way to create an image gallery within WordPress is by using the add feature (from WP 2.5+), but to give your gallery something extra you may wish to add the Lightbox effect. Originally developed byLokeshdhaker.com, Lightbox has gained widespread popularity because it is easy to use and it gives a professional and stylish finish to your images.

Lightbox 2 WP Plugin

WP Lightbox Plugins

Description : Lightbox 2 allows you to present images in a slick window, while darkening the rest of the page. It gives your site a professional feel and adds very little to page load times. Lightbox 2 works on almost every web browser out there, if a browser doesn’t support javascript, the code fails gracefully.
This is the simplest and easiest plugin to use, if its an easy image gallery you want, this is for you.
Compatibility :Up to WP 2.7.
Demo : View Demo.

jQuery Lightbox Plugin WP Plugin

WP Lightbox Plugins

Description : This is WordPress’s version of the jQuery Lightbox Plugin written by Balupton, the effect keeps with the traditional lightbox effect (simple overlay), it does not offer many frills, but just like Lightbox2 above, it is simple to use and implement.
Compatibility :Up to WP 2.7.
Demo : View Demo.

Picasa LightBox WP Plugin

WP Lightbox Plugins

Description : You can add Picasa images to your posts and pages without using any custom tags, click the Picasa Photos tab, browse your albums and select the picture you want to insert. Picasa LightBox does not download Picasa images to your serve, instead it displays them directly from Picasa.
The simplest and easiest plugin to use, if its a simple gallery you want, this is for you.
Compatibility :Up to WP 2.5.
Demo : View Demo.

Lightbox Gallery WP Plugin

WP Lightbox Plugins

Description : This plugin uses add , which was introduced in WordPress 2.5. The plugin automatically converts the default view of your gallery into the lightbox view. A nice feature of this plugin are the tooltips which display the images captions.
Compatibility :WP 2.5 – WP 2.7.
Demo : View Demo.

jQuery Lightbox For Native Galleries WP Plugin

WP Lightbox Plugins

Description : This plugin allows to use the Lightbox features for images and wordpress galleries without touching the html code. It includes an option “Open using lightbox” on the Setting Panel to be used before inserting the single images on your post. And for the native WordPress galleries the plugin inserts the “lightbox” class automatically.
Compatibility :Up to WP 2.7.
Demo : View Demo.

Flexible Lightbox WP Plugin

WP Lightbox Plugins

Description : This plugin integrates nicely into the gallery features offered by WordPress, it extends the features by adding Lightbox into the mix.
Compatibility :WP 2.5 – WP 2.7.
Demo : View Demo.

Add LightBox & Title WP Plugin

WP Lightbox Plugins

Description : This plugin automatically adds the rel=”lightbox[POST-ID]” to images linked in a post and in a comment, and recovers the image title. POST-ID is unique per post so all images per post are grouped in one lightbox set.
Compatibility :WP 2.5 – WP 2.7.
Screenshots : View Screenshots.

Slimbox WP Plugin

WP Lightbox Plugins

Description : This plugin includes the new Slimbox 1.64 , it is a 7kb visual clone of the popular Lightbox JS v2.0 by Lokesh Dhakar, written using the MooTools framework. It was designed to be small, efficient, more convenient and 100% compatible with the original Lightbox v2.
Compatibility :Up to WP 2.7.
Demo : View Demo.

Shadowbox JS WP Plugin

WP Lightbox Plugins

Description : A javascript media viewer similar to Lightbox and Thickbox only better, much better. It supports all types of media (flash, video, mp3…), not just images. This plugin can also be used as a drop in lightbox replacement, without requiring you to edit posts already using lightbox.
This is by far the most powerful WP Lightbox plugin, it is easy to use and install as well. Recommended.
Compatibility :WP 2.6 – WP 2.8.
Screenshots : View Screenshots.

Add Lightbox WP Plugin

Description : This plugin for WordPress automatically add the lightbox effect to all images linked within a post, all images from a post are also grouped into one lightbox set creating a simple gallery. Useful plugin, unless you only want certain images to have the lightbox effect.
Compatabilty :Up to WP 2.7.

Filed under: Plugins

WordPress Error – “Allowed memory size of 8388608 bytes”

You sometimes might get the following error if you are trying to import a previous blog into a newly installation of WordPress through an RSS feed or while installing a new plugin as:

Allowed memory size of 8388608 bytes exhausted (tried to allocate xxxxx bytes)

This means that the server is not allowing to process the size of the data than its maximum alloted size. Remember that there is nothing wrong with the WordPress installation. Its the matter of the amount of data that the server can process at one time.

Don’t be scared, you can get it resolved in a matter of seconds. There are two ways of resolving this error.

Method #1 : Without Restarting the Server

If the error mentioned appears during the importing, what you need to do is get access to the source code of the WordPress where you have done the installation.

Once you get the access you will need to modify two files . They are:

  1. <installation_directory>/wp-admin/import.php
  2. <installation_directory>/wp-admin/import/wordpress.php

Now copy this line of code:

ini_set('memory_limit','16M');

This line increases the server processing capacity by the included size i.e 16M. Paste the above line in the import.php file just after the line of code:

require_once ('admin-header.php');

Now in the second file i.e. wordpress.php paste the code after the line of code:

<?php

Note: If the error mentioned appears during the installation of a plugin then make a note of the path and the .php page which is given out in the error and paste the same line in the mentioned .php page.Remember, the code must be pasted within the php code block i.e in between <?php and php?> in the page since it is to be executed by the server.

Now once again access your WordPress URL and go to the manage > import menu and try importing. If your problem still remains, just keep increasing the size mentioned in the pasted code in multiples of 4 i.e. in place of “16M”, try “20M”, “24M” etc.

Method #2 : Which Requires a Server Restart

If you want to eliminate this error once and for all then you need to target your server to make the changes. But you should have the permissions to restart the server.

If you have this permission then go to the server installed path and search for the file php.ini file. In this file there will numerous things mentioned. But all you have to do is search for the term “memory_limit“. Change the value of this variable from 8M to either 16M, 24M, etc as required.

Save the file and restart your server. The error will be resolved once and for all. Good luck!

Filed under: WP settings

Get the lastest posts from a category

<h2>Recent Posts</h2>
<ul>
<?php
	$args = array( 'numberposts' => '5' );
	$recent_posts = wp_get_recent_posts( $args );
	foreach( $recent_posts as $recent ){
		echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.$recent["post_title"].'" >' .   $recent["post_title"].'</a> </li> ';
	}
?>
</ul>

Filed under: BASIC CODE

Add New Hook In Prestashop

PrestaShop hooks are great way to insert or add data at the most important places or actions of this great e-commerce platform. But may be some time you want to use custom hooks with my custom modules. So here I show you how to implement custom hook?


How to create custom hook?

Step 1: Register a new hook in FrontController.php

open file \classes\FrontController.php and find below code

1
2
3
4
5
self::$smarty->assign(array(
'HOOK_HEADER' => Module::hookExec('header'),
'HOOK_TOP' => Module::hookExec('top'),
'HOOK_LEFT_COLUMN' => Module::hookExec('leftColumn')
));

Updated code

For add new hook I add this line of code

1
'HOOK_Top_Center' => Module::hookExec('topCenter') // New Hook

So you code look like below.

1
2
3
4
5
6
self::$smarty->assign(array(
'HOOK_HEADER' => Module::hookExec('header'),
'HOOK_TOP' => Module::hookExec('top'),
'HOOK_LEFT_COLUMN' => Module::hookExec('leftColumn'),
'HOOK_Top_Center' => Module::hookExec('topCenter')
));

Step 2: All active hooks are hold in Prestashop database table called ps_hook. So I make query for new hook and run into database.

1
2
3
4
5
6
7
8
9
10
INSERT INTO 'yourdatabasename'.'ps_hook' (
'id_hook' ,
'name' ,
'title' ,
'description' ,
'position'
)
VALUES (
NULL , 'topCenter', 'Top of Center', NULL , '1'
);

What are field mean ps_hook.

`id_hook` = An auto increment value
`name` = Name of the new hook
`title` = This title is used in Modules tab in Back Office
`description` = The description of hook (optional)
`position` = Whether this hook observe the order of appearance with other module or not

Or you can add value manually from php myadmin.

open your “php_myadmin” and table “ps_hook” click on “insert” and insert ‘new’ hook name, ‘new hook’ in ‘title’

Step 3: Add code in your module:

Please create new function with name hooktopCenter in class of modules PHP file which you want to use.
‘hook’ is prefix function for hook
‘topCenter’ is name of hook postion

Here I call blockmanufacturer.tpl file in this funcation.

1
2
3
4
5
6
7
8
9
10
11
12
13
function hooktopCenter($params){
global $smarty, $link;
$smarty->assign(array(
'manufacturers' => Manufacturer::getManufacturers(),
'link' => $link,
'text_list' => Configuration::get('MANUFACTURER_DISPLAY_TEXT'),
'text_list_nb' => Configuration::get('MANUFACTURER_DISPLAY_TEXT_NB'),
'form_list' => Configuration::get('MANUFACTURER_DISPLAY_FORM'),
'display_link_manufacturer' => Configuration::get('PS_DISPLAY_SUPPLIERS'),
));
return $this->display(__FILE__, 'blockmanufacturer.tpl');
}

Step 4: Add the code {$HOOK_Top_Center} in theme/prestashop/header.tpl or any other tpl file where you want to use it.

1
<div id="header_right"> {$HOOK_Top_Center} </div>

Step 5: Then go to backend
=> Click on module top of link and configure any module which you want to change position and show in you new hook position.
=> Click position
=> Click on transplant module and select “topCenter” from dropdown and save.

Than look at your frontend at that position.

Filed under: Prestashop

Add widget to wordpress theme

We can add widget to wordpress theme ( any where: sidebar,footer,content page,…)

In this example, I will guide you add widget to wordpress theme.

There are really three main parts to introducing a footer-sidebar
1. Registering the Sidebars in the WordPress Theme
2. Inserting the Sidebars In the WordPress Theme
3. Putting some style into the sidebars

1. Register the Sidebars in the WordPress Theme

Go to the WordPress theme editor and open the Theme Functions (functions.php) file. Now Search for the following line in your Theme Functions (functions.php)

if ( function_exists('register_sidebar') )

Once you find the above line then take a look at the the next line which should look similar to one of the followings depending on how many sidebars you have:

register_sidebar(array(
or
register_sidebars(2,array(

Say for example you have one sidebar in your theme and you want to add three rows of sidebars in the footer area so you can put widgets then overwrite the code with the following:

register_sidebars(4,array(

The above will register 4 sidebars (one that you already have and three more that you are about to introduce in the footer area of your wordpress theme).

2. Insert the Sidebars In the WordPress Theme

Now lets insert the siderbars where we want them in the WordPress theme. In our case we are going to insert in in the footer area of the theme so open the Footer (footer.php) file and insert the following code just above the ‘footer’ division:

<div id="footer-sidebar">
<div id="footer-sidebar1">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar(2) ) : ?>
<?php endif; ?>
</div>

<div id="footer-sidebar2">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar(3) ) : ?>
<?php endif; ?>
</div>

<div id="footer-sidebar3">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar(4) ) : ?>
<?php endif; ?>
</div>

</div>
<div style="clear-both"></div>

3. Put some style into the sidebars

Finally, lets put a little style to all the ‘footer-sidebar’ divisions that we just introduced. Open the Stylesheet (style.css) file and insert the following CSS (you will probably have to adjust the CSS to your need depending on what wordpress theme you are using).

#footer-sidebar {
display:block;
height: 250px;
}

#footer-sidebar1 {
float: left;
width: 340px;
margin-left:5px;
margin-right:5px;
}

#footer-sidebar2 {
float: left;
width: 340px;
margin-right:5px;
}

#footer-sidebar3 {
float: left;
width: 340px;
}

Hope this helps! Now you don’t have to change your beloved WordPress theme just to get footer-sidebar :)

Filed under: BASIC CODE

Get page in wordpress

1- When you want to list all pages, you can use this function:

  <?php wp_list_pages( $args ); ?>

2- Get ID OF A PAGE BY SLUG PAGE

function get_ID_by_slug($page_slug) {
$page = get_page_by_path($page_slug);
if ($page) {
return $page->ID;
} else {
return null;
}
}

3 – Get page title by page ID

<?php $pageID = 86; $page = get_post($pageID); 
echo $page->post_title; ?>

Filed under: BASIC CODE

Get taxonomy in wordpress

Today, I post about the way to get taxonomy in wordpress:
1-Get the taxonomy name by query_var

$the_tax = get_taxonomy( get_query_var( ‘taxonomy’ ) );
echo $the_tax->labels->name;

Get

if (is_archive())
{
if(is_tax(‘destination’))
{
$term = get_term_by( ‘slug’, get_query_var( ‘term’ ),            get_query_var( ‘taxonomy’ ) );

Get the description:
echo $term->description);

or use this:

$description = explode(“|”, $term->description);
$dest1= $description[0];
echo $dest1;
}
}

Filed under: BASIC CODE, , ,