Monitor and Control Applications Using Supervisor: Part 2

In the first part of this two-part tutorial series, we saw to set up and control Supervisor to work with our web applications. In this part, we will see how we can programmatically control Supervisor processes remotely via the XML-RPC API.

Getting Started

In the previous part, we saw that Supervisor provides a web-based GUI which allows us to remotely control the processes with the help of a few clicks. Below is a screenshot of this GUI for the application we created in the previous part:

Supervisor

A question immediately starts ringing in the brain. What if it were possible to control the Supervisor processes programmatically? This would open up a lot of possibilities where processes can be started or stopped conditionally rather than having them run indefinitely or controlling them manually by clicking buttons or running terminal commands. This is very much possible using the XML-RPC API provided by Supervisor.

The XML-RPC API

The API itself is pretty straightforward and easy to use. We saw that the HTTP server for Supervisor runs on port 9001 by default. The same can be used to connect using any XML-RPC library. In the case of Python, we can simply use the built-in xmlrpclib. Assuming that the Supervisor server runs on http://localhost:9001/:

To check the current state of the Supervisor server, run:

The server daemon can be restarted and stopped by:

Similarly, the list of all available methods can be fetched by:

The API reference provided in the Supervisor documentation is pretty clean and self-explanatory. Going ahead in this tutorial, I will cover an example of how to control the processes based on a condition, and also how we can extend this API in order to implement our own methods.

Controlling Processes Using the API

Lets say we want a start a new process to send an email every time an action is performed by some user. (There are many ways of doing this, and maybe this is not the best one, but I am just using it as an example to demonstrate this). Let’s say the name of this process as defined in supervisord.conf is send_mail.

Similarly, we can also trigger automatic restarting of the supervisord server daemon in case we have a code change in our application.

This API can similarly be applied to countless such instances. 

Extending the XML-RPC API

We can not only use the standard API methods provided by Supervisor but also write our own methods, extending the API by using the XML-RPC interface factories. This can simply be done by adding a new [rpcinterface:x] section in supervisord.conf.

Now I will create a small custom interface for the same in a file named my_interface.py.

Above, I have created a method which when called will retry the process three times in case of failure to start.

Conclusion

In this tutorial series, we learnt how to use Supervisor to monitor and control our applications. We also saw how we can use the Web UI and XML-RPC Interface for the same. Finally, the XML-RPC interface is extended in order to leverage the power of Supervisor to our benefit.


Source: Nettuts Web Development

Mastering WP_Meta_Query & WP_Date_Query

Welcome to the final part of the series—well, technically the final part will be “Series Finale”, but you get the idea. In this part, you’re going to learn about two sibling classes called WP_Meta_Query and WP_Date_Query.

Without further ado, let’s begin!

Working With All Kinds of Meta Data Through the WP_Meta_Query Class

The WP_Meta_Query class is a “helper class”, helping WP_Query to make queries with meta data.

As you know, WordPress stores three kinds of meta data in the database: post meta, user meta and comment meta. We saw in the previous tutorials that we can run meta queries within the queries that we make with the WP_Query, WP_User_Query and WP_Comment_Query classes (with the 'meta_query' parameter). The WP_Meta_Query is actually running when you do those queries.

Turns out, you can get the SQLs for these meta-related queries with the help of the WP_Meta_Query class. This class doesn’t really get the results of the given query, but instead prepares the SQL commands for you to use somewhere else.

Example Use of the WP_Meta_Query Class

We can’t say it’s a tutorial if we don’t do an example, right? With a simple example, we’re going to see how we can use the WP_Meta_Query class in real life. (Granted, it’s an extremely specific thing to get the SQL code for a meta-related query, but I will try to come up with a real-world example.)

Let’s imagine that you want to make a special “related posts plugin” for your own website, where you will list posts which have the same meta value for a meta key—or another meta value for another meta key. And instead of making a meta query within a WP_Query instance, you want to get the SQL code of the query to use it dynamically in separate code blocks. Here are the steps to prepare that SQL code:

There you go: The $my_meta_sql variable stores the SQL code for your special query, and you can use this SQL code anywhere you like within your project.

Wrangling Date Queries With the WP_Date_Query Class

Just like WP_Meta_Query, the WP_Date_Query is a helper class for the WP_Query, WP_User_Query and WP_Comment_Query classes. This helper class was introduced in WordPress version 3.7. Back then, the class didn’t support WP_User_Query, but since the 4.1 version, you can query inside the users table (the user_registered column specifically).

Similar to WP_Meta_Query and its ability to query meta keys and values, the WP_Date_Query class allows us to query date fields inside the posts, comments and users tables. And exactly like WP_Meta_Query, this helper class also lets you return the prepared SQL code to run a date-related query.

Example Use of the WP_Date_Query Class

In order to fully understand how the WP_Date_Query class works, let’s go through an example with it. It’s going to be yet another unnecessarily specific example, but it wouldn’t feel right to leave this part without an example.

Let’s imagine that, for some reason, we need to query for comments that are made in the current month and before noon. (Please shoot me a comment if you find a good case to fetch comments made in the current month and before noon!) Here’s how to get the SQL code for this bizarre query:

There you go. Keep in mind that you can use PHP relative date formats, which are really useful.

Quick tip: Christian Bruckner has a great post on MarketPress.com about how WP_Date_Query works. It’s a little bit outdated (because it was written before WordPress 4.1 was released) but it’s very well-written and still a good read. Be sure to check it out.

Wrapping Everything Up

With these two helper classes, we’re ending the long journey of dissecting the WP_Query class. This was one of the longest tutorial series in the history of Tuts+, so thank you for bearing with us till the end! In the next (and last) part, we’re going to recap what we went through for the last time and close the series.

Do you have anything to add to this article? If so, don’t hesitate to share your thoughts in the Comments section below. And if you liked the article, don’t forget to share it with your friends!


Source: Nettuts Web Development

Monitor and Control Applications Using Supervisor: Part 1

Supervisor
is a monitoring tool which controls various child processes and
handles starting/restarting of these child processes when they exit
abruptly or exit due to some reasons. It can be extended to control
the processes via the XML-RPC API over remote locations without logging
in to the server. I will cover the XML-RPC API in the second part of this two-part series.

In the first part of this tutorial series, I will take you through how to set up Supervisor to work with our application. For this, I will create a trivial application in Flask along with Gunicorn to act as our WSGI HTTP server. 

I assume that you have a basic understanding of Flask, Gunicorn and environment setup best practices using virtualenv to be followed while developing a Python application.

Installing Packages

The following packages need to be installed for developing and controlling the application we’ll be developing.

The Trivial Application

I will now create a trivial application in Flask. This application is small but will meet the needs of this tutorial.

Below is the structure of the application:

flask_app/my_app/__init__.py

In the file above, the application has been configured and initialised.

flask_app/my_app/views.py

In the file above, I have created a simple Hello World endpoint.

To run the application as a process, we can use Gunicorn. To check if Gunicorn is working as expected, just run the following command from inside the application folder.

After this, point your browser to http://127.0.0.1:8000/ to see the application’s
home page.

Configuring and Using Supervisor

Now, we need to do the same using Supervisor so that this runs as a daemon and will be controlled by Supervisor itself rather than human intervention. 

First of all, we need a Supervisor configuration file. Supervisor, by default, looks for an etc folder that has a file named
supervisord.conf. In system-wide installations, this folder is /etc/, and in virtualenv,
it will look for an etc folder in virtualenv and then fall back to /etc/.

In the case of a system-wide installation, run:

In the case of virtualenv, from inside the virtualenv root folder, run:

The echo_supervisord_conf program is provided by
Supervisor; it prints a sample config file to the location specified. This will create a file named supervisord.conf at the location specified in the above command.

To configure Supervisor for our application, add the following block somewhere in this file:

Here we configure the command that needs to be run and from which directory location it needs to do so under which user. Also specified is whether to restart the application in case of any failure. The log files’ locations can also be specified. There are many other configuration options, which can be looked up in the official documentation of Supervisor.

Make a note that one should never run the applications as a root user.
This is a huge security flaw as the application crashes, which
can harm the OS itself.

To run the application using Supervisor, run the following commands:

The first command invokes the supervisord server, and the next one gives a status of all
the child processes.

Every time you make a change to your application and then wish to restart Gunicorn in order
for it to reflect the changes, run the following command:

You can also give specific processes instead of restarting everything: 

Supervisor also provides a Web UI interface which can be enabled by enabling the inet_http_server configuration block in supervisord.conf. This Web UI can be looked up on http://localhost:9001/.

Conclusion

In this tutorial, we have seen how to configure Supervisor and use it to run an application as a daemon process and control the processes collectively or selectively. In the second part of this tutorial series, we will see how to control and interrogate Supervisor and its programs/processes using the XML-RPC API.


Source: Nettuts Web Development

Mastering WP_User_Query

After all those previous parts, we’re done going through the WP_Query class—but that doesn’t mean that we’re done with the series! It’s time to meet WP_Query‘s brother and sister classes: WP_User_Query, WP_Comment_Query, WP_Meta_Query and WP_Date_Query.

In this part, we’re going to learn about using the WP_User_Query class to query users in WordPress.

Let’s begin!

What Is WP_User_Query?

You probably get the idea of what WP_User_Query is by merely reading its name. Yes, nobody would expect to see WP_User_Query working with the “Tag Cloud” widget—it’s a class that runs queries about users in WordPress.

Let’s see what WordPress Codex says about the WP_User_Query class:

WP_User_Query is a class, defined in wp-includes/user.php, that allows querying WordPress database tables ‘wp_users‘ and ‘wp_usermeta‘. This class was introduced in Version 3.1 and as a result, the WP_User_Search class got deprecated.

In essence, we can say that “WP_User_Query is WP_Query for users”. It works with wp_users and wp_usermeta to query users and their metadata.

Now, let’s see what’s under the hood and learn about WP_User_Query‘s properties, methods and parameters. Then we’ll see how it works by going through a few examples.

Quick Tip: We’ve covered this while introducing the properties and methods of the WP_Query class, but let me say it again as a quick reminder: “Properties” and “methods” are merely “variables” and “functions” that are defined inside a PHP class.

Properties of WP_User_Query

There are only seven properties to learn about in the WP_User_Query class. Remember: These should NOT be used to change their values. You can fetch their values, but it’s better not to alter them.

$query_vars

This property stores an associative array of query variables and their values.

$results

This property has the number of found items (users in this case) for the query.

$query_fields

This property, similar to the following properties, stores the SQL clauses for the return fields.

$query_from

This property stores the FROM clause for the query.

$query_where

This property stores the WHERE clause for the query.

$query_orderby

This property stores the ORDERBY clause for the query and is used to order the list of users returned.

$query_limit

This property stores the LIMIT clause for the query and is used to limit the number of users returned.

Methods of WP_User_Query

Remember the methods of the WP_Query class? Well, this class has only four methods and they work just like the methods of WP_Query. Let’s quickly see why each one exists.

The get() Method

This method simply fetches a query variable from the query.

The set() Method

Contrary to the one above, this method sets a query variable instead of getting it.

The get_results() Method

Unlike WP_Query, the WP_User_Query class doesn’t work with a “loop”. Instead, you need to use the get_results() method to get the query results and work on them.

The get_total() Method

This little method returns the total number of items (users) for the query.

Parameters of WP_User_Query

Like the WP_Query class, WP_User_Query has parameters that you need to know about. But while WP_Query has a large number of parameters (more than 50!), WP_User_Query has only 17 parameters to worry about—and they’re very similar to the ones in WP_Query, so if you’re familiar with those, it shouldn’t be any hassle learning these ones.

  • blog_id: An integer to specify a blog’s ID in multisite networks. Defaults to the current blog.
  • role: A string to state a user role. Accepts subscriber, author, contributor, author, editor, administrator, and any custom-created user role.
  • include: An array of user IDs to include in the query.
  • exclude: An array of user IDs to exclude from the query.
  • search: A string value to search for in the fields of the wp_users table.
  • search_columns: An array of columns of the wp_users table. Accepts ID, user_login, user_url, user_email, and user_nicename.
  • orderby: A string to state how to sort the returned users. Accepts ID, display_name, name/user_name, login/user_login, nicename/user_nicename, email/user_email, url/user_url, registered/user_registered, post_count, and meta_value. Defaults to login.
  • order: A string to set the order to ascending (ASC) or descending (DESC).
  • offset: An integer to specify the number of users to pass over.
  • number: An integer to set the number of users to return.
  • count_total: A boolean (TRUE/FALSE) to state whether to count the total number of users found.
  • fields: A string or array to decide which fields to return from the wp_users table.
  • who: A string (either authors or all, which is the default value) to state which users to query.
  • meta_key: A string to state a custom user meta field key.
  • meta_value: A string to state a custom user meta field value.
  • meta_compare: A string to set an operator to test the 'meta_value' parameter. Accepts '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS', and 'NOT EXISTS'. Defaults to '='.
  • meta_query: An array to create a full meta data query, using keys similar to the ones above:
    • key: A string to set a custom field key.
    • value: A string or an array to set a custom field value (or values).
    • compare: A string to set the compare operator. Accepts the same values as meta_compare above.
    • type: A string to set the custom field type. Accepts NUMERIC, BINARY, CHAR, DATE, DATETIME, DECIMAL, SIGNED, TIME, and UNSIGNED. Defaults to CHAR.

Trying Out WP_User_Query With a Few Examples

Now we’ve seen how WP_User_Query works, let’s do a couple of examples to learn how to use it.

Listing All Editors Except Lisa

Let’s say you want to list your editors to your readers, but you remember that one of your editors, Lisa, has agreed to work with you on condition of anonymity, so you need to leave her out in the “Editors” list. Here’s how you construct the query:

Search for Gmail Users Among Your Authors

Let’s say you want to collect email addresses of your authors which use a Gmail address. Here’s what you do:

Wrapping Everything Up

As you can see, there are just a few differences between WP_Query and WP_User_Query, and the differences actually make WP_User_Query easier to understand. I hope I helped you learn about this neat class of WordPress.

Do you have anything to add to this article? Share your thoughts with us in the Comments section below. And if you liked the article, don’t forget to share it with your friends.

See you in the next part of the series!


Source: Nettuts Web Development

The Beginners Guide to WooCommerce: Taxes Report

One of the biggest confusion and hindrance in setting any kind of business is to understand the tax structure which will apply on your dealings. Taxation is quite a sensitive issue as far as business is concerned and it needs to be sorted well and in an organized way. Especially when you own an ecommerce business tax issues become even more complicated. As you are dealing with customers from all around the world and the tax rates vary accordingly. So, I am sure being an online store owner you will never want to find yourself trapped in any legal complication due to some tax related issue.

Taxes Report in WooCommerce

A more professional approach towards dealing with taxes is to fully monitor and study tax rates and keep them stacked in some organized way. This way you can check your past tax records whenever needed. 

For online store owners all this has been made possible with WooCommerce with which you can easily review your tax status via reports which are displayed in the form of tables. So, let’s discuss the section of taxes report in detail.         

Taxes report in WooCommerce

To enter this last section of reports you must follow the path i.e. WooCommerce > Reports > Taxes. This section is further divided into two sub-sections i.e.

  1. Taxes by code
  2. Taxes by date 
Taxes report in WooCommerce

The layout in this section is pretty much similar to the section of Orders & Customers reports. Where the first row displays various time filters according to which the tax reports will be listed. These are displayed on the basis of year, last month, this month & a custom date. Also towards the end of this first row is a button for Export CSV which allows you to download all the tax reports in .csv format.

Taxes by code

I have explained in my previous articles that every new tax rate bears a unique id or more precisely a tax code. So, in the first sub-section the tax details are displayed w.r.t to the tax codes. 

Taxes report in WooCommerce

Here you will find a table in which different entries are stacked in the form of lists in different columns. These columns are for:

  • Tax: This is the first column under which the tax code names are displayed.
  • Rate: In the next column the actual tax rate is displayed.
  • Number of orders: The total number of orders which are received in a particular period of time.
  • Tax Amount: The total tax amount which will be implemented on the total no. of orders. 
  • Shipping Tax Amount: If you are implementing taxes on various shipping types then this amount is displayed here.
  • Total Tax: The sum of Tax Amount & Shipping Tax Amount is shown in this last column.

According to the the figure shown above, this tax report corresponds to the Last Month. Where the stats about the tax code US-US-1 have been shown. In this time span, a total amount of £15.00 tax was applied on 5 orders. Out of which £5.00 was the Tax Amount & £10.00 was the Shipping Tax Amount.

Similarly, you can view tax reports for other time spans as well E.g. year, last 7 days, etc. 

Taxes by date

The second and the last sub-section is for the Taxes by date and as its name explains, the taxes are categorized and listed w.r.t to various dates in a particular time span. Once again the tax reports are listed in columns.

