Create a custom archives page in WordPress. Create ZIP archive in PHP Authoritative details archive php
When you need to quickly download site sources from the server, even a relatively fast SSH tunnel does not provide the required speed. And you have to wait for a very, very long time. And many hosting providers do not provide this access, but force them to be content with FTP, which is many times slower.
For myself, I determined the way out. A small script is uploaded to the server and launched. After a while, we get an archive with all the sources. And one file, even through the ancient FTP, downloads much faster than a hundred small ones.
Earlier on the pages of this blog, the zipArchive. However, then it was about unpacking the archive.
First, we need to find out if the server has zipArchive support. This popular library is installed on the overwhelming majority of hosting sites.
The library is hard-coded php parameters and the server. You won't be able to archive huge databases and banks of photos. Even the bases of the good old 1C program for accounting. It would seem that they should contain only text data. But no.
I advise you to use the library only when archiving relatively small sites with a huge number of small files.
Check if working with the library is available
If (! Extension_loaded ("zip")) (return false;)
If all is well, the script will continue its execution further.
A small offtopic for such checks. Checks should be done this way, avoiding large nested parentheses. This will make the code more atomic and easier to debug. Compare
If (a == b) (if (c == d) (if (e == f) (echo "All conditions worked";) else echo "e<>f ";) else echo" c<>d ";) else echo" a<>b;
and a code like this
If (a! = B) exit ("a<>b); if (c! = d) exit ("c<>d); if (e! = f) exit ("e<>f); echo "All conditions met";
The code is nicer and doesn't grow into huge nested constructs.
Sorry for the offtopic, but I wanted to share this find.
Now let's create an object and an archive.
$ zip = new ZipArchive (); if (! $ zip-> open ($ destination, ZIPARCHIVE :: CREATE)) (return false;)
where $ destination is the full path to the archive. If the archive has already been created, the files will be added to it.
$ zip-> addEmptyDir (str_replace ($ source. "/", "", $ file. "/"));
where $ source is the full path to our category (which we originally archived), $ file is the full path to the current folder. This is done so that there are no full paths in the archive, but only relative ones.
Adding a file works in a similar way, but you need to read it into a string first.
$ zip-> addFromString (str_replace ($ source. "/", "", $ file), file_get_contents ($ file));
At the end, you need to close the archive.
Return $ zip-> close ();
How to go through all the files and subdirectories in a folder, I think there is no need to explain. Google something like Recursive folder traversal in php
This option suited me
Function Zip ($ source, $ destination) (if (! Extension_loaded ("zip") ||! File_exists ($ source)) (return false;) $ zip = new ZipArchive (); if (! $ Zip-> open ( $ destination, ZIPARCHIVE :: CREATE)) (return false;) $ source = str_replace ("\\", "/", realpath ($ source)); if (is_dir ($ source) === true) ($ files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator ($ source), RecursiveIteratorIterator :: SELF_FIRST); foreach ($ files as $ file) ($ file = str_replace ("\\", "/", $ file); // Ignore "." and ".." folders if (in_array (substr ($ file, strrpos ($ file, "/") + 1), array (".", ".."))) continue; $ file = realpath ($ file ); $ file = str_replace ("\\", "/", $ file); if (is_dir ($ file) === true) ($ zip-> addEmptyDir (str_replace ($ source. "/", "" , $ file. "/"));) else if (is_file ($ file) === true) ($ zip-> addFromString (str_replace ($ source. "/", "", $ file), file_get_contents ($ file));))) else if (is_file ($ source) === true) ($ zip-> addFromString (basename ($ source), file_get_contents ($ source));) return $ zip-> close (); )
Yesterday on the forum I was asked about creating ZIP archives in PHP... I thought a little and realized that this topic would be of interest to a large number of people, because ZIP archiving in PHP a very popular topic. And in this article I will show an example, how a ZIP archive is created via a PHP script.
Let me give you an example right away create a zip archive, and then I will thoroughly comment on it:
$ zip = new ZipArchive (); // Create an object for working with ZIP archives
$ zip-> open ("archive.zip", ZIPARCHIVE :: CREATE); // Open (create) archive archive.zip
$ zip-> addFile ("index.php"); // Add the index.php file to the archive
$ zip-> addFile ("styles / style.css"); // Add the styles / style.css file to the archive
$ zip-> close (); // Finish working with the archive
?>
As a result of executing this script, ZIP archive, which will have the file at the root index.php and a directory will also be created styles where the file will be located style.css... I think this is all obvious and logical. And now I comment on what we did with you:
- Created an object ZipArchive using the constructor.
- Created an archive using the method open () object ZipArchive... We passed the name of the archive ( archive.zip) and constant ZIPARCHIVE :: CREATE, which tells if the archive does not exist, then it must be created.
- Method addFile () adds files to the archive. First, we added the file " index.php", which is located in the same directory as the script. Next, we added the file style.css, also pointing to it the right way relative to the script.
- Method close () ends work with the archive. Always do it to free up computer resources and avoid the most various problems related to the operation of this script and other scripts that need access to this archive.
In such a simple way you can create in automatic mode ZIP archives with using PHP ... In the next article we will analyze with you, how to extract ZIP archive via PHP.
Here are the most important news items we have published in 2008 on website.
Update (December 6th): Added missing zip security fix
There have been a great number of other additions and improvements since the last alpha, but here is a short overview of the most important changes:
- (documentation has been updated to the current state)
- ext / msql has been removed, while ext / ereg will now raise E_DEPRECATED notices
- ext / mhash has been replaced by ext / hash but full BC is maintained
- PHP now uses cc as the default compiler, instead of gcc
- A number of bug fixes to ext / pdo, ext / soap, the stream layer among others
Several under the hood changes also require in depth testing with existing applications to ensure that any backwards compatibility breaks are minimized.
We would love developers, designers, managers or anyone else with an interest in the PHP programming language to join us for what promises to be an awesome event at a very reasonable rate:
- Standard tickets: £ 60.00
- Early bird (until 8th November): £ 50.00
- Concessionary tickets: £ 35.00
* Confirmation with your company "s letter head
** With Student ID. Limited seating available
The purpose of this alpha release is to encourage users to not only actively participate in identifying bugs, but also in ensuring that all new features or necessary backwards compatibility breaks are noted in the documentation. Please report any findings to the or the.
There have been a great number of other additions and improvements, but here is a short overview of the most important changes:
- (documentation maybe out dated)
- Addition of the, (phar is scheduled for some more work a head of alpha2), and extensions
- Optional cyclic garbage collection
- Optional support for the MySQLnd replacement driver for libmysql
- Windows older than Windows 2000 (Windows 98, NT4, etc.) are not supported anymore ()
- New syntax features like, limited GOTO, ternary short cut "?:"
Several under the hood changes also require in depth testing with existing applications to ensure that any backwards compatibility breaks are minimized. This is especially important for users that require the undocumented Zend engine multibyte support.
Our top submitter Felix De Vliegher has actually committed his last submissions himself since, based on the high quality of his submissions, he has been granted commit rights to the PHP repository. We have not heard back from all participants, but we encourage everybody to blog about their experience and provide us with feedback on how to improve future events.
Now better late than never, here are the 10 winners of the promised elePHPant raffle sponsored by Nexen. Note that Felix asked me not to include him in the raffle, since he is already herding quite a number of elePHPants at home.
- Eric Stewart
- Håvard Eide
- Marc veldman
- Michelangelo van dam
- Rein Velt
- Rob young
- Sami greenbury
- Sebastian Deutsch
- Sebastian Schürmann
- Stefan Koopmanschap
We will provide Nexen with the email addresses of the winners, so that they can arrange to get the elePHPants shipped. Also for those people wondering, you can continue to submit tests on the. A bit thank you to all participants and TestFest organizers! Without the countless people that helped organize local events, implement the infrastructure and submissions reviewers, the TestFest would have obviously not worked out as well as it has. We will surely do similar events in the future based on the big success of TestFest 2008.
Security Enhancements and Fixes in PHP 5.2.6:
- Fixed possible stack buffer overflow in the FastCGI SAPI identified by Andrei Nigmatulin.
- Fixed integer overflow in printf () identified by Maksymilian Aciemowicz.
- Fixed security issue detailed in CVE-2008-0599 identified by Ryan Permeh.
- Fixed a safe_mode bypass in cURL identified by Maksymilian Arciemowicz.
- Properly address incomplete multibyte chars inside escapeshellcmd () identified by Stefan Esser.
- Upgraded bundled PCRE to version 7.6
The Internet Archive offers over 15,000,000 freely downloadable books and texts. There is also a collection of that may be borrowed by anyone with a free site account.
Alternatively, our portable Table Top Scanner can also be purchased and used on-site within libraries and archives. To read more about our TT Scribe, please visit.
Since 2005, the Internet Archive has collaborated and built digital collections with over 1,100 Library Institutions and other content providers. Partnerships include:, the and the. These collections are digitized from various mediatypes including:, and a wide variety of. Significant contributions have come from partners in North America (and Libraries), and, representing more than 184 languages.
The Internet Archive encourages our global community to contribute physical items, as well as uploading digital materials directly to the Internet Archive. If you have digital items that you would like to add to the Internet Archive, please a new item using the uploader interface. Click here to apply the specific creative commons license Creative Commons license to communicate how the material can be used.
For donation of physical books or items, please contact [email protected] site
Free to read, download, print, and enjoy. Some have restrictions on bulk re-use and commercial use, please see the collection or the sponsor of a book. By near-unrestricted access to these texts, we hope to encourage widespread use of texts in new contexts by people who might not have used them before.
If I ask you which standard WordPress page type you use the least, then most likely your answer will be the archive template. Or, more likely, you haven't even heard of the archive template at all - it's so unpopular. The reason is simple. Standard way the use of archives is far from being "user friendly".
Let's fix it today! Let's create a WordPress archives page that's really useful. The best part is that you can use these archives in any modern WordPress theme installed on your site. However, let's first understand what we mean by "archives page"?
History of WordPress archives
In WordPress, you work with tons of different templates and structural elements that come with the default configuration. If we look at the list of Twenty Fifteen default theme directories, we see the following:
- 404 error page
- Archives page (our guest today)
- Attached Images Page
- Index page (main page)
- Page template (for standard pages)
- Search results page
- Individual post and attachment pages
Despite their different purposes, these pages are all very similar in structure, and they often differ in only a few sections or a few lines of code. The only visible difference between an index page and an archive page is the extra heading at the top, which changes depending on the page you are viewing.
The idea behind the archive structure is to offer the blog administrator a convenient and easy way to display archives based on various criteria. After all, all of these various archive pages are just versions of the index page; they display content published in a specific time period, a specific author, with specific tags and categories.
Sounds good when viewed from a programmer's perspective, but it is not the most convenient approach from a user perspective. V this case one important level is missing - the level that lies between the user's intention to find content and individual elements of the archives.
This is what I mean. Currently, the only built-in way to display archived links on a WordPress site is via a widget. Thus, if you want to allow users to delve into archives, and you want to do this in a way that people can understand, you would have to dedicate the entire sidebar to one archives (just to reveal different types of structuring: archives by date, archives of categories, archives tags, copyright archives, etc.).
We need some kind of intermediary, some kind of page that will greet the visitor, explain to him that he is in the archive, and point out the content that he is interested in, or offer popular content.
It is for this reason that we decided to create a custom archives page.
How to create custom archives page in WordPress
Here's what we're going to do. Our custom archive page will be based on a custom page template. This template will allow us to do the following:
- Add custom post (can contain text, images, registration form, etc. - standard WordPress content).
- Display the last 15 entries (configurable)
- Display links to copyright archives
- Display links to archives by month
- Have additional widget areas (to display things like popular content, categories, tags).
Finally, the page will be responsive and usable on any site.
However, we really need to take some topic as a basis. I used the Zerif Lite theme. I confess that this is one of our own themes. However, it is one of the 10 most popular themes published last year in the WordPress theme directory. So I hope you will take advantage of it.
And yes, if you don’t like the topic, you don’t need to swear. You can use the approach presented in this article with any other topic.
Starting with the main file
The most best model to create an archive page is the page.php file of your current theme, for some reason:
- Its structure is already optimized for displaying arbitrary content within the main content block
- This is perhaps one of the simplest page templates in your theme structure.
Therefore, we will use the page.php file of the Zerif Lite theme. I will create a copy of it and name it tmpl_archives.php.
(Make sure you don't name the page page-archives.php. All filenames starting with "page-" will be treated as new templates pages within the main WordPress theme file hierarchy. This is why we used the tmpl_ prefix).
Let's change it to the following:
All this line does is pass the appropriate content file for our archives page.
You can remove other elements that appear to be redundant from your archive page (like comments, for example), but make sure to remove all elements that are relevant to the HTML structure. And overall, don't be afraid to experiment. After all, if something suddenly stops working, you can always go back to the previous code and easily debug it.
In addition, do not forget about the standard comment - the description of the template - which should be located at the very beginning of your file (in our case, in the tmpl_archives.php file):
In the end, we will be left with the following structure (some elements have been removed for convenience):
In this file, we will need to remove all unnecessary things, leaving only structural elements, as well as calls to basic WordPress functions:
The placeholder comment in the very middle of the code is where we will then insert our arbitrary elements.
Adding a custom greeting
This has already been taken care of by WordPress itself. We just need to insert the following line:
Adding new widget areas
Let's set up new widget areas in WordPress using a standard process. We'll do this with an additional function file to keep things reusable from theme to theme. We'll create a new file, archives-page-functions.php, put it in the main theme directory, and also register two new widget scopes:
If (! Function_exists ("archives_page_widgets_init")): function archives_page_widgets_init () (/ * First archive page widget, displayed to the LEFT. * / Register_sidebar (array ("name" => __ ("Archives page widget LEFT", "zerif -lite ")," description "=> __ (" This widget will be shown on the left side of your archive page. "," zerif-lite ")," id "=>" archives-left "," before_widget " => "
"," before_title "=>""," after_title "=>"
",)); / * Second archive page widget, displayed to the RIGHT. * / Register_sidebar (array (" name "=> __ (" Archives page widget RIGHT "," zerif-lite ")," description "=> __ ("This widget will be shown on the right side of your archive page.", "Zerif-lite"), "id" => "archives-right", "before_widget" => " "," before_title "=>""," after_title "=>"
",));) endif; add_action (" widgets_init "," archives_page_widgets_init ");If (! Function_exists ("archives_page_styles")): function archives_page_styles () (if (is_page_template ("tmpl_archives.php")) (wp_enqueue_style ("archives-page-style", get_template_directory_uri (). "/ Archives-page-style. css "); // standard way of adding style sheets in WP.)) endif; add_action ("wp_enqueue_scripts", "archives_page_styles");
This is a conditional queuing operation. It will only work if the visitor is viewing the archived page.
Remember to include our new archives-page-functions.php file by adding the following line to the very end of the current theme's functions.php file:
Require get_template_directory (). "/archives-page-functions.php";
Finally, the new block we'll be using in our main content-tmpl_archives.php file is pretty simple. Place the following code below the the_content (); call:
All we now have to do is take care of the only missing file, archives-page-style.css. However, let's leave it for later, as we will use it as a repository for all the styles of our custom archive page, including for widgets.
Displaying the last 15 records
For this we need to do some PHP manual coding. Even though the output of posts can be implemented using a variety of widgets, let's avoid the monotony and dive into the coding to demonstrate more of the different possibilities.
You are probably asking why exactly 15 entries? I don't know, I just took this number from the ceiling. Let's make it customizable with custom fields.
Here's what we'll do:
- Set the number of posts via the custom archived-posts-no field.
- If the number is not correct, the template will use the default value of the last 15 records.
Below is the code that does this. Place it below the previous section in the content-tmpl_archives.php file, which handles the new widget areas.
ID, "archived-posts-no", true)); / * Here, we "re making sure that the number fetched is reasonable. In case it" s higher than 200 or lower than 2, we "re just resetting it to the default value of 15. * / if ($ how_many_last_posts> 200 || $ how_many_last_posts< 2) $how_many_last_posts = 15; $my_query = new WP_Query("post_type=post&nopaging=1"); if($my_query->have_posts ()) (echo "
"; echo"
- "; $ counter = 1; while ($ my_query-> have_posts () && $ counter<= $how_many_last_posts) {
$my_query->the_post (); ?>
- ">
All this code does is get the value of a custom field, sets the number of records to display, and then fetches those records from the database using WP_Query () ;. I also use some Font Awesome icons to add some charm to this block.
Displaying links to copyright archives
This section is only useful if you are running a multi-author blog. Skip this if you have one author.
This functionality can be implemented with a simple block of code that needs to be placed in our content-tmpl_archives.php file (below the previous block):
Our Authors
We'll move on to styles in a couple of minutes. For now, notice that everything is done with a call to the wp_list_authors () function.
Displaying links to archives by month
I added this element at the very end, as it is not the most useful component from the point of view of readers. However, it is important to have it on the archive page so that you don't have to use widgets to display monthly archives elsewhere on the site.
This is how it will look in the content-tmpl_archives.php file:
By Month
In this case, we will display it as a separate paragraph with entries separated by forward slashes (|).
Complete Archive Page Template
Let's take a look at the complete content-tmpl_archives.php file, which is our main file for outputting an arbitrary archive:
Last ". $ How_many_last_posts." Posts
"; echo" "; $ counter = 1; while ($ my_query-> have_posts () && $ counter<= $how_many_last_posts) {
$my_query->the_post (); ?>
Our Authors
By Month
Style sheet
Finally, let's take a look at the stylesheet. This is what the archives-page-style.css file looks like:
Archives-widget-left (float: left; width: 50%;) .archives-widget-right (float: left; padding-left: 4%; width: 46%;) .archives-latest-section () .archives -latest-section ol (font-style: italic; font-size: 20px; padding: 10px 0;) .archives-latest-section ol li (padding-left: 8px;) .archives-authors-section () .archives -authors-section ul (list-style: none; text-align: center; border-top: 1px dotted # 888; border-bottom: 1px dotted # 888; padding: 10px 0; font-size: 20px; margin: 0 0 20px 0;) .archives-authors-section ul li (display: inline; padding: 0 10px;) .archives-authors-section ul li a (text-decoration: none;) .archives-by-month-section ( ext-align: center; word-spacing: 5px;) .archives-by-month-section p (border-top: 1px dotted # 888; border-bottom: 1px dotted # 888; padding: 15px 0;) .archives- by-month-section pa (text-decoration: none;) @media only screen and (max-width: 600px) (.archives-widget-left (width: 100%;) .archives-widget -right (width: 100%; ))
Most of the styles are about fonts and a few structural elements, with the exception of a couple of alignments and a responsive design block at the end.
Let's see how it will look in practice. Here's a site that has a ton of content in the archive:
How to integrate this template into any theme
The custom archives page we created here is for the Zerif Lite theme, which is available in the official WordPress directory. However, as I said, it can be used in conjunction with any theme. Here's how to do it:
- We take the archives-page-style.css and archives-page-functions.php files that we created in the tutorial and then place them in the main directory of the theme.
- Edit the theme's functions.php and add the following line at the very end: require get_template_directory (). '/Archives-page-functions.php';
- We take the theme's page.php file, make a copy of it, rename it, change the call to the get_template_part () function to get_template_part ('content', 'tmpl_archives');, and then add a descriptive comment at the very beginning: / * Template Name: Archive Page Custom * /.
- We take the content-page.php file of your theme, make a copy of it, rename it to content-tmpl_archives.php, and add all the arbitrary blocks that we created in the tutorial to it, just below the call to the_content (); function.
- We test and enjoy.
This is how it would look in the default Twenty Fifteen theme: