Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Web Development

1802 Articles
article-image-testing-your-jboss-drools-business-rules-using-unit-testing
Packt
14 Oct 2009
5 min read
Save for later

Testing your JBoss Drools Business Rules using Unit Testing

Packt
14 Oct 2009
5 min read
What is unit testing? A good enterprise computer system should be built as if it was made of Lego bricks. Your rules are only a piece of the puzzle. You'll need to go back to the Lego box to get pieces that talk to the database, make web pages, talk to other systems that you may have in your company (or organization), and so on. Just as Lego bricks can be taken apart and put together in many different ways, the components in a well-designed system should be reusable in many different systems. Before you use any of these components (or 'bricks') in your system, you will want to be sure that they work. For Lego bricks this is easy—you can just make sure that none of the studs are broken. For components this is a bit harder—often, you can neither see them, nor do you have any idea whether their inputs and outputs are correct. Unit testing makes sure that all of the component pieces of your application work, before you even assemble them. You can unit test manually, but just like FIT requirements testing, you're going to 'forget' to do it sooner or later. Fortunately, there is a tool to automate your unit tests known as Junit (for Java; there are also versions for many other languages, such as .Net). Like Drools and FIT, Junit is open source. Therefore, we can use it on our project without much difficulty. Junit is integrated into the JBoss IDE and is also pretty much an industry standard, so it's easy to find more information on it. A good starting point is the project's home page at http://www.Junit.org. The following points can help you to decide when to use unit testing, and when to use the other forms of testing that we talked about: If you're most comfortable using Guvnor, then use the test scenarios within Guvnor. As you'll see shortly, they're very close to unit tests. If the majority of your work involves detailing and signing off against the requirement documents, then you should consider using FIT for Rules. If you're most comfortable using Java, or some other programming language, then you're probably using (J)unit tests already—and we can apply these unit tests to rule testing. In reality, your testing is likely to be a mix of two or three of these options. Why unit test? An important point to note is that you've already carried out unit testing in the rules that we wrote earlier. OK, it was manual unit testing, but we still checked that our block of rules produced the outcome that we expected. All we're talking about here is automating the process. Unit testing also has the advantage of documenting the code because it gives a working example of how to call the rules. It also makes your rules and code more reusable. You've just proved (in your unit test) that you can call your code on a standalone basis, which is an important first step for somebody else to be able to use it again in the future. You do want your rules to be reused, don't you? Unit testing the Chocolate Shipments sample As luck would have it, our Chocolate Shipments example also contains a unit test. This is called DroolsUnitTest.java, and it can be found in the test/java/net/firstpartners/chap7 folder. Running the Junit test is similar to running the samples. In the JBoss IDE Navigator or package explorer, we select DroolsUnitTest.java, right-click on it, and then select Run as | Junit test from the shortcut menu. All being well, you should see some messages appear on the console. We're going to ignore the console messages; after all, we're meant to be automating our testing, not manually reading the console. The really interesting bit should appear in the IDE— the Junit test result, similar to the screenshot shown below. If everything is OK, we should see the green bar displayed—success! We've run only one unit test, so the output is fairly simple. From top to bottom we have: the time it took to run the test; the number of errors and failures (both zero—we'll explain the difference shortly, but having none of them is a good thing), the green bar (success!), and a summary of the unit tests that we've just run (DroolsUnitTest). If you were running this test prior to deploying to production, all you need to know is that the green bar means that everything is working as intended. It's a lot easier than inspecting the code line by line. However, as this is the first time that we're using a unit test, we're going to step through the tests line by line. A lot of our Junit test is similar to MultipleRulesExample.java. For example, the unit test uses the same RuleRunner file to load and call the rules. In addition, the Junit test also has some automated checks (asserts) that give us the green bar when they pass, which we saw in the previous screenshot.
Read more
  • 0
  • 0
  • 7608

article-image-building-facebook-application-part-1
Packt
14 Oct 2009
4 min read
Save for later

Building a Facebook Application: Part 1

Packt
14 Oct 2009
4 min read
A simple Facebook application Well, with the Facebook side of things set up, it's now over to your server to build the application itself. The server could of course be: Your web host's server – This must support PHP, and it may be worthwhile for you to check if you have any bandwidth limits. Your own server – Obviously, you'll need Apache and PHP (and you'll also need a fixed IP address). Getting the server ready for action Once you have selected your server, you'll need to create a directory in which you'll build your application, for example: mkdir -p /www/htdocs/f8/penguin_picd /www/htdocs/f8/penguin_pi If you haven't already done so, then this is the time to download and uncompress the Facebook Platform libraries: wget http://developers.facebook.com/clientlibs/facebook-platform.tar.gztar -xvzf facebook-platform.tar.gz We're not actually going to use all of the files in the library, so you can copy the ones that you're going to use into your application directory: cp facebook-platform/client/facebook.phpcp facebook-platform/client/facebookapi_php5_restlib.php And once that's done, you can delete the unwanted files: rm -rf facebook-platform.tar.gz facebook-platform Now, you're ready to start building your application. Creating your first Facebook application Well, you're nearly ready to start building your application. First, you'll need to create a file (let's call it appinclude.php) that initiates the application. The application initiation code We've got some code that needs to be executed every time our application is accessed, and that code is: <?phprequire_once 'facebook.php'; #Load the Facebook API$appapikey = '322d68147c78d2621079317b778cfe10'; #Your API Key$appsecret = '0a53919566eeb272d7b96a76369ed90c'; #Your Secret$facebook = new Facebook($appapikey, $appsecret); #A Facebook object$user = $facebook->require_login(); #get the current user$appcallbackurl = 'http://213.123.183.16/f8/penguin_pi/'; #callback Url#Catch an invalid session_keytry { if (!$facebook->api_client->users_isAppAdded()) { $facebook->redirect($facebook->get_add_url()); }} catch (Exception $ex) { #If invalid then redirect to a login prompt $facebook->set_user(null, null); $facebook->redirect($appcallbackurl);}?> You'll notice that the code must include your API Key and your secret (they were created when you set up your application in Facebook). The PHP file also handles any invalid sessions. Now, you're ready to start building your application, and your code must be written into a file named index.php. The application code Our application code needs to call the initiation file, and then we can do whatever we want: <?phprequire_once 'appinclude.php'; #Your application initiation fileecho "<p>Hi $user, ";echo "welcome to Pygoscelis P. Ellsworthy's Suspect Tracker</p>";?> Of course, now that you've written the code for the application, you'll want to see what it looks like. Viewing the new application Start by typing your Canvas Page URL into a browser (you'll need to type in your own, but in the case of Pygoscelis P. Ellesworthy's Suspect Tracker, this would be http://apps.facebook.com/penguin_pi/): You can then add the application just as you would add any other application: And at last, you can view your new application: It is worth noting, however, that you won't yet be able to view your application on your profile. For the time being, you can only access the application by typing in your Canvas Page URL. That being said, your profile will register the fact that you've added your application: That's the obligatory "Hello World" done. Let's look at how to further develop the application.
Read more
  • 0
  • 0
  • 2469

article-image-building-friend-networks-django-10
Packt
14 Oct 2009
6 min read
Save for later

Building Friend Networks with Django 1.0

Packt
14 Oct 2009
6 min read
An important aspect of socializing in our application is letting users to maintain their friend lists and browse through the bookmarks of their friends. So, in this section we will build a data model to maintain user relationships, and then program two views to enable users to manage their friends and browse their friends' bookmarks. Creating the friendship data model Let's start with the data model for the friends feature. When a user adds another user as a friend, we need to maintain both users in one object. Therefore, the Friendship data model will consist of two references to the User objects involved in the friendship. Create this model by opening the bookmarks/models.py file and inserting the following code in it: class Friendship(models.Model): from_friend = models.ForeignKey( User, related_name='friend_set' ) to_friend = models.ForeignKey( User, related_name='to_friend_set' ) def __unicode__(self): return u'%s, %s' % ( self.from_friend.username, self.to_friend.username ) class Meta: unique_together = (('to_friend', 'from_friend'), ) The Friendship data model starts with defining two fields that are User objects: from_friend and to_friend. from_friend is the user who added to_friend as a friend. As you can see, we passed a keyword argument called related_name to both the fields. The reason for this is that both fields are foreign keys that refer back to the User data model. This will cause Django to try to create two attributes called friendship_set in each User object, which would result in a name conflict. To avoid this problem, we provide a specific name for each attribute. Consequently, each User object will contain two new attributes: user.friend_set, which contains the friends of this user and user.to_friend_set, which contains the users who added this user as a friend. Throughout this article, we will only use the friend_set attribute, but the other one is there in case you need it . Next, we defined a __unicode__ method in our data model. This method is useful for debugging. Finally, we defined a class called Meta. This class may be used to specify various options related to the data model. Some of the commonly used options are: db_table: This is the name of the table to use for the model. This is useful when the table name generated by Django is a reserved keyword in SQL, or when you want to avoid conflicts if a table with the same name already exists in the database. ordering: This is a list of field names. It declares how objects are ordered when retrieving a list of objects. A column name may be preceded by a minus sign to change the sorting order from ascending to descending. permissions: This lets you declare custom permissions for the data model in addition to add, change, and delete permissions. Permissions should be a list of two-tuples, where each two-tuple should consist of a permission codename and a human-readable name for that permission. For example, you can define a new permission for listing friend bookmarks by using the following Meta class: class Meta: permissions = ( ('can_list_friend_bookmarks', 'Can list friend bookmarks'), ) unique_together: A list of field names that must be unique together. We used the unique_together option here to ensure that a Friendship object is added only once for a particular relationship. There cannot be two Friendship objects with equal to_friend and from_friend fields. This is equivalent to the following SQL declaration: UNIQUE ("from_friend", "to_friend") If you check the SQL generated by Django for this model, you will find something similar to this in the code. After entering the data model code into the bookmarks/models.py file, run the following command to create its corresponding table in the database: $ python manage.py syncdb Now let's experiment with the new model and see how to store and retrieve relations of friendship. Run the interactive console using the following command: $ python manage.py shell Next, retrieve some User objects and build relationships between them (but make sure that you have at least three users in the database): >>> from bookmarks.models import *>>> from django.contrib.auth.models import User>>> user1 = User.objects.get(id=1)>>> user2 = User.objects.get(id=2)>>> user3 = User.objects.get(id=3)>>> friendship1 = Friendship(from_friend=user1, to_friend=user2)>>> friendship1.save()>>> friendship2 = Friendship(from_friend=user1, to_friend=user3)>>> friendship2.save() Now, user2 and user3 are both friends of user1. To retrieve the list of Friendship objects associated with user1, use: >>> user1.friend_set.all()[<Friendship: user1, user2>, <Friendship: user1, user3>] (The actual usernames in output were replaced with user1, user2, and user3 for clarity.) As you may have already noticed, the attribute is named friend_set because we called it so using the related_name option when we created the Friendship model. Next, let's see one way to retrieve the User objects of user1's friends: >>> [friendship.to_friend for friendship in user1.friend_set.all()][<User: user2>, <User: user3>] The last line of code uses a Python feature called "list" comprehension to build the list of User objects. This feature allows us to build a list by iterating through another list. Here, we built the User list by iterating over a list of Friendship objects. If this syntax looks unfamiliar, please refer to the List Comprehension section in the Python tutorial. Notice that user1 has user2 as a friend, but the opposite is not true. >>> user2.friend_set.all() [] In other words, the Friendship model works only in one direction. To add user1 as a friend of user2, we need to construct another Friendship object. >>> friendship3 = Friendship(from_friend=user2, to_friend=user1)>>> friendship3.save()>>> user2.friend_set.all() [<Friendship: user2, user1>] By reversing the arguments passed to the Friendship constructor, we built a relationship in the other way. Now user1 is a friend of user2 and vice-versa. Experiment more with the model to make sure that you understand how it works. Once you feel comfortable with it, move to the next section, where we will write views to utilize the data model. Things will only get more exciting from now on!
Read more
  • 0
  • 0
  • 9485

article-image-synchronous-communication-and-interaction-moodle-19-multimedia
Packt
14 Oct 2009
5 min read
Save for later

Synchronous Communication and Interaction with Moodle 1.9 Multimedia

Packt
14 Oct 2009
5 min read
These options can be helpful for distance education, providing new ways of communicating and interacting with our students (and between them) when we are not all in the same physical space. Because Moodle does not provide effective synchronous communication tools (the chat activity could overload the server), the aforementioned tools are presented as extensions that can support our courses, giving them a new level of interaction. In distance courses with considerable duration, such communication can be a motivation and a way of providing support to students when we are online at the same time. Communicating in real-time using text, audio, and video Google Chat is a service from Google that allows text, audio, and video chat amongst Google Mail users meaning, we'll need a Google account. The audio conversation is usually called Voice over IP (VoIP), but as bandwidth allowances increase, the use of video is becoming common. With this tool we can: Meet with colleagues or students, individually or in groups Participate in a distant event (for example, attend a conference) Conduct interviews Teach how to play an instrument (by using the webcam) Teach gestural language (by using the webcam) I find it really useful to use VoIP in distance courses, not only to give feedback to students and get to know them better, but also to create opportunities for students to interact with each other during group tasks outside of these tutor-students meeting times. A good time to use this application is in Module 10 – What's good music—a theme that fits well with an online debate about how to define quality criteria for music. Students will be required to work in groups and debate on what they think is good music and how it can be assessed. This discussion will be facilitated by using this tool. Chat and group chat The chat option is available in Google Mail, on the sidebar on the left. For a start, we can configure some settings, especially privacy settings, by going to Options | Chat settings…: In the section Auto-add suggested contacts, we should select the option Only allow people that I've explicitly approved to chat with me and see when I'm online option, as shown in the screenshot below: We can also disable chat history if we don't want to keep a record of our chat. There is another option during a chat to go "off record", meaning that if the chat history is on, this portion of the conversation (that takes place whilst this option is selected) will not be archived. We are now ready to start a chat. We can search for contacts in the same Google Mail Chat sidebar, using the search form that is available (Search, add or invite) and double-click on the name of the contact that is displayed, or in the Chat link of the pop-up window that is displayed: Because the chat is synchronous, it's obvious that the (two or more) people chatting must be online. We can check if a person is online or not by looking at the small icon next to the people we've located, or in our chat list. If they have a grey, round icon on the left of their name, they are offline (or invisible and don't want to be bothered). If the color is green (available), yellow (idle), or red (busy) it's possible to chat to them. In the pop-up, we can also add the person to the chat list below the search form. After starting the chat, a window similar to the one shown below opens in the lower-right corner of the Google Mail account, and we can start talking: When we are chatting with someone, we can click on the Video & More | Group Chat option to invite one or more friends to join the conversation: A new window will appear, in which we can chat with the participants. Note that if we click on the arrow in the blue bar at the top of our chat window, the window will pop-up from its position in the Google Mail window and we can access it as an independent window. If we paste a URL from a YouTube video into the chat window, a preview of the video will be integrated directly into our conversation, as shown in the screenshot below: Transferring files The easiest way to send files to participants for reading, or supporting discussion or commenting upon is either by using Google Mail, or by uploading them to Moodle or Google Docs and sharing these with the chat participants. This can be useful in many online discussions. Voice and video chat Chat, as we saw, is available by default in Google Mail, on the leftmost sidebar. To add audio and voice capabilities to this chat, we have to install a plug-in that is available at http://mail.google.com/videochat, for Windows and Mac users (again, sorry to Linux users). After installing this plug-in, we can start an audio or video conversation (only one-to-one). If our contacts have a camera or microphone, we can click on the Video & more option again, and the following two options will be available: In the case of voice chat, a call will be started, and we will also keep the text chat functionality: In the case of video chat, the same applies. In the upper area, a video of the person that we are chatting with will be displayed, and in the lower corner, if we have a webcam, our video will be displayed: Image source: Scmoewes (2005). Jimi. Retrieved March 30, 2009,from http://www.flickr.com/photos/cmoewes/30989105/ For distance courses or even in e-learning, Google chat is an option. But if we need more complex functionality, including audio conferencing and desktop sharing, there are other tools that are available. We will now look at one in particular, called Dimdim.
Read more
  • 0
  • 0
  • 1843

article-image-creating-administration-interface-django-10
Packt
14 Oct 2009
5 min read
Save for later

Creating an Administration Interface with Django 1.0

Packt
14 Oct 2009
5 min read
Activating the administration interface The administration interface comes as a Django application. To activate it, we will follow a simple procedure that is similar to enabling the user authentication system. The administration application is located in the django.contrib.admin package. So the first step is adding the path of this package to the INSTALLED_APPS variable. Open the settings.py file, locate INSTALLED_APPS, and edit it as follows: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.comments', 'django_bookmarks.bookmarks',) Next, run the following command to create the necessary tables for the administration application: $ python manage.py syncdb Now we need to make the administration interface accessible from within our site by adding URL entries for it. The admin application defines many views (as we will see later), so manually adding a separate entry for each view can become a tedious task. Therefore, the admin interface provides a shortcut for this. There is a single object that encapsulates all the admin views. To use it, open the urls.py file and edit it as follows: from django.contrib import adminadmin.autodiscover()urlpatterns = ('', [...] # Admin interface (r'^admin/(.*)', admin.site.root),) Here, we are importing the admin module, calling a method in it, and mapping all the URLs under the path ^admin/ to a view called admin.site.root. This will make the views of the administration interface accessible from within our project. One last thing remains before we see the administration page in action. We need to tell Django what models can be managed in the administration interface. This is done by creating a new file called the admin.py file in the bookmarks directory. Create the bookmarks/admin.py file and add the following code to it: from django.contrib import adminfrom bookmarks.models import *class LinkAdmin(admin.ModelAdmin): passadmin.site.register(Link, LinkAdmin) We created a class derived from the admin.ModelAdmin class and mapped it to the Link model using the admin.site.register method. This effectively tells Django to enable the Link model in the administration interface. The keyword pass means that the class is empty. Later, we will use this class to customize the administration page; so it won't remain empty. Do the same to the Bookmark, Tag, and SharedBookmark models and add it to the bookmarks/admin.py file. Now, create an empty admin class for each of them and register it. The User model is provided by Django and, therefore, we don't have control over it. But fortunately, it already has an Admin class so it's available in the administration interface by default. Next, launch the development server and direct your browser to http://127.0.0.1:8000/admin/. You will be greeted by a login page. The superuser account after writing the database model is the account that you have to use in order to log in: Next, you will see a list of the models that are available to the administration interface. As discussed earlier, only models that have admin classes in the bookmarks/admin.py file will appear on this page. If you click on a model name, you will get a list of the objects that are stored in the database under this model. You can use this page to view or edit a particular object, or to add a new one. The following figure shows the listing page for the Link model: The edit form is generated according to the fields that exist in the model. The Link form, for example, contains a single text field called Url. You can use this form to view and change the URL of a Link object. In addition, the form performs proper validation of fields before saving the object. So if you try to save a Link object with an invalid URL, you will receive an error message asking you to correct the field. The following figure shows a validation error when trying to save an invalid link: Fields are mapped to form widgets according to their type. For example, date fields are edited using a calendar widget, whereas foreign key fields are edited using a list widget, and so on. The following figure shows a calendar widget from the user edit page. Django uses it for date and time fields. As you may have noticed, the administration interface represents models by using the string returned by the __unicode__ method. It was indeed a good idea to replace the generic strings returned by the default __unicode__ method with more helpful ones. This greatly helps when working with the administration page, as well as with debugging. Experiment with the administration pages. Try to create, edit, and delete objects. Notice how changes made in the administration interface are immediately reflected on the live site. Also, the administration interface keeps a track of the actions that you make and lets you review the history of changes for each object. This section has covered most of what you need to know in order to use the administration interface provided by Django. This feature is actually one of the main advantages of using Django. You get a fully featured administration interface from writing only a few lines of code! Next, we will see how to tweak and customize the administration pages. As a bonus, we will learn more about the permissions system offered by Django.
Read more
  • 0
  • 0
  • 5044

article-image-anatomy-typo3-extension
Packt
14 Oct 2009
8 min read
Save for later

Anatomy of TYPO3 Extension

Packt
14 Oct 2009
8 min read
TYPO3 Extension Categories All TYPO3 extensions are classified into several predefined categories. These categories do not actually differentiate the extensions. They are more like hints for users about extension functionality. Often, it is difficult for the developer to decide which category an extension should belong to. The same extension can provide PHP code that fits into many categories. An extension can contain Frontend (FE) plugins, Backend (BE) modules, static data, and services, all at once. While it is not always the best solution to make such a monster extension, sometimes it is necessary. In this case, the extension author should choose the category that best fits the extension's purpose. For example, if an extension provides a reservation system for website visitors, it is probably FE related, even if it includes a BE module for viewing registrations. If an extension provides a service to log in users, it is most likely a service extension, even if it logs in FE users. It will be easier to decide where the extension fits after we review all the extension categories in this article. Choosing a category for an extension is mandatory. While the TYPO3 Extension Manager can still display extensions without a proper category, this may change and such extensions may be removed from TER (TYPO3 Extension Repository) in the future. The extension category is visible in several places. Firstly, extensions are sorted and grouped by category in the Extension Manager. Secondly, when an extension is clicked in the Extension Manager, its category is displayed in the extension details. If an extension's category is changed from one to another, it does not affect extension functionality. The Extension Manager will show the extension in a different category. So, categories are truly just hints for the user. They do not have any significant meaning in TYPO3. So, why do we care and talk about them? We do so because it is one of those things that make a good extension. If an extension developer starts making a new extension, they should do it properly from the very beginning. And one of the first things to do properly is to decide where an extension belongs. So, let's look into the various extension categories in more detail. Category: Frontend Extensions that belong to the Frontend category provide functionality related to the FE. It does not mean that they generate website output. Typically, extensions from the FE category extend FE functionality in other ways. For example, they can transform links from standard /index.php?id=12345 to /news/new-typo3-bookis-out.htm. Or, they can filter output and clean it up, compress, add or remove HTML comments, and so on. Often, these extensions use one or more hooks in the FE classes. For example, TSFE has hooks to process submitted data, or to post‑filter content (and many others). Examples of FE extensions are source_optimization and realurl. Category: Frontend plugins Frontend plugins is possibly the most popular extension category. Extensions from this category typically generate content for the website. They provide new content objects, or extend existing types of content objects. Typical examples of extensions from the Frontend plugins category are tt_news, comments, ratings, etc. Category: Backend Extensions from the Backend category provide additional functionality for TYPO3 Backend. Often, they are not seen inside TYPO3 BE, but they still do some work. Examples of such extensions are various debugging extensions (such as rlmp_ filedevlog) and extensions that add or change the pop-up menu in the BE (such as extra_page_cm_options system extension). This category is rarely used because extensions belonging to it are very special. Category: Backend module Extensions from this category provide additional modules for TYPO3 BE. Typical examples are system extensions such as beuser (provides Tools | Users module) or tstemplate (provides Web | Template module). Category: Services Services extend core TYPO3 functionality. Most known and most popular service extensions are authentication services. TYPO3 Extension Repository contains extensions to authenticate TYPO3 users over phpBB, vBulletine, or LDAP user databases. Services are somewhat special and will not be covered in this article. Extension developers who are interested in the development of services should consult appropriate documentation on the typo3.org website. Category: Examples Extensions from this category provide examples. There are not many, and are typically meant for beginners or for those who want to learn a specific feature of TYPO3, or features that another TYPO3 extension provides. Category: Templates Extensions from this category provide templates. Most often, they have preformatted HTML and CSS files in order to use them with the templateautoparser extension or map with TemplaVoila. Sometimes, they also contain TypoScript templates, for example, tmpl_andreas01 and tmpl_andreas09 extensions. Once installed, they provide pre‑mapped TemplaVoila templates for any website, making it easy to have a website up and running within minutes. Category: Documentation Documentation extensions provide TYPO3 documentation. Normally, TYPO3 extensions contain documentation within themselves, though sometimes, a document is too big to be shipped with extensions. In such cases, it is stored separately. There is an unofficial convention to start an extension key for such extensions with the doc_ prefix (that is, doc_indexed_search). Category: Miscellaneous Everything else that does not fit into any other category goes here; typical examples are skins. But do not put your extension here if you just cannot decide where it fits. In all probability, it should go into one of the other categories, not into Miscellaneous. Extension Files TYPO3 extensions consist of several files. Some of these files have predefined names, and serve a predefined purpose. Others provide code or data but also follow certain naming conventions. We will review all the predefined files in this article and see what purpose they serve. We will look into the files according to their logical grouping. While reading this section, you can take any extension from the typo3conf/ext/ directory at your TYPO3 installation and check the contents of each discussed file. Some files may be missing if the extension does not use them. There is only one file which is mandatory for any TYPO3 extension, ext_emconf.php. We will start examining files starting from this one. Common Files All files from this group have predefined names, and TYPO3 expects to find certain information in them. Hacking these files to serve another purpose or to have a different format usually results in incompatibility with other extensions or TYPO3 itself. While it may work in one installation, it may fail in others. So, avoid doing anything non-standard with these files. ext_emconf.php This is the only required file for any TYPO3 extension. And this is the only file that should be modified with great care. If it is corrupt, TYPO3 will not load any extension. This file contains information on the TYPO3 Extension Manager. This information tells the Extension Manager what the extension does, provides, requires, and conflicts with. It also contains a checksum for each file in the extension. This checksum is updated automatically when the extension is sent to TER (TYPO3 Extension Repository). The server administrator can easily check if anyone has hijacked the extension files by looking into the extension details in the Extension Manager. The modified files are shown in red. Here is a tip. If you (as an extension developer) send your own extension directly to the customer (bypassing TER upload), or plan to use it on your own server, always update the ext_emconf.php file using the Backup/Delete function of the Extension Manager. This will ensure that TYPO3 shows up-to-date data in the Extension Manager. Here is an example of a ext_emconf.php file from the smoothuploader extension: <?php ############################################################# # Extension Manager/Repository config file for ext: ↵ # "smoothuploader" # Auto generated 29-02-2008 12:36 # Manual updates: # Only the data in the array - anything else is removed by ↵ # next write. # "version" and "dependencies" must not be touched! ############################################################# $EM_CONF[$_EXTKEY] = array( 'title' => 'SmoothGallery Uploader', 'description' => 'Uploads images to SmoothGallery', 'category' => 'plugin', 'author' => 'Dmitry Dulepov [Netcreators]', 'author_email' => 'dmitry@typo3.org', 'shy' => '', 'dependencies' => 'rgsmoothgallery', 'conflicts' => '', 'priority' => '', 'module' => '', 'state' => 'beta', 'internal' => '', 'uploadfolder' => 0, 'createDirs' => '', 'modify_tables' => 'tx_rgsmoothgallery_image', 'clearCacheOnLoad' => 0, 'lockType' => '', 'author_company' => 'Netcreators BV', 'version' => '0.3.0', 'constraints' => array( 'depends' => array( 'rgsmoothgallery' => '1.1.1-', ), 'conflicts' => array( ), 'suggests' => array( ), ), '_md5_values_when_last_written' => 'a:12:{s:9:...;}', 'suggests' => array( ), ); ?> The variable _md5_values_when_last_written is shortened in the listing above.
Read more
  • 0
  • 0
  • 3221
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-creating-better-selling-experience-drupal-e-commerce
Packt
14 Oct 2009
5 min read
Save for later

Creating a Better Selling Experience with Drupal e-Commerce

Packt
14 Oct 2009
5 min read
Doug is an avid dinosaur and model enthusiast, and runs his own shop and museum selling model dinosaurs and offering information and facts on various dinosaurs. For the purpose of this article, we will create an e-commerce website named 'Doug's Dinos!' for Doug and his business. Making Things Easier Although Doug's store is relatively simple for his customers to use, it is missing three key features that would make their time on the website easier, these are: An overview of the shopping cart Search features Ability to auto-create user accounts At the moment, without a search feature the only way for users to find products is by manually browsing through the website and stumbling across a product they like. Adding a Shopping Cart We can add a shopping cart to our theme so that customers can continue browsing the website but still know how much is in their shopping cart, and easily get to it later. To add this block, we need to go to the Blocks section, which is under Site Building within the Administer area. Within the Blocks section, we need to ensure we have all our themes selected (or do this for each theme we are using) and then change the Region of the Shopping cart to the left sidebar. Once we click on the Save blocks button, the shopping cart block is displayed in our theme: Adding Search Capabilities Doug tested the website with a few friends and family members, and their main issue with it was the difficulty in finding products they wanted. The first thing we need to do is install the Search module, which is grouped under the Core - optional section of Modules in the Administer area. With the module installed, we now need to enable the Search feature from the Blocks section; otherwise the search box won't be displayed on the website. We can select this feature by going to Administer | Site Building | Blocks, then set it up in the same way as for the shopping cart and save the settings. We now have a search box on our website under the header but above the main menu! Let's try searching for one of our products, for instance T-Rex. Notice something? No results found! This seems quite strange as we have a product with T-Rex in the name, so why didn't we get any results? The reason for this is that Drupal has not yet been indexed. Drupal uses a cron job to create the index of the site. Without the indexing done Search options cannot work. The Search settings under Administer | Site configuration allow us to specify how many pages are indexed per "cron run" and allow us to set the site to be re-indexed. Cron JobsA cron job is a setting on your web host's server (if you have cPanel hosting, it is available under "crontab") that performs tasks at specific times. Drupal has a special page that performs various tasks; this can be called by a cron job so that it regularly opens the page and runs the tasks. This setting depends on having set up a cron job to periodically call the cron.php file. For more information on setting up cron jobs, you should contact your web host. Typically it involves a crontab setting in your hosting control panel such as cPanel. We can manually run the cron task, by opening the cron.php file in our web browser. In this case we just open: http://www.dougsdinos.com/cron.php. Once we have opened this page, let's try searching for T-Rex again. This time we will get some results! Customers will now be able to find products and other content on Doug's website much more easily! Auto-Creating User Accounts If a customer is not a user on our site, we can automatically create a user account for them once they have placed their order; this saves the inconvenience of using an anonymous purchase policy where the user has to log in or register, but it gives the user the added convenience of having their details saved for future orders. This is something Doug wants to enable to make things easier for regular customers on this site. The first thing we need to do is install the module. The module is called EC Useracc and is listed in the E-Commerce Uncategorized group of modules. Now under E-Commerce configuration we have a new option called User Account; let's take a look at it. This has the following settings: Confirmation e-mail Welcome mail Days to confirm expiry The Confirmation e-mail is to see if the customer wants to create a user account; this email expires after the number of days set in the Days to confirmation expiry setting has passed, and the Welcome mail is the email sent when the account is created. These emails can be configured on the Mail page. These settings don't actually enable the feature though; we have installed the module and looked at the global settings, but to actually get it to work we need to set how we would like each product to work in relation to this module. If we go to edit any product, there is a new section, which was not there previously, called User account provision; this is what we need to change. As Doug wants this feature enabled, we need to check the option Create an account for the user when this product is purchased. The other option, Block the user's account when this product expires, relates to using recurring billing in products (mainly non-tangible products i.e. services) such as a customer support contract or a magazine subscription.
Read more
  • 0
  • 0
  • 1455