Taxes report in WooCommerce

These columns are for the following:

  • Period: The first column displays the exact date on which tax was applied.
  • Number of orders: Lists the no. of orders which were placed on a particular date.
  • Total Sales: The revenue which was generated on a particular date.
  • Total Shipping: Displays the total amount which was charged for shipping.
  • Total Tax: The amount of tax which was applied.
  • Net Profit: This amount is calculated by “Total Sales – Total Tax“.

Once again the above stats are for the Last Month and you can view for other time filters as well. According to the above figure on January 14, 2015 the online store owner enjoyed a net profit of £192.00 which was gathered from 2 orders. 

Conclusion

This ends not only the Taxes reports but also the entire section of reports in WooCommerce. I am sure that after reading all the articles of the reports section you can easily manage your store’s Orders, Customers, Stock & Taxes. However, if you have any queries regarding this section you may ask in the comment field below.


Source: Nettuts Web Development

Combining WP_Query With the Main Query

So far in this series you’ve learned how to use WP_Query to create custom queries for use in your theme or plugins.

In most cases, you’ll use WP_Query with a completely new set of arguments which are separate from that in the main query, but what if you want to include the main query in your arguments?

Examples of when you might want to do this include:

  • on a category or taxonomy page, displaying only posts of one post type
  • on a category page, displaying posts with the current category and another category or a tag or taxonomy term
  • on a page for a post type, just displaying posts with certain metadata

I could go on—there are plenty of opportunities for combining the main query with your own custom query.

I’m going to demonstrate this with three examples: the first one will be a simple example with one loop; the second will use foreach to output multiple loops, one for each post type; and the third will output two post types on a category archive by using two separate queries.

Defining a Variable Based on the Main Query

However you’re going to combine your main query with WP_Query, you need to store the current query object in a way that makes it easy to use in your WP_Query arguments. The easiest way to do this is by assigning it to a variable.

You do this before defining your WP_Query arguments, like so:

The get_queried_object() function returns the currently queried object, whatever that may be. On a single post, it will just return the post object, while on an archive it will return the category, tag, term object or whatever object relates to the archive. It returns the ID of the queried object.

You can then use this $mainquery variable in your WP_Query arguments. Now let’s take a look at some examples.

Example 1: Displaying Only Posts of One Post Type on a Category Page

Let’s say your site has a custom post type added to it and you’ve enabled categories for that custom post type. On the category archive for each category, you don’t want to display posts: instead you want to display posts of your new post type—let’s call it product.

Your query might look something like this:

Because the category_name parameter I’ve used above takes the category slug as its argument, you need to add ->slug after the variable to output the category slug.

This gives you a query which fetches posts of the product post type from the database with the currently queried category. You’d use it on the category.php page template.

Note: You could also achieve this result using the pre_get_posts hook to amend the main query, combined with a conditional function to check for category archives.

Example 2: Combining the Main Query With WP_Query and foreach to Output Multiple Loops

The next example will output all of the posts for the current category page, but instead of showing them all in one block it will separate them by post type.

This means you can sort your post types into blocks or columns on your page using CSS, or just separate them out into different lists.

To do this, you’d use the following code:

This uses the $mainquery variable we used before, but it also adds a $post_types variable to store all of the post types registered on the site, and a $post_type variable to store each individual post type in turn.

Example 3: Two Separate Queries for Two Post Types

The final example is similar to the second one, but separates out the post types into two separate queries, each with its own distinct loop. This gives you more control over what’s displayed for each, so you could display posts differently from products, maybe including a featured image for products or giving them a different layout.

Let’s say your site has the product post type registered, with categories enabled for it, and you’re also writing blog posts with the same categories. On each category archive page you want to display the most recent ten posts, and then you want to display a list of all products in the same category.

To do this, you’d use something like this code:

You’d then write each loop differently to output different data for each post type.

Summary

As you can see from the examples above, it’s possible to use WP_Query not only to create completely custom queries separate from the main query, but also to incorporate the currently queried object and create more powerful queries on archive pages.

The examples above can also be done with other archive types: for taxonomies, authors, dates and more. See if you can come up with more possibilities!


Source: Nettuts Web Development

Get Started Building Your Blog With Parse.js: Delete, Logout, and Single Blog View

