Create a quick sinking portfolio using WordPress
Sep 05, 2023 am 09:09 AMToday you'll harness the magic of Razorjack's Quicksand to turn your simple portfolio into something amazing.
Introduction
Ever wanted to use the jQuery plugin Quicksand? Ever tried to do it with WordPress? But is discovering both a nightmare? Well, I’m going to help you go from a blank WordPress theme to a beautiful custom portfolio using Quicksand with a simple step-by-step guide. I will be using a custom theme that has been streamlined with WordPress 3.0 for the purposes of this tutorial.
So open your favorite text editor and let’s get started!
Step 1Create Post Type
With WordPress we are able to create custom post types where we can manage all our content. We will create a custom post type to store all of our portfolio items in a dedicated admin section.
To facilitate code management, we first create a folder named portfolio and a PHP file named portfolio-post-types.php (or whatever you think is appropriate document).
After creating the file, let's add some code...
Let’s start by creating a function:
<?php // function: post_type BEGIN function post_type() { // We will fill this function in the next step } // function: post_type END
Now that we have created the blank function, let's add some code to make this function perform some special operations. First, create tags for our custom post type. Insert the following code into our post_type function:
$labels = array( 'name' => __( 'Portfolio'), 'singular_name' => __('Portfolio'), 'rewrite' => array( 'slug' => __( 'portfolio' ) ), 'add_new' => _x('Add Item', 'portfolio'), 'edit_item' => __('Edit Portfolio Item'), 'new_item' => __('New Portfolio Item'), 'view_item' => __('View Portfolio'), 'search_items' => __('Search Portfolio'), 'not_found' => __('No Portfolio Items Found'), 'not_found_in_trash' => __('No Portfolio Items Found In Trash'), 'parent_item_colon' => '' );
Breakdown of the code we just wrote:
The "labels" variable is an array of strings representing your post types, each string is the text output by a specific function.
-
name
– The plural form of the post type name. -
singular_name
– The singular form of the post type name. -
rewrite
– Rewrite permalinks using this format. -
add_new
– Menu item for adding a new post. -
edit_item
– The title displayed when editing a post. -
new_item
– Displayed in the favorites menu of the admin title. -
view_item
– Appears next to the permalink on the edit post screen. -
search_items
– Button text for the search box on the edit post screen. -
not_found
– Text displayed when a post is not found by searching in the admin. -
not_found_in_trash
– Text displayed when there are no posts in the trash. -
parent_item_colon
– used as the label for the parent post on the edit post screen. Only useful for hierarchical post types.
Next, create the parameters for our custom post type. Insert the following code into our post_type function:
$args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'menu_position' => null, 'supports' => array( 'title', 'editor', 'thumbnail' ) );
-
labels
– Array of labels for this post type. -
public
– Meta-parameters used to define default values ??for public_queriable, show_ui, show_in_nav_menus, and except_from_search. -
publicly_queryable
– Whether the front end can perform post type queries. -
show_ui
– Whether to generate the default user interface for managing this post type. -
query_var
– False to block queries, or the string value of the query variable to use for this post type. -
rewrite
– Rewrite permalinks using this format. -
capability_type
– String used to build read, edit, and delete capabilities. -
hierarchical
– Whether the post type is hierarchical. Allows parent to be specified. -
menu_position
– The position where the post type should appear in the menu order in the admin. -
supports
– Alias ??for calling add_post_type_support() directly.
Learn more about add_post_type_support in the WordPress Codex
Now that our post type is set up, we need to register the post type. We register the post type by inserting the following code into the post_type function:
register_post_type(__( 'portfolio' ), $args);
Format custom post type output
We have now created a custom post type. Let's format the output so we get a user-friendly message. First create another function in our portfolio-post-type.php file.
// function: portfolio_messages BEGIN function portfolio_messages($messages) { $messages[__( 'portfolio' )] = array( 0 => '', 1 => sprintf(('Portfolio Updated. <a href="%s">View portfolio</a>'), esc_url(get_permalink($post_ID))), 2 => __('Custom Field Updated.'), 3 => __('Custom Field Deleted.'), 4 => __('Portfolio Updated.'), 5 => isset($_GET['revision']) ? sprintf( __('Portfolio Restored To Revision From %s'), wp_post_revision_title((int)$_GET['revision'], false)) : false, 6 => sprintf(__('Portfolio Published. <a href="%s">View Portfolio</a>'), esc_url(get_permalink($post_ID))), 7 => __('Portfolio Saved.'), 8 => sprintf(__('Portfolio Submitted. <a target="_blank" href="%s">Preview Portfolio</a>'), esc_url( add_query_arg('preview', 'true', get_permalink($post_ID)))), 9 => sprintf(__('Portfolio Scheduled For: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Portfolio</a>'), date_i18n( __( 'M j, Y @ G:i' ), strtotime($post->post_date)), esc_url(get_permalink($post_ID))), 10 => sprintf(__('Portfolio Draft Updated. <a target="_blank" href="%s">Preview Portfolio</a>'), esc_url( add_query_arg('preview', 'true', get_permalink($post_ID)))), ); return $messages; } // function: portfolio_messages END
What we just did is create a function called portfolio_messages that accepts a parameter called $messages
. Next, we create a variable to store an array of all messages. We leave "0" blank in the array because our message index starts at 1. And then finally return our array to our function.
Create Category
Finally, we need to create our taxonomy. First create another function called portfolio_filter and enter the following code:
// function: portfolio_filter BEGIN function portfolio_filter() { register_taxonomy( __( "filter" ), array(__( "portfolio" )), array( "hierarchical" => true, "label" => __( "Filter" ), "singular_label" => __( "Filter" ), "rewrite" => array( 'slug' => 'filter', 'hierarchical' => true ) ) ); } // function: portfolio_filter END
我們首先注冊(cè)我們的分類法,然后將分類法應(yīng)用于我們的自定義帖子類型組合。接下來(lái),我們應(yīng)用分類法的最終設(shè)置并輸入創(chuàng)建的標(biāo)簽。我們創(chuàng)建分類法的原因是因?yàn)槲覀冊(cè)谑褂?Quicksand 對(duì)投資組合進(jìn)行排序時(shí)將使用它作為參考鍵。
現(xiàn)在我們所有的自定義帖子類型以及正確的格式和我們自己的分類法都已完成,我們需要最終初始化所有代碼,以便它將顯示在管理中。首先,我們?cè)谖募撞刻砑右韵麓a:
add_action( 'init', 'post_type' ); add_action( 'init', 'portfolio_filter', 0 ); add_filter( 'post_updated_messages', 'portfolio_messages' );
輸入此內(nèi)容后,我們需要打開 functions.php 文件并插入以下代碼行:
include("portfolio/portfolio-post-types.php");
我們需要將自定義組合類型包含到 functions.php 文件中,以便在調(diào)用 WordPress 主題的函數(shù)時(shí)運(yùn)行腳本?,F(xiàn)在,您將在管理面板中看到一個(gè)標(biāo)題為投資組合的部分,其中包含 3 個(gè)子導(dǎo)航項(xiàng),分別稱為“投資組合”、“添加項(xiàng)目”和“過(guò)濾器”。
第 2 步創(chuàng)建投資組合頁(yè)面
現(xiàn)在我們已經(jīng)完成了整個(gè)投資組合設(shè)置,我們需要輸出我們的投資組合項(xiàng)目。我們首先創(chuàng)建一個(gè)名為 portfolio.php 的新 PHP 文件。首先,讓我們添加一些創(chuàng)建頁(yè)面模板的要點(diǎn):
<?php /* Template Name: Portfolio */ ?> <?php get_header(); ?> <!-- #content BEGIN? --> <div id="content" class="clearfix"> // We will add our content later </div><!-- #content END --> <?php get_footer(); ?>
現(xiàn)在,我們已經(jīng)創(chuàng)建了基本頁(yè)面模板,我們需要填充我們的投資組合。我們需要首先創(chuàng)建一個(gè)頁(yè)面作為我們的投資組合頁(yè)面,因此請(qǐng)前往儀表板中的頁(yè)面 -> 添加新內(nèi)容。在右側(cè),您將看到一個(gè)標(biāo)題為頁(yè)面屬性的框,其中包含默認(rèn)模板的下拉菜單,選擇您想要在我們的案例中使用的所需模板應(yīng)選擇 >portfolio,然后選擇發(fā)布。
顯示過(guò)濾器
現(xiàn)在,讓我們返回編輯我們的投資組合頁(yè)面模板并開始為我們的投資組合插入過(guò)濾器。首先,我們首先將過(guò)濾器包裝在無(wú)序列表中,每個(gè)類別都將是列表中的一個(gè)元素。
<ul class="filter clearfix"> <li><strong>Filter:</strong></li> <li class="active"><a href="javascript:void(0)" class="all">All</a></li> </ul>
讓我們向過(guò)濾器添加一些 PHP,以自動(dòng)生成在我們的產(chǎn)品組合中使用的過(guò)濾器類別。
<?php $terms = get_terms('filter', $args); $count = count($terms); $i=0; if ($count > 0) { foreach ($terms as $term) { $i++; $term_list .= '<li><a href="javascript:void(0)" class="'. $term->slug .'">' . $term->name . '</a></li>'; if ($count != $i) { $term_list .= ''; } else { $term_list .= ''; } } echo $term_list; } ?>
我們?cè)谶@里所做的首先是初始化我們希望獲得的分類法,在我們的例子中是過(guò)濾器。其次,為我們的類別設(shè)置一個(gè)計(jì)數(shù),以便我們?cè)谶^(guò)濾器中的每個(gè)元素上遞增,然后應(yīng)用條件語(yǔ)句來(lái)檢查我們?cè)O(shè)置的計(jì)數(shù)是否小于 0;這意味著如果過(guò)濾器中沒(méi)有類別或沒(méi)有為投資組合項(xiàng)目分配類別,則不會(huì)輸出任何內(nèi)容。如果我們的過(guò)濾器中有類別,那么我們想要更改每個(gè)元素的輸出。
我們通過(guò)代碼段中的以下行來(lái)完成此操作:
$term_list .= '<li><a href="javascript:void(0)" class="'. $term->slug .'">' . $term->name . '</a></li>';
我們正在創(chuàng)建一個(gè)列表元素以適合我們的無(wú)序列表,然后將“href”設(shè)置為空白目標(biāo),因?yàn)?Quicksand 將處理內(nèi)容的組織,然后我們將類名設(shè)置為投資組合項(xiàng)目的 slug一致的引用,最后在我們的過(guò)濾器中輸出類別的名稱。
顯示投資組合項(xiàng)目
太棒了,我們現(xiàn)在實(shí)現(xiàn)了動(dòng)態(tài)過(guò)濾器?,F(xiàn)在我們要輸出我們的投資組合項(xiàng)目。讓我們開始查詢我們的數(shù)據(jù)庫(kù),以獲取投資組合帖子類型的所有帖子并設(shè)置我們的 WordPress 循環(huán)。我們首先設(shè)置一個(gè)新的 WP_Query 對(duì)象并向其傳遞正確的參數(shù)。
<?php $wpbp = new WP_Query(array( 'post_type' => 'portfolio', 'posts_per_page' =>'-1' ) ); ?>
我們將 WP_Query 對(duì)象分配給一個(gè)變量,以便在初始化循環(huán)時(shí)可以引用我們的查詢。我們將帖子類型設(shè)置為 portfolio,因此我們只查詢之前創(chuàng)建的自定義帖子類型,最后將 posts_per_page 設(shè)置為 -1。我們使用-1,這樣每頁(yè)的帖子數(shù)量沒(méi)有固定的限制,因此顯示所有投資組合項(xiàng)目,如果我們?cè)敢?,我們也可以輸入任何?shù)字,它只會(huì)顯示此處輸入的投資組合項(xiàng)目的數(shù)量。< /p>
現(xiàn)在我們有了一個(gè)可以引用的查詢對(duì)象,讓我們?cè)O(shè)置循環(huán)來(lái)輸出我們的投資組合項(xiàng)目。我們首先插入以下代碼:
<?php if ($wpbp->have_posts()) : while ($wpbp->have_posts()) : $wpbp->the_post(); ?> <?php // All of our portfolio content will be inserted in here... ?> <?php endwhile; endif; ?> <?php wp_reset_query(); ?>
在開始將內(nèi)容輸入循環(huán)之前,我們將設(shè)置特色圖像。打開您的 functions.php 文件,我們將為每個(gè)投資組合項(xiàng)目添加一些要輸出的自定義特色圖像尺寸。
我們首先檢查當(dāng)前版本的 WordPress 是否支持特色圖片功能,然后設(shè)置一些常規(guī)設(shè)置以使其正常工作。我們添加了對(duì)后縮略圖的支持,并將默認(rèn)尺寸設(shè)置為 56 像素 x 56 像素。
if ( function_exists( 'add_theme_support' ) ) { add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 56, 56, true ); }
然后我們要添加我們自己的自定義縮略圖大小。在下面一行插入以下代碼:set_post_thumbnail_size
add_image_size( 'portfolio', 295, 150, true );
此方法允許您創(chuàng)建自己的縮略圖大小,方法是首先設(shè)置縮略圖的參考名稱,然后設(shè)置寬度和高度,最后設(shè)置縮略圖是否應(yīng)硬裁剪圖像以適合指定的大小。您可以更改特色圖像的尺寸以適合您的布局;為了本教程的目的,我有一個(gè) 3 列網(wǎng)格布局。
現(xiàn)在我們已經(jīng)設(shè)置了特色圖像,我們將返回我們的投資組合頁(yè)面模板并輸出投資組合項(xiàng)目特色圖像。
由于每個(gè)投資組合項(xiàng)目的組織最好通過(guò)無(wú)序列表處理,因此我們將首先創(chuàng)建一個(gè),然后輸出我們剛剛設(shè)置的特色圖像。在 WordPress 循環(huán)中插入以下代碼:
<ul class="filterable-grid clearfix"> <li> <?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) : ?> <?php the_post_thumbnail('portfolio'); ?> <?php endif; ?> <p><a href="<?php the_permalink(); ?>"><?php echo get_the_title(); ?></a></p> </li> </ul>
我們首先檢查主題是否支持縮略圖功能。如果主題支持此功能,那么它將在我們之前指定的專用縮略圖上輸出特征圖像。輸出特色圖像后,我們將作品集項(xiàng)目的標(biāo)題直接輸出在圖像下方。
連接投資組合項(xiàng)目和過(guò)濾器
我們需要調(diào)整每個(gè)投資組合列表項(xiàng)的不同元素,以確保每個(gè)投資組合的引用對(duì)于該項(xiàng)目分配到的類別是正確的。為此,我們首先需要從分類中獲取類別。在循環(huán)中插入以下代碼:
<?php $terms = get_the_terms( get_the_ID(), 'filter' ); ?>
接下來(lái),我們將向列表元素(li
)添加一些屬性。我們首先將 data-id
添加到列表項(xiàng)中,為每個(gè)投資組合項(xiàng)提供唯一的標(biāo)識(shí)。我們還將添加一個(gè) data-type
;這將作為我們對(duì)過(guò)濾器的引用。讓我們用以下代碼替換我們的起始列表元素 (li
):
<li data-id="id-<?php echo $count; ?>" data-type="<?php foreach ($terms as $term) { echo strtolower(preg_replace('/\s+/', '-', $term->name)). ' '; } ?>">
我們對(duì) data-id
應(yīng)用計(jì)數(shù),當(dāng)循環(huán)遍歷每個(gè)項(xiàng)目時(shí),計(jì)數(shù)將會(huì)增加(我們很快就會(huì)添加計(jì)數(shù))。然后,我們循環(huán)分類法中的每個(gè)類別,并應(yīng)用正則表達(dá)式來(lái)查找空格,并將其替換為“-”以匹配該類別的子句,最后在末尾添加一個(gè)空格,這樣我們就可以應(yīng)用一個(gè)投資組合項(xiàng)目有多個(gè)類別。
最后,我們將確保增加計(jì)數(shù)并為每個(gè)投資組合項(xiàng)目提供唯一的參考。我們需要在結(jié)束循環(huán)之前添加以下代碼:
<?php $count++; ?>
顯示投資組合的最終代碼
<ul class="filterable-grid clearfix"> <?php $wpbp = new WP_Query(array( 'post_type' => 'portfolio', 'posts_per_page' =>'-1' ) ); ?> <?php if ($wpbp->have_posts()) : while ($wpbp->have_posts()) : $wpbp->the_post(); ?> <?php $terms = get_the_terms( get_the_ID(), 'filter' ); ?> <li data-id="id-<?php echo $count; ?>" data-type="<?php foreach ($terms as $term) { echo strtolower(preg_replace('/\s+/', '-', $term->name)). ' '; } ?>"> <?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) : ?> <?php the_post_thumbnail('portfolio'); ?> <?php endif; ?> <p><a href="<?php the_permalink(); ?>"><?php echo get_the_title(); ?></a></p> </li> <?php $count++; ?> <?php endwhile; endif; ?> <?php wp_reset_query(); ?> </ul>
第 3 步 jQuery 和 Quicksand
我們現(xiàn)在正在取得進(jìn)展,但在繼續(xù)之前我們需要下載一些 jQuery 腳本。我們需要下載以下腳本:
- jQuery 1.7(WordPress 3.3.1 附帶的版本)
- Quicksand 插件(來(lái)自 GitHub 的最新版本)
- 緩動(dòng)插件(版本1.3)
我們還需要?jiǎng)?chuàng)建一個(gè) JavaScript 文件來(lái)處理我們將很快編寫的所有自定義 jQuery。因此,讓我們創(chuàng)建一個(gè)名為 jquery.custom.js 的空白 JavaScript 文件?,F(xiàn)在我們已經(jīng)擁有了所有必要的腳本,讓我們打開 functions.php 并創(chuàng)建一個(gè)名為 register_js 的空白函數(shù)。一旦我們有了空白函數(shù),我們將使用 wp_register_script 和 wp_enqueue_script 方法插入腳本。首先,我們必須檢查我們是否不在管理員中,以確保腳本僅在前端加載。將以下代碼插入到我們的函數(shù)中:
// Register our scripts function register_js() { if ( !is_admin() ) { wp_register_script( 'quicksand', get_template_directory_uri() . '/js/jquery.quicksand.js', 'jquery' ); wp_register_script( 'easing', get_template_directory_uri() . '/js/jquery.easing.1.3.js', 'jquery' ); wp_register_script( 'custom', get_template_directory_uri() . '/js/jquery.custom.js', 'jquery', '1.0', true ); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'quicksand' ); wp_enqueue_script( 'easing' ); wp_enqueue_script( 'custom' ); } }
首先,使用wp_register_script,我們指定一個(gè)句柄作為第一個(gè)參數(shù)以供在排隊(duì)腳本時(shí)參考,然后將腳本的源鏈接添加為我們的第二個(gè)參數(shù)(這適用于腳本的每次注冊(cè)) 。我們還指定 jquery 作為依賴項(xiàng),以便在將腳本排入隊(duì)列時(shí)加載 WordPress 包含的 jQuery 版本。
注冊(cè)完所有腳本后,我們將使用 wp_enqueue_script 將它們排入隊(duì)列。我們傳遞注冊(cè)時(shí)使用的所有句柄作為引用來(lái)排隊(duì)我們的腳本。最后,我們需要通過(guò)在 functions.php 文件中添加以下代碼來(lái)初始化我們的函數(shù):
add_action('init', 'register_js');
書寫流沙
現(xiàn)在我們已經(jīng)準(zhǔn)備好了所有腳本,我們可以開始編寫 jQuery 自定義腳本來(lái)處理流沙。讓我們打開 jquery.custom.js 腳本,并通過(guò)插入以下代碼來(lái)設(shè)置環(huán)境:
jQuery(document).ready(function() { // We will insert our quicksand script in here }); // END OF DOCUMENT
現(xiàn)在我們有了腳本結(jié)構(gòu),我們將創(chuàng)建一個(gè)名為 portfolio_quicksand 的函數(shù),并且僅在 Quicksand 插件存在時(shí)才執(zhí)行。
function portfolio_quicksand() { // All of our quicksand handling will happen in this function } if(jQuery().quicksand) { portfolio_quicksand(); }
我將把以下內(nèi)容分解為更小的步驟,以便您了解創(chuàng)建流沙投資組合時(shí)發(fā)生的所有事情。讓我們從設(shè)置變量開始。將以下代碼插入到我們的 portfolio_quicksand 函數(shù)中:
var $filter; var $container; var $containerClone; var $filterLink; var $filteredItems;
我們將更頻繁地使用這些變量,因此這始終是為變量設(shè)置奠定堅(jiān)實(shí)基礎(chǔ)的好方法。接下來(lái)我們將分配變量:
$filter = $('.filter li.active a').attr('class'); $filterLink = $('.filter li a'); $container = $('ul.filterable-grid'); $containerClone = $container.clone();
我們首先將過(guò)濾器設(shè)置為投資組合頁(yè)面模板中的無(wú)序列表類。其次,我們?cè)O(shè)置一個(gè)filterLink;這將充當(dāng)我們?cè)谶^(guò)濾器中單擊的項(xiàng)目。然后我們需要分配我們的投資組合項(xiàng)目的容器,最后我們需要容器的克隆版本,以使用 Quicksand 操作數(shù)據(jù)。
接下來(lái),我們將編寫點(diǎn)擊函數(shù),因此當(dāng)用戶選擇一個(gè)類別時(shí),應(yīng)該操作容器并顯示內(nèi)容的輸出。讓我們首先調(diào)用 filterLink 上的點(diǎn)擊函數(shù):
$filterLink.click(function(e) { // We will add the content for this function now... });
現(xiàn)在讓我們處理列表元素的活動(dòng)狀態(tài)。我們首先刪除具有當(dāng)前活動(dòng)狀態(tài)的任何類,然后搜索過(guò)濾器并將過(guò)濾器拆分為單獨(dú)的項(xiàng)目,最后將活動(dòng)類應(yīng)用于單擊的項(xiàng)目(類別):
$('.filter li').removeClass('active'); $filter = $(this).attr('class').split(' '); $(this).parent().addClass('active');
這在設(shè)計(jì)過(guò)濾器樣式時(shí)會(huì)有所幫助,因?yàn)槟鷮⒛軌蛟谟脩暨x擇類別時(shí)提供活動(dòng)狀態(tài)。
接下來(lái),我們將處理數(shù)據(jù)過(guò)濾的條件。我們首先檢查是否已選擇全部。如果選擇了全部,則顯示容器內(nèi)的所有元素,否則顯示容器內(nèi)已被過(guò)濾器選擇的項(xiàng)目。
以前,當(dāng)我們創(chuàng)建投資組合頁(yè)面模板時(shí),我們?yōu)槊總€(gè)投資組合項(xiàng)目分配了 data-type
,我們將在此處使用它作為參考鍵來(lái)查找所選數(shù)據(jù)。
if ($filter == 'all') { $filteredItems = $containerClone.find('li'); } else { $filteredItems = $containerClone.find('li[data-type~=' + $filter + ']'); }
最后,我們調(diào)用 Quicksand 方法,并傳遞 filteredItems 和所有動(dòng)畫選項(xiàng):
$container.quicksand($filteredItems, { duration: 750, easing: 'easeInOutCirc', adjustHeight: 'dynamic' });
流沙的最終代碼
function portfolio_quicksand() { // Setting up our variables var $filter; var $container; var $containerClone; var $filterLink; var $filteredItems // Set our filter $filter = $('.filter li.active a').attr('class'); // Set our filter link $filterLink = $('.filter li a'); // Set our container $container = $('ul.filterable-grid'); // Clone our container $containerClone = $container.clone(); // Apply our Quicksand to work on a click function // for each of the filter li link elements $filterLink.click(function(e) { // Remove the active class $('.filter li').removeClass('active'); // Split each of the filter elements and override our filter $filter = $(this).attr('class').split(' '); // Apply the 'active' class to the clicked link $(this).parent().addClass('active'); // If 'all' is selected, display all elements // else output all items referenced by the data-type if ($filter == 'all') { $filteredItems = $containerClone.find('li'); } else { $filteredItems = $containerClone.find('li[data-type~=' + $filter + ']'); } // Finally call the Quicksand function $container.quicksand($filteredItems, { // The duration for the animation duration: 750, // The easing effect when animating easing: 'easeInOutCirc', // Height adjustment set to dynamic adjustHeight: 'dynamic' }); }); }
第 4 步燈箱集成(額外)
令人驚奇的是,您現(xiàn)在應(yīng)該擁有一個(gè)功能齊全的流沙投資組合,但我們不能僅限于此。我要添加一個(gè)額外的功能,這是完全可選的,但它可能成為我最喜歡的功能,那就是燈箱。我們將使用名為 PrettyPhoto 的 jQuery 插件來(lái)集成 Lightbox。
我們要做的第一件事是下載 PrettyPhoto 插件。
- PrettyPhoto v3(或最新版本)
下載 PrettyPhoto 文件后,我們將首先復(fù)制 PrettyPhoto 圖像,該圖像位于 images 文件夾中,然后您需要復(fù)制標(biāo)題為 PrettyPhoto 的文件夾> 進(jìn)入我們的主題。我們還需要復(fù)制 CSS 和 PrettyPhoto 的 JavaScript 文件,因此讓我們將它們復(fù)制到主題中的相應(yīng)文件夾中。
現(xiàn)在我們已經(jīng)準(zhǔn)備好了所有文件,我們需要在主題中初始化它們。在我們的 functions.php 文件中,我們將創(chuàng)建另一個(gè)函數(shù)來(lái)處理我們的樣式,我們將調(diào)用該函數(shù) register_css。然后我們將注冊(cè)我們的樣式并將我們的樣式排入隊(duì)列,從而將以下代碼插入到您的 functions.php 文件中:
// Register our styles function register_css() { if (!is_admin()) { wp_register_style( 'prettyPhoto', get_template_directory_uri() . '/css/prettyPhoto.css' ); wp_enqueue_style( 'prettyPhoto' ); } } add_action( 'init', 'register_css' );
我們已準(zhǔn)備好所有文件,并且它們正在由我們的主題初始化?,F(xiàn)在我們需要利用它并將 Lightbox 實(shí)現(xiàn)到我們的主題中。讓我們打開 portfolio.php(作品集頁(yè)面模板)并向我們的特色圖片添加一些代碼。
首先,我們需要獲取已設(shè)置的特色圖片的大圖。當(dāng)用戶單擊圖像并加載 PrettyPhoto 時(shí),這將充當(dāng)全尺寸圖像。在 WordPress 循環(huán)中,我們需要插入以下代碼:
<?php $large_image =?wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'fullsize', false, '' ); $large_image = $large_image[0]; ?>
我們插入的代碼將在循環(huán)中查找當(dāng)前帖子,并找到圖像的原始來(lái)源,然后找到圖像的全尺寸版本。返回全尺寸圖像后,我們將強(qiáng)制將圖像存儲(chǔ)在數(shù)組索引 0 中。這用于不覆蓋或與全尺寸圖像重復(fù)。
一旦我們可以訪問(wèn)完整尺寸的圖像,我們現(xiàn)在將在我們的特色圖像上初始化 PrettyPhoto。以下代碼會(huì)將全尺寸圖像鏈接到投資組合項(xiàng)目的特色圖像,并將引用傳遞給 PrettyPhoto,將您創(chuàng)建特色圖像的代碼替換為以下內(nèi)容:
<a rel="prettyPhoto[gallery]" href="<?php echo $large_image ?>"><?php the_post_thumbnail('portfolio'); ?></a>
太棒了,我們已經(jīng)準(zhǔn)備好所有文件和腳本,我們已經(jīng)獲得了特色圖像的全尺寸圖像,并且我們已經(jīng)使用 PrettyPhoto 將我們的特色圖像引用到了我們的全尺寸圖像。接下來(lái),我們需要編寫 JavaScript 以使燈箱出現(xiàn)并工作。
讓我們回到 jquery.custom.js 文件并創(chuàng)建另一個(gè)空白函數(shù)來(lái)處理 PrettyPhoto:
function lightbox() { // Our Lightbox functioning will be added now... } if(jQuery().prettyPhoto) { lightbox(); }
現(xiàn)在我們有了函數(shù),我們將初始化 PrettyPhoto。我們通過(guò)在 Lightbox 函數(shù)中添加以下代碼來(lái)實(shí)現(xiàn)此目的:
jQuery("a[rel^='prettyPhoto']").prettyPhoto({ animationSpeed:'fast', slideshow:5000, theme:'pp_default', show_title:false, overlay_gallery: false, social_tools: false });
您可以在以下位置閱讀 PrettyPhoto 在使用該插件時(shí)接受的所有參數(shù)的完整文檔:PrettyPhoto jQuery Lightbox Clone
所以,一切都完成了! Lightbox 實(shí)現(xiàn)到您的 WordPress 主題中,但等一下,讓我猜猜您何時(shí)單擊過(guò)濾器并使用 Quicksand;燈箱不再工作。這是因?yàn)槲覀冃枰?Quicksand 腳本并傳遞一小段代碼,以確保 Lightbox 即使在我們過(guò)濾投資組合時(shí)也能正常工作。
因此,讓我們通過(guò)將以下腳本添加到 jquery.custom.js 文件中的 portfolio_quicksand 函數(shù)來(lái)解決這個(gè)小問(wèn)題:
$container.quicksand($filteredItems, function () { lightbox(); } );
我們?cè)谶@里所做的是再次調(diào)用 Quicksand 插件,并將此調(diào)用中的函數(shù)傳遞給我們的 Lightbox 函數(shù)。因此,每次 Quicksand 過(guò)濾內(nèi)容時(shí),都會(huì)調(diào)用 Lightbox 函數(shù),將 PrettyPhoto 應(yīng)用于每個(gè)圖像。
第5步分頁(yè)集成(額外)
許多人喜歡使用 Quicksand,但有些人喜歡在其作品集中同時(shí)使用 Quicksand 和分頁(yè)。這是在您的投資組合中創(chuàng)建分頁(yè)的另一個(gè)額外功能。我將使用 WordPress 插件:WP_PageNavi。
讓我們首先安裝并激活該插件。前往我們管理部分的插件->添加新頁(yè)面并搜索WP_PageNavi,找到后單擊立即安裝并激活插件< /strong> 安裝后。
現(xiàn)在我們已經(jīng)完成了插件設(shè)置,讓我們打開我們的作品集頁(yè)面模板并對(duì)我們的文件進(jìn)行一些修改。
首先,我們需要設(shè)置頁(yè)面以允許分頁(yè)。我們通過(guò)在查詢數(shù)據(jù)庫(kù)之前插入以下代碼段來(lái)實(shí)現(xiàn)此目的:
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
初始化分頁(yè)后,我們需要修改數(shù)據(jù)庫(kù)查詢。我們將 post_per_page 更改為一個(gè)數(shù)字,以顯示每個(gè)頁(yè)面上顯示的最大帖子數(shù)。然后,我們將一個(gè)新參數(shù)傳遞給查詢paged,并將其引用到我們的代碼段,該代碼段允許我們對(duì)頁(yè)面進(jìn)行分頁(yè),如以下代碼所示:
$wpbp = new WP_Query(array( 'post_type' => 'portfolio', 'posts_per_page' =>'2', 'paged' => $paged ) );
太棒了,我們有一個(gè)帶分頁(yè)的作品集。我們只需要一些控件來(lái)幫助我們進(jìn)行每個(gè)頁(yè)面的導(dǎo)航。以下代碼檢查是否安裝了 WP_PageNavi 插件,然后使用作為參數(shù)傳遞的數(shù)據(jù)庫(kù)查詢來(lái)初始化 wp_pagenavi。然后,我們重置帖子數(shù)據(jù),所有內(nèi)容都正確分頁(yè)。
<?php if(function_exists('wp_pagenavi')) { wp_pagenavi(array( 'query' => $wpbp ) ); wp_reset_postdata(); } ?>
就是這樣!您將擁有一個(gè)包含 Quicksand、Lightbox 和 Pagination 的功能齊全的產(chǎn)品組合。
結(jié)論
給自己一個(gè)鼓勵(lì)吧!您已成功使用 WordPress 創(chuàng)建了流沙作品集。所有艱苦的工作都已完成,您可以將其與您開發(fā)的任何工作一起實(shí)施。
非常感謝您花時(shí)間閱讀我的教程,希望對(duì)您有所幫助。歡迎大家留言評(píng)論,我會(huì)盡力協(xié)助和解答。
The above is the detailed content of Create a quick sinking portfolio using WordPress. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

Object cache assists persistent storage, suitable for high access and low updates, tolerating short-term lost data. 1. Data suitable for "persistence" in cache includes user configuration, popular product information, etc., which can be restored from the database but can be accelerated by using cache. 2. Select a cache backend that supports persistence such as Redis, enable RDB or AOF mode, and configure a reasonable expiration policy, but it cannot replace the main database. 3. Set long TTL or never expired keys, adopt clear key name structure such as user:1001:profile, and update the cache synchronously when modifying data. 4. It can combine local and distributed caches to store small data locally and big data Redis to store big data and use it for recovery after restart, while paying attention to consistency and resource usage issues.

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

PluginCheck is a tool that helps WordPress users quickly check plug-in compatibility and performance. It is mainly used to identify whether the currently installed plug-in has problems such as incompatible with the latest version of WordPress, security vulnerabilities, etc. 1. How to start the check? After installation and activation, click the "RunaScan" button in the background to automatically scan all plug-ins; 2. The report contains the plug-in name, detection type, problem description and solution suggestions, which facilitates priority handling of serious problems; 3. It is recommended to run inspections before updating WordPress, when website abnormalities are abnormal, or regularly run to discover hidden dangers in advance and avoid major problems in the future.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website