article-image-enhancing-user-experience-wordpress-27part-1
Packt
14 Oct 2009
6 min read
Save for later

Enhancing User Experience with WordPress 2.7(Part 1)

Packt
14 Oct 2009
6 min read
As a blogger, I read loads of blog posts every day, on many different blogs. Very often, I'm scared to see how many blogs have a non user-friendly interface. How often does it happen that you can't click on the logo to go back to the blog homepage, or can't find what you're looking for by using the search engine? It is a well known fact that in blogging the content is king, but a nice, user friendly interface makes your blog look a lot more professional, and much easier to navigate. In this article, I'll show you what can be done for enhancing user experience and making your blog a better place. Replacing the Next and Previous links by a paginator When a web site, or blog, publishes lots of articles on a single page, the list can quickly become very long and hard to read. To solve this problem, paginations were created. Pagination allows displaying 10 articles (for example) on a page. If the user wants, then he or she can go to the next page, or click on a page number to directly go to the related page. I definitely don't understand why WordPress still doesn't have a built-in pagination system. Instead, at the bottom of each page you'll find a Next link to go to the next page, and a Previous link to go back. This works fine when you're on page two and would like to go to page three, but what if you're on page one, and remember a very interesting article which was located on page eight? Are you going to browse page per page until you find your article? The answer is yes, because you don't have the choice. You can't jump from page one to page eight. In this recipe, I'll show you how to integrate a pagination plugin in your WordPress blog theme. One very good point of this recipe is that the plugin file is embedded in your theme, so if you're a theme designer, you can distribute a theme which has a built-in pagination system. Getting ready To execute this recipe you need to grab a copy of the WP-PageNavi plugin, which can be found at http://wordpress.org/extend/plugins/wp-pagenavi/. I have used version 2.40 of the Wp-PageNavi plugin in this example. Once you have downloaded it, unzip the zip file but don't install the plugin yet. How to do it Open the WP-PageNavi directory and copy the following files into your WordPress theme directory (For example, http://www.yourblog.com/wp-content/ theme/yourtheme). wp-pagenavi.php wp-pagenavi.css Once done, edit the index.php file. You can do the same with other files, such as categories.php or search.php as well. Find the following code (or similar) in your index.php file: <div class="navigation"> <div class="alignleft"><?php next_posts_link('Previous entries') ?></div> <div class="alignright"><?php previous_posts_link('Next entries') ?></div></div> Replace that with the following code: <?php include('wp-pagenavi.php'); if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?> Save the index.php file. If you visit your blog now, you'll see that nothing has changed. This is because we have to call a function in the wp-pagenavi.php file. Open this file and find the following code (line 61): function wp_pagenavi($before = '', $after = '') {global $wpdb, $wp_query; We have to call the pagenavi_init() function, so let's do this in the following way: function wp_pagenavi($before = '', $after = '') {global $wpdb, $wp_query;pagenavi_init(); //Calling the pagenavi_init() function Now, save the file and refresh your blog. The pagination is now displayed! This is great news, but the pagination doesn't look good. To solve this problem, you simply have to integrate the wp-pagenavi.css file that you copied earlier in your theme directory. To do so, open the header.php file from your theme and paste the following line between the <head> and </head> tags: <link rel="stylesheet" href="<?php echo TEMPLATEPATH.'/pagenavi. css';?>" type="text/css" media="screen" /> Visit your blog homepage one more time. The pagination looks a lot better. You may have to edit the wp-pagenavi.css file in order to make your pagination look and feel ft your blog style. How it works In this recipe, you have discovered a very useful technique that I often use on my blogs, or in the themes that I distribute—the integration of a WordPress plugin into a theme. When the plugin is integrated into your theme as I have shown you in this example, there's no activation process needed. All of the work is done directly from the theme. The WP-PageNavi plugin itself works by using two values—the number of posts to be displayed per page and the first post to be displayed. Then, it executes the relevant query to WordPress database to get the posts. The pagination bar is calculated by using the total number of posts from your blog, and then dividing this value by the number of posts per page. One good point of this technique is that the plugin is integrated in your blog and you can redistribute the theme if you want. The end user will not have to install or configure anything. Highlighting searched text in search results I must admit that I'm not a big fan of the WordPress built-in search engine. One of its weakest features is the fact that searched text aren't highlighted in the results, so the visitor is unable to see the searched text in the context of your article. Getting ready Luckily, there's a nice hack using regular expressions to automatically highlight searched text in search results. This code has been created by Joost de Valk who blogs at www.yoast.com. How to do it This useful code is definitely easy to use on your own blog: Open your search.php file and find the following: echo $title; Replace it with the following code: <?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt"></strong>',$title);?> Save the search.php file and open the style.css file. Append the following line to it: strong.search-excerpt { background: yellow; } You're done. Now, the searched text will be highlighted in your search results. How it works This code is using PHP regular expressions to find the searched terms in the text returned by WordPress. When an occurrence has been found, it is wrapped in a <strong> HTML element. Then, I simply used CSS to define a yellow background to this element.
Read more
  • 0
  • 0
  • 1920

article-image-creating-your-first-web-page-using-expressionengine-part-2
Packt
14 Oct 2009
7 min read
Save for later

Creating Your First Web Page Using ExpressionEngine: Part 2

Packt
14 Oct 2009
7 min read
Viewing Our First Entry Now one question remains: where do we have to go to see our entry? The answer is that our entry is not yet on our website. That is because the entry does not appear in a template and everything on an ExpressionEngine website must go into a template before it can be viewed. Follow these instructions to point a template to our new weblog. Click on Templates in the menu bar. Select Create a New Template Group, and call the New Template Group to be news. Leave all the other options at their default and click Submit. Select the news template group, and then click on the index template to edit it. To include a weblog in a template, we use a tag. A tag is a unique ExpressionEngine piece of code that is used in templates to include extra functionality. In this case, we want to include a weblog, so we need a weblog tag. A tag has two parts: variables and parameters. Parameters are always part of the opening tag whereas variables are used between the opening tag and the closing tag. In the news/index template we will add in the weblog tag as well as some standard HTML code. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html > <head> <title>News from the President</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head> <body> <h1>Toast for Sale!</h1> <h2>News from the President</h2> {exp:weblog:entries weblog="toastnews"} <h3>{title}</h3> {summary} {body} {extended} {/exp:weblog:entries} </body> </html> The indentation helps to demarcate related sections and therefore make the code more readable, but is certainly not required. Click Update and Finished to save our updates. The difference between Update and Update and Finished is that Update will keep you in the template editing screen so that you can continue to make further edits, whereas Update and Finished returns you to the main templates screen. Now view the news template at http://localhost/news or www.example.com/news to see how it looks. It should look like the following screenshot. Notice how the {title} has been changed to reflect the actual title of our entry (and so has {summary} and {body}). What happens if we post two entries? Let us try it and see! Back in the control panel, select Publish | Toast News and write a second entry with a different title, URL title, and so forth. Hit Submit, and then visit http://localhost/news or http://www.example.com/news to see what happens. It should look like as follows: For our final enhancement, let us edit the template to include variables for the author name and the date of the entry. To do this, add the highlighted code as shown next: <body> <h1>Toast for Sale!</h1> <h2>News from the President</h2> {exp:weblog:entries weblog="toastnews"} <h3>{title}</h3> {summary} {body} {extended} <p class="footnote">Written by {author} on {entry_date format="%F %j%S"}</p> {/exp:weblog:entries} </body> {author} is a variable that returns the name of the person who was logged in when the entry was created. {entry_date} is a variable that displays the date that the entry was written on. format is a parameter of the entry_date variable that is used to specify how the date should be formatted. %F is the month of the year spelled out; %j is the day of the month; and %S is the suffix (for example, nd or th). So %F %j%S is rendered as 'February 7th'. For a complete list of date formats, visit http://expressionengine.com/docs/templates/ date_variable_formatting.html.   Revisit http://localhost/news or http://www.example.com/news, and you can now see the author name underneath both entries. Make Our Weblog Pretty Using CSS Our weblog, whilst functional, is not exactly the prettiest on the web. We will spruce it up with some more HTML and CSS. This section will not introduce any new ExpressionEngine features but will demonstrate how to incorporate standard CSS into our templates. An understanding of HTML and CSS will be invaluable as we develop our ExpressionEngine site. Please note that this article can only demonstrate the basics of using HTML with CSS in an ExpressionEngine website. If you are already familiar with using HTML and CSS, then you will only need to go through the section in the first part (Creating and Linking to a Styling Template) to create the CSS template and link to it from the HTML template. Creating and Linking to a Styling Template As with a more conventional HTML/CSS website, our CSS code will be separated out from our HTML code, and placed in its own template (or file). This requires creating a new CSS template and modifying our existing template to identify the main styling elements, as well as to link to the CSS template. First, let us go back into our news template and add the following code (highlighted). The trick with writing HTML with CSS is to identify the main sections of the HTML code using the <div> tag. <body> <div id="header"> <h1>Toast for Sale!</h1> <h2>News from the President</h2> </div> <div id="content"> {exp:weblog:entries weblog="toastnews"} <h3>{title}</h3> <div class="contentinner"> {summary} {body} {extended} </div> <p class="footnote">Written by {author} on {entry_date format="%F %j%S"}</p> {/exp:weblog:entries} </div> </body> Here we have identified three sections using the <div> tag. We have encapsulated our website title in a header section. We have wrapped up all of our ExpressionEngine entries into a content section. Finally, we have created a contentinner section that contains just the text for each ExpressionEngine entry, but does not include the title. Also note that footnote is a section. What is the difference between an id and a class in our <div> tags? A section defined with an id only appears once on a page. In our case, the header only appears once, so we can use the id. A section defined with a class may appear multiple times. As the contentinner section will appear on the page for each entry present there, we have used a class for this section. Next, we want to create a CSS template that tells us what to do with these sections. To do this, go back to the main Templates page, select the toast template group, and then select New Template. Call the new template toast_css. Under Template Type select CSS Stylesheet instead of Web Page. Leave the Default Template Data as None – create an empty template and hit Submit. Before we start editing our new CSS template, we must be sure to tell the HTML template about it. Select to edit the index template in the news template group. Insert the following highlighted commands between the <head> and </head> tags to tell the HTML template where the CSS template is. <head> <title>News from the President</title> <link rel='stylesheet' type='text/css' media='all' href='{path=toast/toast_css}' /> <style type='text/css' media='screen'>@import "{path=toast/toast_css}";</style> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head>
Read more
  • 0
  • 0
  • 2062