Final product image
What You’ll Be Creating

In the last session, you refactored your entire blog system. Now that everything’s cleaned up, you are ready to speed up for some new adventures. In this session, we are going to do more around the router, and add three more functions to our blog system: delete, logout, and single blog view.

1. Delete

In part 6, we covered the edit function. Chances are, you would also want to delete one of your blog posts. There are two places you can put this function: add it in the BlogsAdminView, or send it to a URL and deal with it in the Router.

I will show you the Router way. It’s more commonly used, and it makes the code better structured.

Step 1: Add URL Pattern

As usual, let’s add a URL pattern first:

Step 2: Link to Delete

Then, update the link in the admin page:

Step 3: del Function

Now, let’s add a new del function to the Router to handle it. It’s pretty straightforward: find the blog post using the id we passed in from the URL, and destroy it.

Try to challenge yourself and write it without reading my code. You should be getting a really good grasp of Parse.js at this point.

Notice that you can use the .then() function here instead of passing an object as we did previously:

It’s an easy way to add callback functions in Parse.js, making your code cleaner and more readable. Go to Parse.com to see full documentation on promises.

Let’s give it a test run, and double-check the database to see if it’s working.

Delete Alert

Congrats, it’s working!

Step 4: Redirect Back to the Admin Page

If you pay attention to the URL, you will see that after you click out of the alert box, the URL is still /del/ and the post you just deleted is still there. We want to send users back to the admin page after deletion, and the page should refresh and reflect the change they just made.

You can achieve all of that by doing a redirect:

Notice that because this time you call navigate from within the router, you can just store the router as self, and call self.navigate().

Step 5: Check Login

Finally, we need to make sure you are the only one who can delete your blog posts. Let’s check login for the function. This should be the same as the edit function.

2. Logout

Like delete, logout can also be handled by the router. And it also starts with adding the URL pattern:

The logout function itself is really easy in Parse.js. Just call Parse.User.logOut() and then redirect to the /login page:

And finally, let’s add a button to #admin-tpl:

Logout Button

As you can see, styling is really not the focus of this tutorial. Feel free to fix the padding and style it however you’d like.

3. Single Blog View

Now let’s move on to make some new functionalities.

Up to this point, we are showing the whole blog article on the home page. While some people do prefer this style, most blogging systems support the idea of having a snippet summary upfront, and if the visitors click into the articles, they then can see the content on a separate page, with possibly some commenting area around it.

I will walk you through creating this detailed single blog view in this session, and we will be focusing on building commenting in the next one.

Step 1: Add a Summary Column

First, let’s add a column for the summary in the Blog table:

Add Summary Column

Step 2: Include Summary in WriteBlogView

Now, let’s add it to the Blog.update() function. You can change the function to take a data object which contains the title, summary, and content, to avoid memorizing the order of the variables.

Add one more <textarea> for summary in #write-tpl:

And change the WriteBlogView.submit() function accordingly:

Now, since we’ve added a new variable in the template, we need to give it a default empty value in the WriteBlogView.render() function:

And if you are using the wysihtml5 plugin for the content, you will notice previously we are targeting all the <textarea> elements:

Let’s give the content textarea a class and target only that with the wysihtml5 plugin.

In #write-tpl:

In the WriteBlogView.render() function:

Now it’s working!

Summary In WriteBlogView

Step 3: Display Summary on the Home Page

Play with the new write blog page and add some blog posts with summary, and pull the summary instead of the content in #blogs-tpl:

Step 4: Add the SingleBlogView Page

Take a minute and think about how would you add a /blog/:id page to show the content for each blog post, and try to do it yourself. You should be able to do it all by yourself now!

But for the purpose of this tutorial, let me give you a quick walkthrough:

Add a new HTML template for this page:

Add a new BlogView class that takes in a blog object, and render it in #blog-tpl:

Add a new URL pattern in BlogRouter:

And in the BlogRouter.blog() function, get a blog by its id, render a blogView, and put it in $container:

Finally, update the link in #blogs-tpl to link to this page:

Give it a try:

blogView

Extra points if you did this by yourself.

Conclusion

In this session, you built a lot: a delete function, a logout function, and another new page type. If you’ve been following this tutorial series until now, I think you have a solid understanding of how database, model, view, template, and router work together. I hope you’re also starting to enjoy building a Parse.js project at this point. Leave me your feedback and let me know if it’s helpful.

