Hack #3 Wordpress: Custom поиск приводит к страница и шаблон
1.392 взгляда -Вывешено в:
1.392 взгляда
Пожалуйста примечание: Эта страница первоначально была написана на английском языке.
Первоначально столб можно осмотреть здесь.
Please note: This page was originally written in English.
The text has been translated using an online service such as Google or Babelfish.
The original post can be viewed here.
Когда поиском визитеров ваше blog Wordpress будет они находя им нужно? Вы знали вас смогли monetize ваши результаты поиска? Этот «hack wordpress» научит вам как построить ваши собственные custom страницу и шаблон результатов поиска.
Это будет день #3 нашего Wordpress «Рубит--thon» 30 Hacks Wordpress в 30 днях. Если вы не имеете уже -, то теперь время подписаться email или RSS вверху страница!
Каждое blog Wordpress имеет характеристику поиска, и когда люди вписывают keyword в ту коробку поиска они рассчитывает найти уместные результаты. Я иду научить вам как поиск работает за местами в Wordpress, и как вы можете customize оно для вашего blog. Во первых препятствуйте мне сказать что Wordpress имеет его будет собственным механизмом поиска - и им не использует google или другие двигатели поиска для результатов - оно ищет столбы и названия столба внутри ваша база данных. Если вы были заинтересованн внутри, то включайте результаты поиска google custom в вашей теме Wordpress и шаблон это не будет местом. Вместо посещение Поиск Google Custom в Wordpress. Было время когда я использовал результаты google вместо поиска Wordpress в моем blog и я как раз не порекомендую его. Во первых, они рекламируют что оно заработает вами деньг, но на месте получая 10.000 уникально посещениям в день я только сделал между $1.50 и $2.00 в месяц. Во-вторых, google только покажет страницы, котор вы индексировали в ваших результатах. Если все ваши страницы не находятся в индексе google?
Первый шаг в customizing поиск в Wordpress понимающ включили природная стихия, котор:
- searchform.php: Searchform не будет страница, оно будет архив шаблона. Когда вы видите коробку поиска на странице blog, этот архив шаблона формы поиска вызван и будет Кодим использовано для того чтобы установить коробку поиска на странице. If you ever wanted to change or style your search box, this file is the one you would edit to do it. We’re not going to be changing this page at all today.
- search.php: The search.php page is also a template file, the one that’s used any time search results are displayed. Since most Wordpress themes have a search box somewhere on every page you can usually search anywhere. The results that come back use this template file
- searchpage.php: More than likely your blog doesn’t contain it’s own “search page” specifically because of the previous point (you can search anywhere). There is however, no reason not to create one. It’s yet again another page to get indexed in the search engines, yet another page to place original content, yet another page to monetize, and yet another page to point people to important content throughout your site. We are going to create a custom search page or “searchpage.php” today in this tutorial.
As I mentioned, we won’t be customizing the search form today, but we will be creating a custom search page and customizing the search results template. First we’ll make the search page. When completed, this will be a page included in our “Pages” block in the sidebar. Let’s start at the the usual place, the Wordpress Codex page for ‘Creating a Search Page’. It’s a pretty straightforward tutorial for creating a Wordpress search page. You going to download your “page.php” file from your Wordpress theme directory. If your theme doesn’t have one - follow the directions in the previous link for creating one. Save that file as “searchpage.php”.
At the top of the page before anything we need to declare the template name - copy and paste this code:
<?php
/*
Template Name: Custom Search Page
*/
?>
Next you need to any information in “the loop” from this page which you might not need like the meta information (date posted, comments, tags or categories, etc). I can’t tell you what will be in your theme, because every theme is different. I’ll show you mine to use as an example in just a second. You need to add in a heading and search form by pasting these lines (after ‘the loop’):
<h3>Search This Blog</h3>
<?php include (TEMPLATEPATH . '/searchform.php'); ?>
Save “searchform.php” and upload it to your Wordpress theme directory. Your file should look something like this at this point:
<?php
/*
Template Name: Custom Search Page
*/
?>
<?php get_header(); ?>
<div id="wrapper">
<div id="content">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="post" id="post-<?php the_ID(); ?>">
<h2 id="post-title"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h2>
<br />
<div class="entrytext">
<?php the_content('<p class="serif">Read the rest of this page »</p>'); ?>
<?php link_pages('<p><strong>Pages:</strong> ', '</p>', 'number'); ?>
</div>
</div>
<?php endwhile; endif; ?>
<h3>Search This Blog</h3>
<br />
<?php include (TEMPLATEPATH . '/searchform.php'); ?>
<?php edit_post_link('Edit this entry.', '<p>', '</p>'); ?>
</div>
<?php get_sidebar(); ?>
</div>
<?php get_footer(); ?>
Congratulations you just created a (search) page template! Now we’re going to create an actual “page” that uses that template. Go to your Wordpress dashboard to “Write -> Page”. On the right, as in the image example here change “Page Template” to ‘Custom Search Page’. The template we created contains the search form, heading, and later is where we’ll place any advertisements. The Wordpress “page” we’re creating now (that is based on that template) is where we’re going to write the actual content that goes on the page. This would be a great time to exploit your best pages while creating some original content.
The content you write should be something like:
“Welcome to ‘X’ Blog where I write about (link to) category a, (link to) category b, (link to) category c, etc. You might also be interested in x and y article series, my z products, or (link to) advertising on this site. If you still can’t find what you’re looking for (link to) please use my contact form to let me know.
To see what I wrote as an example - just visit my “search everything” page. Now that we’ve build a custom search page, let’s customize our search results! Before I customize any code at all - I’m going to install the “Search Everything Wordpress Plugin“. Normally wordpress only searches titles and the content of posts. But by installing search everything searches can also be configured to look at tags, comments, category names, excerpts, attachments, custom fields, and eve drafts! It can also be used to “exclude” from search any category or post or page ID.