article-image-creating-your-first-web-page-using-expressionengine-part-1
Packt
14 Oct 2009
8 min read
Save for later

Creating Your First Web Page Using ExpressionEngine: Part 1

Packt
14 Oct 2009
8 min read
Toast for Sale! To demonstrate the power of ExpressionEngine, we are going to use a fictitious business as an example throughout this article. Our website is in the business of selling toast (heated bread with melted butter) online. With this example, we will be able to explore many of the nuances of building a complete website with ExpressionEngine. Though unlikely that we would really want to sell toast over the internet, the concepts of our example should be transferable to any website. In this article, we want to introduce the world to our business, so we are going to create a 'News from the President' webpage. This will allow the President of our company to communicate to customers and investors the latest goings-on in his business. Inside the Control Panel When you first log into the control panel, there are lots of options. Let us take a quick tour of the control panel. First, we will need to log into ExpressionEngine. If you are using XAMPP to follow along with this article, go to http://localhost/admin.php or http://localhost/system/index.php to log in. It is assumed that you are using XAMPP with http://localhost/ addresses. If you are following along on an actual website, substitute http://localhost/ for your website domain (for example, http://www.example.com/). It is required to move the login page to the root of our website to mask the location of our system directory The first page we see is the CP Home. We can return to this page anytime by selecting CP Home from the menu at the top-right of the screen, above the main menu. In the left column, we have EllisLab News Feed. Below, we have Most Recent Weblog Entries as well as any Recent Comments or trackbacks visitors may have left. In our case, our site is brand new, so there will be no recent comments or trackbacks, and only 1 recent weblog entry (Getting Started with ExpressionEngine). Clicking on the link will take you directly to that entry. On the right, there is a Bulletin Board (a way for you to pass messages to other members of your control panel), the Site Statistics and a Notepad (we can write anything here, and it will be available every time we log-in). Across the top is the main menu bar, and at the top-right are links to your website (My Site), this page (CP Home), the ExpressionEngine user-guide (User Guide), and to log-out (Log-out). The Publish and Edit links in the main menu bar are where you can create new entries and edit existing entries. The Templates link is where we can create new templates and edit existing templates. We will spend most of our time in these sections. The Communicate tab is where we can manage bulk-emails to our website members. At this time we do not have any members to email (other than ourselves), but as our site grows larger, this feature can be a useful communication/marketing tool. Be careful to avoid sending unsolicited bulk emails (or spam) using this feature. In many countries, there are laws governing what can or cannot be done. In the United States, commercial emails must meet very specific guidelines set by the Federal Trade Commission (http://www.ftc.gov/spam/). The Modules tab is where we can manage all the modules that come with ExpressionEngine, as well as optional third-party modules that we may wish to install. We can download additional modules from http://expressionengine.com/downloads/addons/category/modules/. The My Account tab is where we can edit our login preferences, including our username and password. We can also edit the look and feel of the control panel home page from this screen, as well as send private messages to other members. Much of this page is irrelevant when we are the only member of the site (as we are right now). The Admin tab is where most of the configuration of ExpressionEngine takes place, and we will spend a lot of time here. By default, most of the ExpressionEngine settings are already properly set, but feel free to browse and explore all the options that are available. Full documentation on each of the options is available at http://expressionengine.com/docs/cp/admin/index.html. This concludes our brief tour of ExpressionEngine. Now we are going to delve into one of the most important parts of the control panel—templates. Templates and URLs The basic concept in ExpressionEngine is that of a template. Go to any ExpressionEngine-powered website and you will undoubtedly be looking at a template. Templates are what the outside world sees. At its most basic, a template in ExpressionEngine is a HTML (or CSS or JavaScript) file. If we wanted to, we could use a template exactly like a HTML file, without any problems. We could create an entire website without ever using any other part of ExpressionEngine. However, we can take templates a lot further than that. By using ExpressionEngine tags inside our templates, we can take advantage of all the features of ExpressionEngine and combine it with all the flexibility that HTML and CSS offers in terms of layout and design. We are not limited to pre-defined 'cookie-cutter' templates that have been carefully adapted to work with ExpressionEngine. This is why ExpressionEngine is very popular with website designers. On the flip side, this is also why there is such a learning curve with ExpressionEngine. There is no point-and-click interface to change the look and feel of your website; you have to have some experience with HTML to get the most out of it. Let us take a closer look at templates and how they relate to URLs: If you are not already logged in, log into ExpressionEngine at either http://localhost/admin.php or http://www.example.com/admin.php. Click on the Templates button on the top of the screen. Templates are stored in groups. There is no 'right' way to group templates—some sites have all their templates in a single group and other sites have lots of template groups. We are going to create a new template group for each section of our website. ExpressionEngine does come pre-installed with two template groups: the site template group and the search template group. As a new user, it is best not to delete these template groups in case you want to refer to them later. In the next screen we can give our template group a name; let us use toast. There is an option to Duplicate an Existing Template Group which copies all the templates from one template group into our new template group. This can be useful if we are creating one template group that will work very similarly to the one that we already created, but as this is our first template group, we are going to start from scratch. Checking the box Make the index template in this group your site's home page? means that visitors will see the toast website in place of the ExpressionEngine example site. If you are using the XAMPP test server, go ahead and check this box. Hit Submit to create the template group. We will be returned to the Template Management screen. A message will appear saying Template Group Created, and the new template will appear in the box of groups on the left-hand side. Left-click on the New Template group in the Choose Group box on the left-hand side. Each template group comes with an initial template, called index. Remembering that a template is like an HTML file, a template group is like a directory on our server. The index template is the equivalent of the index.html file—when a visitor visits our template group, the index template is displayed first. For that reason, the index template cannot be renamed or deleted. Let us edit the index template to see what it does. Click on the word index. A template is essentially just text (although it usually contains HTML, CSS, or ExpressionEngine code). When we first create a template, there is no text, and therefore all we see is an empty white box. Let us write something in the box to demonstrate how templates are seen by visitors. Type in a sentence and click Update and Finished. Just like HTML files and directories, templates and template groups relate directly to the URL that visitors see. In the URL http://www.example.com/index.php/toast/index, the index.php is what distinguishes this as an ExpressionEngine page. Then comes the template group name, in our case called toast. Finally, we have the template name, in this case index. Go to the previous URL (with or without the index.php as appropriate, for example, http://www.example.com/toast/index or http://localhost/toast/index) and the template we just edited should appear. Now try typing the template group without specifying which template to load. The index template is always returned. What happens if we do not specify the template group, and just go to our base domain (http://localhost/ or http://www.example.com/)? In this case, the toast template of the default template group is returned. The default template group is indicated on the templates screen with an * before the template group name and underneath the list of template groups.
Read more
  • 0
  • 0
  • 4529
article-image-show-additional-information-users-and-visitors-your-plone-site
Packt
12 Oct 2009
5 min read
Save for later

Show Additional Information to Users and Visitors of Your Plone Site