With this single blog post page we built this time, we are going to add a comment section next time. Should be a fun one. Stay tuned!


Source: Nettuts Web Development

Building a Product CSV Import Tool in OpenCart: Part 2

In our last tutorial we discussed how to
implement an import tool, in which we created an import button and its front-end template. Today we’ll learn how we can directly import the bulk data from our computers to our OpenCart System. 

Let’s consider the hierarchy first. In the previous tutorial we implemented the export tool, which allows the user to
download CSV sheets and alternate as needed. After that we implemented the
import tool, which allows the user to upload/import that edited file/data.
Previously we implemented the layout. In this article, we’ll
implement the functionality.

1. Controller File

In our last tutorial, we created a controller which pushes us to the layout of the upload form. In the view file of the layout, we had an upload input where the user can upload a CSV as shown below:

Import CSV page
  1. Navigate to admin/controller/catalog/product.php.
  2. Find the importCSV() Function, which
    we created in the previous tutorial.
  3. Place if
    (($this->request->server['REQUEST_METHOD'] == 'POST') ) {}
    after it, to ensure that the code part will only be executed if the above form is submitted.
  4. Inside the above block of code, we will add the code explained step by step below.

1.1 Getting the File

The following code opens the submitted CSV file and handles it as a read-only.

1.2 Traverse Through Each Record

Now we need to get through each row of the CSV and save into our db. In this regard, we will be looping through the records and saving them accordingly.

1.3 Redirecting

After the importing is finished, the user must be redirected, so the following code redirects the user to the form and gives a success message.

Up to this point, we’ve
created a function that only uploads the CSV, reads its data line by line and parses it to the model. Now we need to create a model as defined in the controller code, which is responsible for saving the parsed data into the db.

2. Model File

  1. Navigate to
    admin/model/catalog/product.php.
  2. Create a public function there named importCsvData($data).
  3. Inside the model function, we will add this code, which contains some queries to save the data.

Conclusion

So, today’s tutorial is all about
providing a complete solution for the Export/Import system. We provide such a solution, in
which users can edit/update their data. This solution is super easy to use and
implement as well. I am looking forward to your feedback. Feel free to leave a comment or query below. Thank you!


Source: Nettuts Web Development

Mastering WP_Query: 10 Useful Examples

Now that we learned almost everything about the WP_Query class, it’s time to try out some examples. In this part, we’re going to work on 10 different scenarios to utilize the WP_Query class and related functions.

It will be a fun exercise and I hope it will be equally educational. Let’s begin!

A Quick Reminder on Creating a Loop With WP_Query

Just to make this article be understandable separately from the “Mastering WP_Query” series, I should do a nano-tutorial on creating WordPress loops with the WP_Query class.

It’s not different than creating a regular loop, really. A typical WordPress loop goes like this:

And creating a loop with the WP_Query class has only a few differences:

Let’s see the difference between the two:

  • We set some arguments for our WP_Query instance,
  • We instantiated the WP_Query class,
  • We added $my_query-> to the beginning of the have_posts() and the_post() functions (so they’re now the methods of the WP_Query class),
  • And we reset the data of $post so it can return to the main query.

Now we know how to create a loop with WP_Query and the difference between a regular loop and a loop created with WP_Query. We’re not going to create loops in every example (for the sake of keeping the tutorial short and on topic), so you can refer to this section if you need to create a loop with the examples below.

Example #1: An Author’s Posts in This Year

Let’s say that you want to list a specific author’s posts written in the current year in a special “Author’s Posts This Year” section. A simple combination of two WP_Query parameters will suffice:

Pass this query in a loop and you’re good to go!

Example #2: “Latest Posts From This Category” (Except the Current Post)

Let’s say that you want to create a loop under each post in their single post pages, and list latest posts from the category that the post is in. Of course, you have to exclude the current post in case it might be one of the latest posts from that category. Here’s how you create the query with the 'cat' and 'post__not_in' parameters:

For the loop, I suggest creating three or four columns with post thumbnails above post titles. It will look really nice right under the post and before the comments section.

Example #3: “Most Popular Posts” Ordered by Comment Count