Next, in your dashboard go to “Presentation -> Theme Editor -> Search Results (or search.php)”. This is your “search results template”. Any changes you make to this file will customize the way your search results come out any time a search is performed on your blog, whether from your new search page we created earlier, or from the search box on any page of your blog.
The search results as has a loop, and the way “the loop” works for search results is the same as any other Wordpress templated page. It will show up to 10 results, and then next and previous links to get the rest of the results. In the case of search, it will show your most recent posts matching the keywords searched first, and then the older ones - which will (from the first search result page) only show a rediculous “<< previous entries" link. Some users not used to blogs or Wordpress will assume there are no more search results other than they see on the first page of results. I want some "google style" navigation for the search results that most people are used to seeing to make my search results more usable. Once again - we're going to use a Lester Chan plugin to get this done, WP-PageNavi for Page Navigation.
Again, every theme is different, and my theme has next and previous navigation before and after “the loop” in my search.php template. I’m going to remove it and replace with the WP-PageNavi wordpress plugin’s navigation. First I find the current navigation, which in my template looks like this:
<div class="navigation">
<div class="alignleft"><?php next_posts_link('« Previous Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Next Entries »') ?></div>
<div style="clear:both;"></div>
</div>
Yours may look different, look for the lines with “Previous Entries” and “Next Entries”. I’m going to replace it with the plugin’s code for navigation:
<?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?>
I made that change at both the top and bottom of my search.php because I want to have navigation before and after my search results pages. I wish google did! Now that I have decent navigation it’s time to do a little monetization of the search results. One thing I didn’t mention previously was that when we created the custom search template earlier, I did place an ad in the bottom of that page after “the loop” for my blog network. However, that ad will only display on the “search page” we created. To have any kinds of ads display in our search results themselves, we have to place them in the “search.php” as well. I’m going to place one google adsense block above the search results, and one blog network ad at the end of the search results.
I’m also going to place some adsense blocks interspersed throughout the search results, and to do that I’m going to place the following code within “the loop” of search.php:
<?php if ($count==2) { include('search-adsense-inline.php'); } ?>
<?php if ($count==6) { include('search-adsense-inline.php'); } ?>
<?php $count = $count + 1; ?>
Let me explain what’s going on here. I logged into adsense and grabbed some code for an adblock and I pasted that code into a new file I named “search-adsense-inline.php”. I uploaded that file to my theme directory. Then I placed the code above in my loop in search.php. The first lilne says to grab the contents of that file and place the ad after the second post, and the next line says to do it again after the sixth post. Google now lets you have 3 adblocks (a 3 text link blocks) per page, so with the first block before my results and then these two, that’s the max (adsense) ads I can place here. The third line sets up a counter that starts with the first post, and ads one for every post from 2-10 so it knows where to place your ads.
This is entirely flexible, meaning you could ad more ads (that weren’t adsense) by creating other files and including them after other posts. You could not use adsense at all, and advertise or promote something else! They don’t even have to be ads, they can be links to your content, or funny and weird sayings to freak people out. ANYTHING you put in those files will be after the posts you choose, whether it’s a graphic, text, or code. Use your imagination - I just gave your a bazillion ways to now monetize your search results!
If that weren’t enough - I have yet another way, you can Monetize your search results with a datafeed as well, which will grab products from merchants online using your affiliate feed and show those results on your search results pages. The great thing about that hack is the fact that you never have a page with a blank search result again. If someone searches for “Wordpress Help” and you have no posts, an Amazon feed for instance would show books, or other products related to “Wordpress Help”. While I have your attention on search, I may as well tell you about another great search plugin Psychic Search, which saves information on all search performed on your Wordpress blog. You can get reports and see what people have been looking for over the last week, or month, and beyond. It has reports on what they found, and which searches had no results at all. This is very, very helpful information to know - and possibly information you can use to create future posts!
I hope you learned something today, and now you should have a brand new search page and monetized pimped out search results! If you have something to add or a question, as always - please comment now!
Tags: blog-help, search results, wordpress-hacks, wordpress-templates, wordpress-theme
























April 17th, 2008 at 7:29 pm
Hi,
Thank you for share this, it really increase my knowledge on wordpress
Ramayadi’s last blog post..My Favorite Photographer
July 11th, 2008 at 11:27 am
Thanks for the very useful article. I’m going to modify the search page templates for my sites in this manner. A trifle OT, but I agree that Google Custom Search is not the way to provide search for one’s own site, but I do think that a Google custom search engine, monetized with Adsense, can be a nice addition to a site. If nothing else, it helps earn a little bit of money from the “bounce” traffic. And I found that registering some custom search engines in a few places earned me a few back links. And, among other things, by having a search engine that people can add to the Google toolbar, and/or add to search box in the upper righthand corner of their browser can bring them back to the site for return visits.