Packt
12 Oct 2009
5 min read
(For more resources on Plone, see here.) What's a portlet, anyway? A portlet is a chunk of information that can be shown outside of the main content area of a page. In the following screenshot of Plone's default home page, the Log in box and the calendar are portlets. Plone's default theme has two portlet managers that control the assignment of portlets on the right and left sidebars of the page. You can place portlets into these slots on the page. It's also possible to add portlet manager slots to a custom theme so that you can display portlets in other areas of the page, but that's beyond the scope of this book. For more information, refer to: http://plone.org/documentation/how-to/adding-portlet-managers. There are two things that we need to know about portlets before we dive into adding them: Portlets can only be added to portlet managers. They can't be added into the body content of your pages. Portlets can be assigned to folders, content types, or user groups, and will cascade down through the site hierarchy unless you explicitly block inheritance. Plone's built-in portlets Plone ships with a generous assortment of basic portlets. Here's a quick list of Plone's default portlet offerings: Login: Shows Plone's login box to anonymous users; is hidden if a user is already logged in Collection portlet: Shows the results of a Collection Review list: Visible only to the users with the Reviewer role; this portlet shows a list of items that users have submitted for review before publishing RSS feed: Shows a list of items in an RSS feed Classic portlet: A wrapper for Zope 2 style portlets, which may have been developed prior to the advent of Plone 3 and its new portlet system Calendar portlet: Shows a simple calendar that highlights the dates of upcoming events for your site Search: Shows Plone's search box useful if you have chosen to disable the standard search box, and want to show it in a sidebar instead Recent items: Shows the most recently-published content items on your site Static text portlet: Shows a chunk of static, editable HTML content; this is one of Plone's most versatile and useful portlets Navigation: Shows the navigation tree Events: Shows upcoming published events on your site You're likely only to use Classic portlets if you are using an add-on product that hasn't fully embraced the new style of building portlets, or if you are building your own custom portlets. Add-on portlets Many add-on products for Plone will supply one or more relevant portlets when the product is installed. There are also additional standalone portlets available as separate add-on products. Among the most useful standalone add-on portlets are: TAL Portlet: A portlet that allows you to write your own simple portlets in Plone's templating language, TAL. Optionally, you could just write a Classic portlet. Feedmixer: A portlet that allows you to aggregate multiple RSS feeds into a single portlet. These products can be found in the Products section of Plone.org. Adding portlets There are three ways to add portlets to your site: Add portlets to specific locations on your site. Add portlets that are associated with specific content types—for example, a portlet that shows on all News Items. Add portlets that are shown only to specific groups of users in your site. Adding portlets to specific sections of your site We'll start with adding portlets to a specific section of your site, as this is the most common and the simplest thing to do. Log in to your site (via the Log in portlet) and look at the bottom of the rightmost sidebar for the Manage portlets link. This will take you to the Manage portlets screen. Managing Portlets PeacefullyBecause you were on the front page of your site, when you clicked on the Manage portlets link, you are now managing the portlets for your entire site. If you only want to manage portlets for a single section of your site, first navigate to that section, and then click on the Manage portlets link. The header of the Manage Portlets screen will tell you which section of the site you are in. The Manage Portlets screen tells you that certain portlets are already assigned to all of the pages of your site. In the example above, the left sidebar portlet manager has the Navigation portlet and the Log in portlet. The right sidebar portlet manager has the Review List, News, Events and Calendar portlets. Moving and Removing PortletsYou can move existing portlets around within a portlet manager by clicking on the up and down arrows within the portlet. You can remove a portlet from the portlet manager by clicking on the red X. To add a portlet to your site, select the Add portlet... drop-down menu at the top of either the right or left sidebar, and choose a portlet type to be added. For practice, let's try adding a static content portlet to the right sidebar. This screen contains the familiar Kupu-powered rich text editing widget, along with: A Portlet header (title) field. A Portlet footer field. A optional hyperlink field, which will be clickable from the portlet header and footer. An Omit portlet border checkbox. If selected, this hides the portlet header, footer, and border. This is very useful if you only want to place an image or some fl oating text in your sidebar. Enter some text into your new portlet, click on the Save button at the bottom of the screen, and then click on the Home tab to return to your site's homepage. You should now see your new static text portlet. If you click around the site, you'll continue to see the portlet on all of the pages of your site.
Read more
  • 0
  • 0
  • 6331

article-image-social-bookmarking-blogger-part-2
Packt
12 Oct 2009
6 min read
Save for later

Social Bookmarking in Blogger: Part 2