WordPress doesn’t have a built-in “post view count” system, and plugins that provide this functionality are famous for slowing down the website (because on each post view, the plugins write in the database over and over again to record the view counts). However, there’s another kind of measurement to determine which posts are most “popular”: counting comments. And unlike view counts, comment counts are already in the database—the WP_Query class makes it super easy to order posts by comment count:

See how easy this is? Now imagine creating a custom page template with a loop running this query—a “Most Commented Posts” page.

Example #4: A Simple Slider Setup

When using WordPress to build corporate websites, portfolios or web magazines, sliders have become a “must-have” industrial standard. I’m not really a fan of sliders (I think it’s bad UX) but the web seems to like it, so I can’t just say no to my clients while making websites for them. If they want sliders, I use a simple query using the WP_Query class:

The 'cat' argument can be used to retrieve slides from different categories so you can separate slide groups and use multiple sliders on multiple pages. If you’re going to use just one slider in your website, you can delete that line and you’re good to go.

Example #5: A Random Quote in the Sidebar

If you’re keen on literature or religious, you might want to have some of your favorite quotes in the sidebar—it’s not a waste of space if you use the area with purpose. So, if you’re going to list a random quote in your sidebar on each page view, you can use the following code snippet to create the post type and use the following query to create a loop in your sidebar:

An easy and elegant solution.

Example #6: Listing Products Between a Price Range

I found this example on Scribu.net and I must say, it might be the best WP_Query trick in this tutorial. It’s a bit more technical than the others, too, because it can be applied to a WordPress-powered e-commerce website in this context.

Here’s the code snippet you’ll use if you want to list items from a custom “Product” post type and filter the results with the “price” custom fields:

A big kudos to Silviu-Cristian Burca!

Example #7: A Shortcode to Embed Posts Inside Posts

Here’s a fun exercise—and we get to use the Shortcode API too! In this example, we’re going to create a shortcode that can embed a post within a post. (I hardly contained myself from naming the shortcode [postception].) In the following code snippet, we create a shortcode function that allows us to embed posts (or any custom post type) and lets us choose whether to show the full post or just an excerpt:

Example #8: List of Current Scheduled Posts (With Optional Excerpts)

Here’s an idea: Why don’t you display some “sneak peeks” of your upcoming posts to your visitors? You can use the following function to list your scheduled posts with or without excerpts after the titles:

Example #9: “Post From a Year Ago Today”

If your blog is older than a year, and your content is timeless (meaning both a person from 2015 and 2025 will find the article relevant), adding a “Post From a Year Ago Today” section might boost your page views. Here’s how you do it:

Use this query to build a loop that displays a single post from yesteryear.

Example #10: Show Children of Current Page

You have nothing other than sub-pages’ titles to put inside your “Services”, “Our Works” or “My Portfolio” page? Maybe an intro paragraph, but you’re right, those pages are doomed to be “placeholders”. Still, it’s a good idea to place sub-pages in there—maybe a grid with square thumbnails and titles below. Let’s see which query we should use when creating such a page template:

Wrapping Up

I hope you enjoyed these examples as much as I did while preparing them. I paid special attention to giving varying examples both to be fun and to spark your creativity.

If you thought of better examples while reading these ones, or have questions, don’t hesitate to shoot a comment below. And if you liked the article, don’t forget to share it with your friends!

In the next part, we’ll talk about WP_User_Query, one of the sister classes of WP_Query. See you then!


Source: Nettuts Web Development

Free Course: Fun With Web Audio

Final product image
What You’ll Be Creating

You may have used the audio tag to play sound in the past. While that works fine for simply playing a sound, it doesn’t give us much control over the quality or timing of the playback.

In our new short course, Fun With Web Audio, you’ll learn about the Web Audio API, a powerful new way of playing and manipulating sound in the browser with JavaScript. 

You can complete the whole course in less than an hour of viewing time, so you can easily fit it in around your other commitments. And best of all, it’s free.

What You’ll Learn

In this short course, Tuts+ instructor Stuart Memo will show you how to build something you don’t usually see in a web browser: a synthesizer. Stuart will demonstrate how to build a little musical keyboard with real-time additive audio synthesis. You’ll also get a chance to experiment with analyzing sound and visualizing audio information on-screen. 

Watch the Introduction

Take the Course

To take this free course, simply go to the course page and follow the steps to create a free account. If you already have an account, just log in and you’ll be able to get started right away.


Source: Nettuts Web Development