Packt
12 Oct 2009
6 min read
Adding buttons gives the site a more homemade feel, but it is time consuming to hunt down the links to the different services on the social networking sites. Wouldn't it be great if there was a third-party service out there that did the gathering for you? AddThis (http://www.addthis.com) offers a multi-bookmark widget popular with many bloggers. Offering Multiple Bookmarks with One Button Using a widget like the one offered by AddThis frees you to spend your time blogging. You can choose to show all the main bookmark networks or pick and choose from an extensive list. We'll configure the widget and then install it on our blog. Time for Action!—Offering Multiple Bookmarks with AddThis Register at the AddThis (http://www.addthis.com) site. Georgia has already created an account for Fruit for All. The AddThis Social Widget Builder screen has multiple options to customize the widget code. Choose the Bookmarking widget option from the Which kind of widget? drop-down box. Select the style of bookmark button you want to use. We will choose the second one. The on a Blog option should be selected for Where? Choose Blogger for the Blogging Platform and then click Get Your Free Button>> for the code. Next, AddThis will provide you with the code. Copy the code from the site or type the code below in place of the button links, above the <p class='post-footer-line post-footer-line-2'> tag in the template code: <!-- AddThis Bookmark Post Dropdown BEGIN --> <div> <script type='text/javascript'>addthis_url='<data:post.url/>'; addthis_title='<data:post.title/>'; addthis_pub='fruitforall';</script> <script src='http://s7.addthis.com/js/addthis_widget.php?v=12' type='text/javascript'></script> </div> <!-- AddThis Bookmark Post Dropdown END --> Save the template changes and view the blog. Try hovering the cursor over the Bookmark button to see whether the list of bookmarks appears. The button looks great. We need to test an icon to see how AddThis submits posts. Click the Del.icio.us icon to bring up the submission window. The URL, description (title), and tags were auto populated for us. Taking a note of the recommended tags will help us label future posts, and will guide us in adding more labels to the current post. What Just Happened? The AddThis button replaced our group of social bookmark buttons. When the visitor hovers their cursor over the button, a list of social bookmark icons appear. The visitor also has the option to choose from social bookmarks not listed in the main group. A new window opens with a submission form for the service we selected. After the form is filled out, AddThis collects statistical data for us and displays it graphically on our AddThis account page. The icons displayed on the button can be changed on the AddThis site. You can't predict which bookmarks your visitors use. Using a multiple bookmark aggregator such as AddThis keeps your posts free of bookmark clutter while giving visitors more bookmarking choices. There are other options as well. ShareThis (http://www.sharethis.com) has recently released the latest version of its multiple bookmark service, which includes tracking. It is available at http://sharethis.com/publisher/. Adding Dynamic Counters to Bookmark Links Showing counters on social bookmark icons is becoming popular. Dynamic counters are offered by bookmark services Reddit, Del.icio.us, Ma.gnolia, and Digg. Bookmark services are adding their own counters every day. Readers can quickly see if a post has already been submitted to a service and can vote to increase or decrease the popularity of the post while still at the blog. We will add the popular del.icio.us dynamic bookmark and examine the features it offers. We will then explore and then explore using Feedburner Flare (http://www.feedburner.com) to show multiple counters easily. Time for Action!—Adding Dynamic Links with Counters to Posts Navigate to the Edit HTML screen on the blog, and click the Expand Widget Templates checkbox. Type the following block of code directly above the <p class='post-footer-line post-footer-line-2'> tag in the template code, deleting any existing social bookmark code we added before: <script type="text/javascript">if (typeof window.Delicious == "undefined") window.Delicious = {}; Delicious.BLOGBADGE_DEFAULT_CLASS = 'delicious- blogbadge-line';</script> <script src="http://images.del.icio.us/static/js/ blogbadge.js"></script> Save the template, and view the blog to see the changes. An example of how it should look now is shown in the following screenshot: Are there any differences between the information captured using this bookmark and others? Let's test the bookmark and find it out. Click on bookmark this on the del.icio.us button and review the results: The bookmark does not display the actual post title and post URL. We will need to customize it to display that information when the reader submits the post. What Just Happened? We inserted a ready made counter bookmark script from the del.icio.us site into our template code. The first JavaScript code snippet will check to see if a link to del.icio.us already exists. If it does not, a special default CSS class is set to control the appearance of the badge. The code is shown for reference below: <script type="text/javascript">if (typeof window.Delicious == "undefined") window.Delicious = {}; Delicious.BLOGBADGE_DEFAULT_CLASS = 'delicious-blogbadge-line';</script> Calling the code controlling the badge counter is done with the final script tag. It links to an external JavaScript file stored at the del.icio.us site. <script src="http://images.del.icio.us/static/js/blogbadge.js"> </script> The script counts how many times readers have recommended the blog site to del.icio.us using their own script counter. The number shown will increase each time the site is bookmarked by someone on del.icio.us.
Read more
  • 0
  • 0
  • 2397

article-image-social-bookmarking-blogger-part-1
Packt
12 Oct 2009
7 min read
Save for later

Social Bookmarking in Blogger: Part 1

Packt
12 Oct 2009
7 min read
The features of social bookmarking sites are in constant evolution. Currently they can be broadly categorized into three types: User generated news: The main goal is to increase visits by getting on the front page of a site like Digg or Reddit. This will increase traffic to a site by huge amounts for anywhere from a few minutes to a day. Sites unprepared for the avalanche of hits often choke on the visitor overload. This is commonly known as the Slashdot effect (http://www.slashdot.org); a popular technologies site whose readers have broken many a site under the crush of their visits. Circle of friends sharing: When posting to Facebook (http://www.facebook.com), Twitter (http://www.twitter.com), Flickr (http://flickr.com), or a blog, the user knows that the main purpose of these sites is sharing content with friends and people. When a user shares a link with a friend, a slight increase in traffic may occur (unless the user is a "celebrity" blogger with thousands of followers). Focusing on such groups would be more effective for smaller blogs. Online bookmarks: Readers use these sites to manage their bookmarks online. Links can be public, and may even serve the public interest, such as "How To". Most people see these sites as a welcome alternative to trying to export or duplicate bookmarks across multiple browsers or computers. Adding links to these sites will increase the chance of first time readers becoming regulars. Examples include del.icio.us (http://del.icio.us), Furl (http://www.furl.net), and Ma.gnolia (http://ma.gnolia.com). How Social Bookmarking Works Social bookmarking works because people share information they find online with each other. The different features that social bookmark services such as online bookmarks, categories, and rss feeds provide make it easier for people to find sites that interest them in new and sometimes unpredictable ways. People are connected to each other through these services, forming social and interacting networks, helping others find information, and spreading the word about sites they enjoy. Submitting Posts without Bookmarks Bookmarks are convenient for readers and bloggers. Submitting articles and posts manually is extra time and work for a reader. Making it easier for them by linking the post title and URL automatically encourages readers to submit posts spontaneously. Let's recommend a site to Reddit (http://www.reddit.com) without using bookmarks. Reddit is a popular online bookmark and user-generated news service. Time for Action!—Become a "Bookmarker" Navigate to http://www.reddit.com and click the submit link at the top of the screen. You will be redirected to the register or login screen. A username and password are all that is needed. Enter a username into the username box. You can enter an email address such as fruitforall@gmail.com into the email text field. Type a password into the password box and again into the verify password box. You can choose to have the site remember your login for you by clicking on the remember me checkbox. After reviewing the privacy policy and user agreement pages, place a check in the box next to I understand…. Click on the create account button after the form has been filled out as shown in the following screenshot: Find an interesting article to submit. We will submit the latest post on the (http://cookingwithamy.blogspot.com) blog. An example of the post being submitted is shown in the following screenshot. Copy the URL and the title of the post into a text editor such as Notepad (Windows) or Textpad (Mac). Log in to Reddit and click the submit link. Enter all the data manually, as shown in the following screenshot. Click the submit button. The link has now been shared. What Just Happened? It took three steps to add one link to Reddit. That did not include the time spent finding the site we wanted to submit. Then we had to log in to the bookmarking service and go to the submit form. We had to copy all the submission information ourselves and then enter it all manually into the bookmarking site form. The URL had to be entered correctly. If we had made a mistake while typing, the process would have taken longer and been more frustrating. It took a minute or two instead of the few seconds a bookmark would take. Now let's see how social bookmarks are a useful addition to our blog. They save the readers' time and make it more likely that new readers will impulse bookmark. Sharing Posts by Email A common way for visitors to share posts and articles they like is to email them to other people. Blogger has an Email Post to a Friend feature. Using features that make sharing posts more convenient for visitors will increase the exposure of your blog. This is a small subset of a type of marketing known as viral marketing, where readers spread your message for you from one person to another. "How hard is it to turn on this feature?" asks Georgia as she navigates the blog. "I'd like to try it. Then my readers will have an easy way to share my posts!" Time for Action!—Turn On Email Posting Log in to the blog, click the Settings link, and navigate to the Basic sub tab link. Scroll down the list to Show Email Post links? and select Yes from the drop‑down list as shown in the following screenshot: Click on Save Settings. Now it's time to test the feature. View the blog and click on the small email icon below the post. The Email Post to a Friend screen will appear. The sender will need to enter his name and email address and the email address of the person he wants to send the post to. The Message box, which is not a required field, can contain any notes from the sender. A sample of the post content is displayed at the bottom of the screen. Click the Send Email button to send the message. An email will be sent to the address fruitforall@gmail.com, and a success screen is displayed with a link back to the blog, as shown in the following screenshot: The submitter will be able to return to the blog using the link under Return to where you were on the confirmation screen. What Just Happened? When you logged into the blog and turned on the email post links feature, The Email post link setting in the blogger template was set to "show". The icon for the Email-Post-To-A-Friend feature was then visible under each blog post. Clicking on the icon brought up a new screen with a form that prompted the submitters to enter the email information for themselves and their friends. The code displayed the post at the bottom of the screen, automatically. The friend is then sent an email with a link to the post. Adding Bookmarks to Blogs Social bookmarks can be displayed on blogs as text links, buttons, or as dynamic mini‑widgets showing the number of submissions. Adding bookmarks to blogs is a task that ranges from simple cut and paste to custom coding. We will first choose the social bookmarks and then explore several different techniques to add them to our blog. Choosing the Right Bookmarks for Your Blog Blogs that focus on specific topics or points of views stand out from thousands of other blogs and attract a more regular following. The social bookmarks you choose should fit the subject and tone of your blog. A technology blog would most likely have bookmarks to Digg (http://www.digg.com), Slashdot (http://www.slashdot.org), and Reddit (http://www.reddit.com). "There are so many social bookmarking services out there," says Georgia. "How do I pick the ones that are right for my blog?" Earlier, we had defined three broad types of social bookmark systems. You could just choose whatever bookmark sites you see your friends using. But you're smarter than that. You are on a mission to make sure your blog post links will show up where readers interested in your topic congregate. Listed below are the most popular and useful social bookmark systems and networks.
Read more
  • 0
  • 0
  • 4074
article-image-blog-cms
Packt
12 Oct 2009
10 min read
Save for later

Blog CMS

Packt
12 Oct 2009
10 min read
Let's get started right away. The first question-do I need a self-hosted or service-based CMS? Blogs have taken the Internet by storm. They started like simple diaries and have grown to be full-fledged CMSs now. If you want to start a blog, you have the following two options: Sign up with a hosted blog service such as WordPress.com, Typepad.com, Blogger.com, or any other similar services available Set up blogging software, such as WordPress, Movable Type, ExpressionEngine, and so on, on your own server If you are a casual blogger, signing up with a hosted service is a suitable choice. But if you want full control of your blog, setting up your own system is the best option. It's not very difficult—you could do it within five minutes. We will cover only self-hosted solutions for this article. But you can easily apply this knowledge to a blog service. Top blogging CMSs  WordPress (www.WordPress.org) is the most popular self-hosted blogging software. Hundreds of thousands of sites run on WordPress, and tens of millions of people see WordPress-driven content every day. The following images are of the PlayStation ( http://blog.us.playstation.com/ ) and the People ( http://offtherack.people.com/ ) blog sites, which use WordPress: Movable Type (www.movabletype.org) is another longtime favorite. It's very easy to use and has a strong fan following. There are many contenders after the top two blogging CMSs. All general-purpose CMSs have a blogging component. Many old blog software applications are no longer actively maintained. There are new entrants on the scene that focus on niches, such as photo blogging. Let us cover the top choices We can't cover all of the blog software in this article. So, we will only cover WordPress at length. We will talk about Movable Type and ExpressionEngine briefly. At the end, we will touch upon other blogging software. What we are interested in is to find out answers to the following questions: What sort of a site is that CMS good for? How easy is it to build a site? How easy is it to edit content? What's its plug-in/template support like? How extensible/customizable is it? What are the interesting or high-profile examples of that CMS? Taking WordPress for a test drive Let's try creating a site structure, adding and editing content, applying design templates, and making a few customizations with WordPress to see how it performs. Time for action-managing content with WordPress Log in to the administration panel of your WordPress installation. Click on the New Post link in the top bar. This opens the Add New Post page.Enter a title for your first blog post where your cursor is blinking. We will enter definition of the word Yoga for our Yoga Site. Start writing your text in the large text entry box. It's a WYSIWYG editor. You can use buttons in the toolbar to format text, insert links, and so on. Let's insert an image into our post. Click on the first icon next to Upload/Insert. When you move your mouse over it, you will see Add an Image in the tooltip. Click on that icon. Upload a file from your computer. Once a file is uploaded, you can enter additional parameters for this image. This includes Title, Caption, Alignment, a link to open when an image is clicked, and so on. Here's how your screen may look at this stage. Click on Insert into Post to add this image to your post. Complete writing the blog entry. If you want to add tags (keywords) to this post, you can do that from the Tagssection at right. WordPress will autocomplete long tags and will create newones as you Add them. We have not yet created any categories for our blog. Navigate to the Categories section below Tags. Click on the + Add New Category link. Enter Background as your category name and Add it. Any new categories youadd are selected automatically. Notice that you can post a blog entry in multiplecategories at once. There are a few other options too. There are the settings for Discussion. We want to allow both comments and trackbacks, so keep both options checked. Scroll up and click on the Publish button on the right to make this post live. Click on View Post at the top left to see how your site looks at the moment. What just happened? We published a new blog post with WordPress! This was the first time we used WordPress, but we could accomplish everything we needed to post this entry just from one screen. This is an important thing. Many CMSs require that you set up categories and images separately. This means you have to know the system before you can use it! WordPress allows you to learn about the system while using it. All sections in the Add New Postpage are well-labeled. There are sufficient descriptions, and what is not needed is hidden by default. Our title automatically became a search engine friendly permalink for this post. We could format our text with a simple WYSIWYG editor. It was packed with features—spell check, full screen editing, and further formatting options via Kitchen Sink. The editor allowed advanced editing by switching to the HTML mode. Adding an image was very easy. Upload, set options, and insert. We could select a previously uploaded image from the gallery, too. We could enter keyword tags for a post quickly. Selecting a category and adding new categories was simple. We created a new category on the Add New Post page itself. WordPress is intelligent enough to understand that if we added a new category on a post page, we would want to use it for that post. So, it was selected automatically. Advance options were available, but were hidden by default. We could publish the post right away, or at a later date. WordPress could also keep history of all the revisions we make to a post, could preview the post, and would auto-save it frequently. WordPress looks easy and powerful so far. Let us look at how we can harness it further. Surviving blog jargon and benefitting from itBlogs have their own terminology. You may not have heard of trackbacks, pingbacks, tags, or permalinks. You can learn more about these terms from http://en.wikipedia.org/wiki/List_of_blogging_terms and http://www.dailyblogtips.com/the-bloggers-glossary/. Similarly, there are excellent features that blogs have—comments, aggregating content from other sources, ability to get updates via RSS feeds, and so on. I recommend you to go through these glossaries to learn more about blogs. Extending WordPress Managing content with WordPress seems easy. We want to see how easy is it to customize its design and extend its features. Let's begin with the action. Time for action-customizing the design Find some themes you like. You can browse through theme galleries at http://WordPress.org/extend/themes/ or Google WordPress themes. There are thousands of free and paid themes available for WordPress. Download some themes that you like. Unzip each theme's ZIP file. Each theme should create a new folder for itself. Upload all these folders to the wp-content/themes folder on your server. In WordPress, go to Admin  Appearance|. You should see new themes you uploaded in the Available Themes section. The page also lists the WordPress Classic andDefault themes. We have three new themes showing up. Click on one of the themes to see a live preview. This is how it will look. Review all themes. Activate the one you like the most by clicking on the Activate link at the top right in the preview window. We liked oriental and activated it. Our site now shows up just like the live preview. What just happened? We installed a new design theme for our WordPress blog. We downloaded three themes from the Web, unzipped them, and uploaded them to our WordPress themes folder. The themes showed up in WordPress admin. Clicking on a theme showed a live preview. This made our decision easy. We activated the theme we liked. That's how easy it was to change the design of our blog! If you recall, installing a new design was similar in Joomla!, except that Joomla! allowed us to upload a ZIP file using its administration interface itself. The tricky part in giving a new design to your site was shortlisting and selecting a design, not setting it up. Customizing the theme Consider the following theme editor in WordPress If you want to further customize your theme, you can do that. In fact, you have full control over how your site looks with WordPress. You can use Appearance | Editor to change individual theme files. We recommend making template customizations on a local installation of WordPress first.Once you get everything done according to your choice, you can upload the changed files to the theme's folder and activate it. WordPress widgets Widgets are content blocks that can be used in a theme. Search, RSS feeds, Blog Post Archives, Tag Cloud, and Recent Posts are some of the built-in widgets available in WordPress. You can turn them on or off independently, determine their position in the sidebar, and also change their settings. Go to the Appearance | Widgets page to take over the control of WordPress widgets. Add unlimited power with plug-ins Our Yoga Site needs a lot more than just the core content management. How can we achieve that with WordPress? And will it be wise to use WordPress for our Yoga Site? The WordPress plug-in architecture is solid. You will find hundreds of high-quality plug-ins from photo galleries to e-commerce. But remember that the core of WordPress is a blog engine, which chronologically displays content under set categories. It encourages sharing and contribution. Theoretically, you can customize WordPress to any need you have. But we recommend you to evaluate the most important features for your site and then decide whether you want to use WordPress as a base, or something else. I use WordPress for my blog and have a range of plug-ins installed. WordPress is painless, and it allows me to focus on the core goal of my blog—sharing knowledge. Take a look at the list of plug-ins on my blog at www.mehtanirav.com. You may have noticed a few plug-ins to handle comments and spam. Why would you need that? Well, because you will end up spending all your time removing spam comments from your system if you don't have them activated. Comment spam is a real pain with all blogs. Spammers have written spam-bots (automatic software) that keep posting junk comments on your blog. If you don't protect comment submission, your blog will soon be flooded with advertisements of pills you don't want to take and a lot of other things you don't want your visitors to attend to. Comment protection plug-ins are the first you should install. I use Akismet with Simple Math. Simple Math poses a simple mathematical question to the comment writer. A human can easily answer that. This takes care of most of the spam comments. Comments that pass through this test need to pass through Akismet. Askimet is an excellent spam-protection plug-in from the WordPress team. These two plug-ins kill almost 99.99% of spam comments on my blog. Once I am left with legitimate comments, I can go to WordPress's Admin | Comments, and Approve, Unapprove, Delete, or Mark as Spam all comments. The Edit Comments screen looks like the following screenshot:| WordPress is a superb choice for creating a blog. It can be used as a general-purpose CMS as well. We have covered most of the day-to-day operations with WordPress so far. Here are some additional resources for you.
Read more
  • 0
  • 1
  • 6214

article-image-enhancing-user-experience-wordpress-27part-2
Packt
12 Oct 2009
7 min read
Save for later

Enhancing User Experience with WordPress 2.7(Part 2)

Packt
12 Oct 2009
7 min read
Creating a drop-down menu for your categories Do you use a lot of categories along with their sub-categories? If so, using a drop-down menu is a nice way to categorize content, especially on larger sites. However, giving a quick access to the categories or sub-categories to readers can become a pain. Over the years, the drop-down menu has become very popular on the Internet. In this recipe, I'm going to show you how to create your own drop-down menu for your WordPress blog categories. Getting ready The menu you are going to create will first list your pages, and then at last a tab called Categories will obviously list your categories. This menu is achieved only with XHTML and CSS. No JavaScript is needed (unless you want to maintain compatibility with it commonly referred to as IE6) to ensure the best SEO possible for your WordPress blog. How to do it In order to make this recipe more readable, I have divided it in 3 steps—the PHP and the HTML, the CSS, and the JavaScript for IE6 compatibility. Step 1: PHP and HTML Open the header.php file from your theme and paste the following code where you'd like your drop-down menu to be displayed: <ul id="nav" class="clearfloat"><li><a href="<?php echo get_option('home'); ?>/"class="on">Home</a></li><?php wp_list_pages('title_li='); ?><li class="cat-item"><a href="#">Categories</a><ul class="children"><?php wp_list_categories('orderby=name&title_li=');$this_category = get_category($cat);if (get_category_children($this_category->cat_ID) != "") {echo "<ul>";wp_list_categories('orderby=id&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID);echo "</ul>";}?></ul></li></ul> The purpose of this code is to make a list of all our pages and subpages, as well as a last list element named Categories. When a reader hovers on one of the top-level menu, the subpages (or categories) are displayed. Step 2: The CSS Open the style.css file from your theme and paste the following styles: #nav{background:#222;font-size:1.1em;}#nav, #nav ul {list-style: none;line-height: 1;}#nav a, #nav a:hover {display: block;text-decoration: none;border:none;}#nav li {float: left;list-style:none;border-right:1px solid #a9a9a9;}#nav a, #nav a:visited {display:block;font-weight:bold;color: #f5f5f4;padding:6px 12px;}#nav a:hover, #nav a:active, .current_page_item a, #home .on {background:#000;text-decoration:none}#nav li ul {position: absolute;left: -999em;height: auto;width: 174px;border-bottom: 1px solid #a9a9a9;}#nav li li {width: 172px;border-top: 1px solid #a9a9a9;border-right: 1px solid #a9a9a9;border-left: 1px solid #a9a9a9;background: #777;}#nav li li a, #nav li li a:visited {font-weight:normal;font-size:0.9em;color:#FFF;}#nav li li a:hover, #nav li li a:active {background:#000;}#nav li:hover ul, #nav li li:hover ul, #nav li li li:hover ul, #nav li.sfhover ul, #nav li li.sfhover ul, #nav li li li.sfhover ul {left: auto;}a.main:hover {background:none;} You may have to tweak this code a bit to match up to your blog's look and feel, for example, by adjusting colors. Once you are finished, simply save the file. Step 3: Optional JavaScript I'm not going to teach you something new here since, Internet Explorer 6 is a totally obsolete, crappy, and buggy browser. Sadly, many peoples are still using it and you may want to make sure that your blog is IE6 compliant. Modern browsers as such as Safari, Firefox, Opera, and even Internet Explorer 7 will not have any problem with the :hover pseudo-class on li elements. But you guessed it, it is asking too much from the IE6. To ensure backward compatibility on your WordPress blog, create a new file and call it dropdown.js. Put this code in the dropdown.js file: <![CDATA[//><!--sfHover = function() {var sfEls = document.getElementById("nav").getElementsByTagName("LI");for (var i=0; i<sfEls.length; i++) {sfEls[i].onmouseover=function() {this.className+=" sfhover";}sfEls[i].onmouseout=function() {this.className=this.className.replace(newRegExp(" sfhoverb"), "");}}}if (window.attachEvent) window.attachEvent("onload", sfHover);//–><!]]> Save the dropdown.js file and upload it to your wp-content/themes/yourtheme directory. Open header.php and add the following line within the <head> and </head> HTML tags: <!--[if lte IE 6]><script type="text/javascript" src="<?php bloginfo('template_url');?>/dropdown.js"></script><![endif]--> That's all! Your blog now has a very professional looking drop-down menu. How it works As IE6 cannot deal with :hover pseudo-classes on <li> elements, this small piece of code automatically ads a new CSS class, named sfhover to <li> elements when they are hovered over. When the mouse goes out of the top level element, a new function is executed, using a regular expression to remove the sfhover class. There's more... Now that I have shown you're the principle of creating a drop-down menu, you can use what you have just learned to create various kinds of menus. As an example, let's see how to re-use the previous code and create a very nice horizontal drop-down menu. Creating a horizontal drop-down menu As you'll notice by observing the code, there's a lot of similar things between this code and the one that you saw earlier. Part 1: PHP and HTML Simply copy this code where you want the menu to be displayed, for example, in your header.php file: <ul id="nav2" class="clearfloat"><li><a href="<?php echo get_option('home'); ?>/"class="on">Home</a></li><?php wp_list_categories('orderby=name&exlude=181&title_li=');$this_category = get_category($cat);if (get_category_children($this_category->cat_ID) != "") {echo "<ul>";wp_list_categories('orderby=id&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID);echo "</ul>";}?></ul> Part 2: The CSS In modern drop-down menus, CSS are a very important part. Indeed, in this example it is CSS that display our menus horizontally. Paste the following code in your style.css file: #nav2{background-color: #202020;display: block;font-size:1.1em;height:50px;width:100%;}#nav2, #nav2 ul {line-height: 1;list-style: none;}#nav2 a ,#nav2 a:hover{border:none;display: block;text-decoration: none;}#nav2 li {float: left;list-style:none;}#nav2 a,#nav2 a:visited {color:#109dd0;display:block;font-weight:bold;padding:6px 12px;}#nav2 a:hover, #nav2 a:active {color:#fff;text-decoration:none}#nav2 li ul {border-bottom: 1px solid #a9a9a9;height: auto;left: -999em;position: absolute;width: 900px;z-index:999;}#nav2 li li {width: auto;}#nav2 li li a,#nav2 li li a:visited {color:#109dd0;font-weight:normal;font-size:0.9em;}#nav2 li li a:hover,#nav2 li li a:active {color:#fff;}#nav2 li:hover ul, #nav2 li li:hover ul, #nav2 li li li:hover ul,#nav2 li.sfhover ul, #nav2 li li.sfhover ul, #nav2 li li li.sfhover ul {left: 30px;} Once you have added theses lines to your style.css file and saved it, your WordPress blog will feature a very cool horizontal menu for displaying your categories. Part 3: (Optional) JavaScript As usual, if you want to maintain backward compatibility with Internet Explorer 6, you'll have to use the Javascript code that you have already seen in the previous example.
Read more
  • 0
  • 0
  • 1518
Modal Close icon
Modal Close icon