概述
This is a guest post by Josh Pollock
这是Josh Pollock的来宾帖子
The Pinterest-like grid display of posts has been a popular design for WordPress blog index pages for a while. It is popular not only because it mimics the look of the popular social media site, but also because it makes the best use of space on the screen. On a WordPress blog index, it allows each post preview to be the size it naturally needs to be, without leaving extra space.
一段时间以来,类似Pinterest 的帖子网格显示一直是WordPress博客索引页面的流行设计。 它之所以受欢迎,不仅是因为它模仿了流行的社交媒体网站的外观,而且还因为它可以充分利用屏幕上的空间。 在WordPress博客索引上,它允许每个帖子预览达到其自然所需的大小,而不会留下额外的空间。
In this tutorial, I will show you how to use the popular Masonry JavaScript Library to create cascading grid layouts for your blog index, as well as archive pages for your theme. I will address a few issues that you need to consider for mobile-optimization and how to solve them.
在本教程中,我将向您展示如何使用流行的Masonry JavaScript库为博客索引以及主题的存档页面创建级联网格布局。 我将解决您需要进行移动优化的一些问题以及如何解决这些问题。
Note: This is an advanced level tutorial for those who feel comfortable editing WordPress themes and have sufficient HTML/CSS knowledge.
注意:这是一个高级教程,适合那些喜欢编辑WordPress主题并且具有足够HTML / CSS知识的人。
步骤1:将必要的库添加到您的主题 (Step 1: Add Necessary Libraries To Your Theme)
Update: WordPress 3.9 now includes the latest version of Masonry.
更新 :WordPress 3.9现在包括最新版本的Masonry。
First you need to load Masonry into your theme, using this code:
首先,您需要使用以下代码将Masonry加载到主题中:
if (! function_exists('slug_scripts_masonry') ) :
if ( ! is_admin() ) :
function slug_scripts_masonry() {
wp_enqueue_script('masonry');
wp_enqueue_style('masonry’, get_template_directory_uri().'/css/’);
}
add_action( 'wp_enqueue_scripts', 'slug_scripts_masonry' );
endif; //! is_admin()
endif; //! slug_scripts_masonry exists
This code simply loads masonry and makes it available to your theme’s template files (see our guide on how to properly add JavaScripts and Styles in WordPress). Also note that we are not adding jQuery as a dependency for either. One of the advantages of Masonry 3 is that it does not require jQuery, but can be used with it. In my experience, initializing Masonry without jQuery is more reliable, and opens up the possibility of skipping loading jQuery, which can help with both page load times and compatibility issues.
此代码仅加载砌筑并将其提供给主题的模板文件(请参阅有关如何在WordPress中正确添加JavaScript和样式的指南)。 还要注意,我们都没有将jQuery作为依赖项添加。 Masonry 3的优点之一是它不需要jQuery,但可以与它一起使用。 以我的经验,在没有jQuery的情况下初始化Masonry更为可靠,并且可以跳过加载jQuery,这可以帮助解决页面加载时间和兼容性问题。
步骤2:初始化Javascript (Step 2: Initialize The Javascript)
This next function sets up Masonry, defines the containers that will be used with it and also makes sure everything happens in the right order. Masonry needs to do calculate the size of each of the items on the page in order to layout its grid dynamically. A problem I’ve run into with Masonry in many browsers is that Masonry will miscalculate the height of items with slow loading images, leading to overlapping items. The solution is to use imagesLoaded to prevent Masonry from calculating the layout until all images are loaded. This ensures proper sizing.
下一个功能设置砌筑,定义将与之配合使用的容器,并确保一切按正确顺序进行。 石工需要计算页面上每个项目的大小,以便动态布局其网格。 我在许多浏览器中遇到Masonry时遇到的一个问题是,Masonry会错误地计算加载缓慢图像的物品的高度,从而导致物品重叠。 解决方案是使用imagesLoaded来防止Masonry在加载所有图像之前计算布局。 这样可以确保正确调整大小。
This is the function and action that will output the initialization script in the page footer:
这是将在页面页脚中输出初始化脚本的函数和操作:
if ( ! function_exists( 'slug_masonry_init' )) :
function slug_masonry_init() { ?>
<script>
//set the container that Masonry will be inside of in a var
var container = document.querySelector('#masonry-loop');
//create empty var msnry
var msnry;
// initialize Masonry after all images have loaded
imagesLoaded( container, function() {
msnry = new Masonry( container, {
itemSelector: '.masonry-entry'
});
});
</script>
<?php }
//add to wp_footer
add_action( 'wp_footer', 'slug_masonry_init' );
endif; // ! slug_masonry_init exists
The function is explained step by step with inline comments. What the Javascript function does is tell Masonry to look inside a container with the id “masonry-loop” for items with the class “masonry-entry” and to calculate the grid only after images are loaded. We set the outer container with querySelector and the inner with itemSelector.
通过内联注释逐步解释该功能。 Javascript函数的作用是告诉Masonry在id为“ masonry-loop”的容器中查找具有“ masonry-entry”类的项目,并仅在加载图像后才计算网格。 我们使用querySelector设置外部容器,使用itemSelector设置内部容器。
第2步:创建砌体环 (Step 2: Create Masonry Loop)
Instead of adding the HTML markup for Masonry directly to a template we are going to create a separate template part for it. Create a new file called “content-masonry.php” and add it to your theme. This will allow you to add the Masonry loop to as many different templates as you want.
与其直接将MasonryHTML标记添加到模板中,我们不为它创建一个单独的模板部分。 创建一个名为“ content-masonry.php”的新文件,并将其添加到您的主题中。 这将允许您将Masonry循环添加到所需的任意数量的不同模板中。
In your new file you will add the code shown below. The markup is similar to what you would normally see for any content preview. You can modify it anyway you need to, just be sure that the outermost element has the class of “masonry-entry” that we set as the itemSelector in the last step.
在新文件中,您将添加以下代码。 标记类似于您在任何内容预览中通常看到的标记。 您可以根据需要进行任何修改,只需确保最外面的元素具有在最后一步中设置为itemSelector的“砌体进入”类即可。
<article class="masonry-entry" id="post-<?php the_ID(); ?>" <?php post_class(); ?> >
<?php if ( has_post_thumbnail() ) : ?>
<div class="masonry-thumbnail">
<a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail('masonry-thumb'); ?></a>
</div><!--.masonry-thumbnail-->
<?php endif; ?>
<div class="masonry-details">
<h5><a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><span class="masonry-post-title"> <?php the_title(); ?></span></a></h5>
<div class="masonry-post-excerpt">
<?php the_excerpt(); ?>
</div><!--.masonry-post-excerpt-->
</div><!--/.masonry-entry-details -->
</article><!--/.masonry-entry-->
This markup has classes for each of its parts so you can add markup to match your theme. I like adding a nice, slightly rounded border to .masonry-entry. Another nice option is no border for .masonry-entry, but to give it a slight shadow. That looks particularly good when the post thumbnail extends the whole way to the border of the container, which can be accomplished by giving .masonry-thumbnail margins and paddings of 0 in all directions. You will want to add all of these styles in a file called masonry.css in your theme’s css directory.
该标记的每个部分都有类,因此您可以添加标记以匹配您的主题。 我喜欢在.masonry-entry中添加一个漂亮的,略圆的边框。 另一个不错的选择是.masonry-entry没有边界,但是要给它一个阴影。 当帖子缩略图一直延伸到容器的边框时,这看起来特别好,这可以通过在所有方向上给.masonry-thumbnail设置边距和填充0来实现。 您将要在主题的css目录中的名为masonry.css的文件中添加所有这些样式。
步骤3:将砌体环添加到模板 (Step 3: Add Masonry Loop To Templates)
Now that we have our template part you can use it in any template in your theme you like. You might add it to index.php, but not category.php if you don’t want it used for category archives. If you only want it used on your theme’s home page, when its set to show blog posts, you would use it in home.php. Wherever you choose all you need to do is wrap your loop in a container with the id “masonry-loop” and add the template part into the loop using get_template_part(). Be sure to start the masonry loop container before while (have_posts() ).
现在我们有了模板部分,您可以在您喜欢的主题的任何模板中使用它。 如果您不希望将它用于类别存档,则可以将其添加到index.php,而不是category.php。 如果只希望在主题的主页上使用它,则当它设置为显示博客文章时,可以在home.php中使用它。 无论您选择什么位置,都需要将循环包装在ID为“ masonry-loop”的容器中,并使用get_template_part()将模板部分添加到循环中。 确保在while(have_posts())之前启动砌体循环容器。
For example, here is the main loop from twentythirteen’s index.php:
例如,这是二十十三的index.php的主循环:
<?php if ( have_posts() ) : ?>
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php twentythirteen_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
And here it is modified to get use our Masonry loop:
在这里,它被修改以使用我们的砌体循环:
<?php if ( have_posts() ) : ?>
<div id="masonry-loop">
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'masonry' ?>
<?php endwhile; ?>
</div><!--/#masonry-loop-->
<?php twentythirteen_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
步骤4:设置砌体项目的响应宽度 (Step 4: Set Responsive Widths of Masonry Items)
There are several ways that you can set the width of each Masonry item. You can set the width using a number of pixels when you initialize Masonry. I’m not a fan of doing that since I use responsive themes and it requires some complex media queries to get things right on small screens. For responsive designs, I’ve found the best thing to do is set a width value for .masonry-entry with a percentage, based on how many items you want in a row and let Masonry do the rest of the math for you.
您可以通过多种方式设置每个砌体项目的宽度。 初始化砌体时,可以使用多个像素设置宽度。 我不喜欢这样做,因为我使用响应式主题,并且它需要一些复杂的媒体查询才能在小屏幕上正确显示内容。 对于自适应设计,我发现最好的方法是根据要连续多少项设置.masonry-entry的宽度值并设置一个百分比,然后让Masonry为您完成其余的数学运算。
All this requires is dividing the 100 by the number of items you want to set the percentage in a simple entry in your theme’s style.css. For example, if you want four items in each row you could do this in your masonry.css file:
所需要做的就是用100除以您要在主题的style.css中的简单条目中设置百分比的项目数。 例如,如果您希望每行有四个项目,则可以在masonry.css文件中执行以下操作:
.masonry-entry{width:25%}
.masonry-entry{width:25%}
第5步:移动优化 (Step 5: Mobile Optimization)
We could stop here, but I don’t think the end-result works incredibly well on small phone screens. Once you’re happy with how your theme looks with the new Masonry grid on your desktop, check it out on your phone. If you’re not happy about how it looks on your phone, then you will need to do a little work.
我们可以在这里停下来,但是我认为最终结果在小的手机屏幕上无法正常运行。 使用桌面上的新Masonry网格对主题外观感到满意后,请在手机上签出。 如果您对手机上的外观不满意,则需要做一些工作。
I don’t think there is enough room on a phone’s screen for everything we added to our content-masonry template part. Two good solutions available to you are to shorten the excerpt for phones or skip it entirely. Here is an extra function you can add to your theme’s functions.php to do that. Because I don’t think these issues are a problem on tablets, I am using a great plugin Mobble in all of the examples in this section to only make the changes on phones, not tablets. I am also checking to see if Mobble is active before using it and if necessary falling back to the more general mobile detection function wp_is_mobile which is built into WordPress.
我认为手机屏幕上没有足够的空间容纳我们添加到内容砌体模板部分的所有内容。 您可以使用两种有效的解决方案来缩短电话摘录或完全跳过摘录。 这是一个额外的功能,您可以将其添加到主题的functions.php中。 因为我认为这些问题在平板电脑上不是问题,所以我在本节的所有示例中都使用了出色的Mobble插件,仅在手机而非平板电脑上进行了更改。 我还在使用Mobble之前先检查它是否处于活动状态,必要时还可以使用WordPress内置的更通用的移动检测功能wp_is_mobile。
if (! function_exists('slug_custom_excerpt_length') ) :
function slug_custom_excerpt_length( $length ) {
//set the shorter length once
$short = 10;
//set long length once
$long = 55;
//if we can only set short excerpt for phones, else short for all mobile devices
if (function_exists( 'is_phone') {
if ( is_phone() ) {
return $short;
}
else {
return $long;
}
}
else {
if ( wp_is_mobile() ) {
return $short;
}
else {
return $long;
}
}
}
add_filter( 'excerpt_length', 'slug_custom_excerpt_length', 999 );
endif; // ! slug_custom_excerpt_length exists
As you can see we start by storing the long excerpt length and short excerpt length in variables, since we will be using those values twice and we want to be able to change them from one place if we need to later on. From there we test if we can use Mobble’s is_phone(). If so we set the short excerpt for phones and the long excerpt if we are not. After that we do the same basic thing, but using wp_is_mobile, which will affect all mobile devices ,if is_phone() can’t be used. Hopefully the else part of this function will never be used, but it’s good to have a backup just in case. Once the excerpt length logic is set it just comes down to hooking the function to the excerpt_length filter.
如您所见,我们首先将长摘录长度和短摘录长度存储在变量中,因为我们将两次使用这些值,并且如果需要以后可以将它们从一个位置更改。 从那里我们测试是否可以使用Mobble的is_phone()。 如果是这样,我们设置电话的简短摘录,如果不是,则设置长摘录。 之后,我们执行相同的基本操作,但是使用wp_is_mobile,如果无法使用is_phone(),它将影响所有移动设备。 希望此功能的else部分将永远不会使用,但是最好以防万一。 一旦设置了摘录长度逻辑,它就归结为将函数挂接到excerpt_length过滤器。
Shortening the excerpt is one option, but we can also do away with it entirely with a simple process. Here is a new version of content-masonry, with the entire excerpt portion ommited on phones:
缩短摘录是一种选择,但是我们也可以通过一个简单的过程完全消除它。 这是内容砌筑的新版本,电话中省略了整个摘录部分:
<article class="masonry-entry" id="post-<?php the_ID(); ?>" <?php post_class(); ?> >
<?php if ( has_post_thumbnail() ) : ?>
<div class="masonry-thumbnail">
<a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail('masonry-thumb'); ?></a>
</div><!--.masonry-thumbnail-->
<?php endif; ?>
<div class="masonry-details">
<h5><a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><span class="masonry-post-title"> <?php the_title(); ?></span></a></h5>
<?php
//put the excerpt markup in variable so we don't have to repeat it multiple times.
$excerpt = '<div class="masonry-post-excerpt">';
$excerpt .= the_excerpt();
$excerpt .= '</div><!--.masonry-post-excerpt-->';
//if we can only skip for phones, else skip for all mobile devices
if (function_exists( 'is_phone') {
if ( ! is_phone() ) {
echo $excerpt;
}
}
else {
if ( ! wp_is_mobile() ) {
echo $excerpt;
}
}
?>
</div><!--/.masonry-entry-details -->
</article><!--/.masonry-entry-->
This time we have are testing to see if we are not on a phone/ mobile device and if so we return the excerpt part of our loop. If we are on a phone/ mobile device we do nothing.
这次,我们正在测试以查看是否不在手机/移动设备上,如果是,我们返回循环的摘录部分。 如果我们在电话/移动设备上,我们什么也不做。
Another thing you might want to do is increase the width of the Masonry items, which reduces the number in a row, on mobile devices. In order to do this, we will add a different inline style to the header based on device detection. Since this function uses wp_add_inline_styles it will be dependent on a specific style sheet. In this case I’m using masonry.css, which you might want, for keeping your masonry styles separate. If you don’t end up using that you can use the handle from another, already registered stylesheet.
您可能想做的另一件事是增加移动设备上的砌体项目的宽度,从而减少连续的数量。 为此,我们将基于设备检测将不同的内联样式添加到标题中。 由于此函数使用wp_add_inline_styles,因此它将依赖于特定的样式表。 在这种情况下,我将使用masonry.css(您可能需要)来使您的砌体样式保持分离。 如果您最终不使用它,则可以使用另一个已经注册的样式表的句柄。
if ( ! function_exists ( 'slug_masonry_styles' ) ) :
function slug_masonry_styles() {
//set the wide width
$wide = '25%';
//set narrow width
$narrow = '50%';
/**Determine value for $width**/
//if we can only set narrow for phones, else narrow for all mobile devices
if (function_exists( 'is_phone') {
if ( is_phone() ) {
$width = $narrow;
}
else {
$width = $wide;
}
}
else {
if ( wp_is_mobile() ) {
$width = $narrow;
}
else {
$width = $wide;
}
}
/**Output CSS for .masonry-entry with proper width**/
$custom_css = ".masonry-entry{width: {$width};}";
//You must use the handle of an already enqueued stylesheet here.
wp_add_inline_style( 'masonry', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'slug_masonry_styles' );
endif; // ! slug_masonry_styles exists
This function eneuques the custom stylesheet, and then sets a value for width using what should now be very familiar logic. After that we create the $custom_css variable by passing the value for width into an otherwise regular looking bit of CSS with {$width}. After that we use wp_add_inline_style to tell WordPress to print our inline styles in the header whenever the Masonry stylesheet is being used and then we hook the whole function to wp_enqueue_scripts and we are done.
此函数使定制样式表无效,然后使用现在应该非常熟悉的逻辑为width设置一个值。 之后,我们通过将width的值传递给带有{$ width}CSS常规外观位来创建$ custom_css变量。 之后,只要使用Masonry样式表,我们就使用wp_add_inline_style告诉WordPress在标头中打印内联样式,然后将整个函数挂接到wp_enqueue_scripts上,然后完成。
If you chose to combine your Masonry styles into an existing stylesheet, be sure to use the handle of that style sheet with wp_add_inline_style or your inline styles will not be included. I like to use wp_add_inline_style because I generally wrap the action hook for enqueueing Masonry in a conditional so it only gets added when needed. For example if I am only using Masonry on my blog index and archive pages I would do this:
如果您选择将Masonry样式合并到现有样式表中,请确保将该样式表的句柄与wp_add_inline_style一起使用,否则将不包括内联样式。 我喜欢使用wp_add_inline_style,因为我通常将动作钩子包装在有条件的情况下使砌体入队,因此仅在需要时才添加它。 例如,如果我仅在博客索引和存档页面上使用Masonry,则可以这样做:
if ( is_home() || is_archive() ) {
add_action( 'wp_enqueue_scripts', 'slug_scripts_masonry' );
}
These last few examples should open up some other ideas in your brain. For example, you could use similar logic to skip Masonry altogether on a mobile device. Also wp_add_inline_style() is a lesser used, yet very helpful function as it allows you to programmatically set different styles based on any type of conditional. It can allow you to radically change the style of any element based on not only device detection, but the changes could also be based on which template is being used, or even if the user is logged in or not.
最后的几个例子应该在您的大脑中打开其他一些想法。 例如,您可以使用类似的逻辑在移动设备上完全跳过石工。 wp_add_inline_style()也是一种较少使用但非常有用的函数,因为它允许您基于任何类型的条件以编程方式设置不同的样式。 它不仅使您可以根据设备检测来根本改变任何元素的样式,而且还可以根据所使用的模板(甚至无论用户是否登录)来进行更改。
I hope you see these different changes I am making as an opportunity to get creative. Masonry and similar cascading grid systems have been popular for awhile now, so its time for some new twists on this popular idea. Show us in the comments what cool ways you’ve come up with for using Masonry in a WordPress theme.
希望您能将我正在做出的这些不同的变化视为获得创意的机会。 砌体和类似的级联网格系统已经流行了一段时间,因此该流行思想有了新的转折。 在评论中向我们展示在WordPress主题中使用Masonry时想出的最酷的方法。
A multi-purpose WordPress guy, Josh Pollock writes about WordPress, does theme development, serves as the community manager for the Pods Framework and advocates open source solutions for sustainable design.
一个多用途的WordPress专家Josh Pollock撰写有关WordPress的文章,进行主题开发,担任Pods Framework的社区经理,并倡导可持续设计的开源解决方案。
翻译自: https://www.wpbeginner.com/wp-themes/how-to-use-masonry-to-add-pinterest-style-post-grid-in-wordpress/
最后
以上就是难过可乐为你收集整理的如何使用砌体在WordPress中添加Pinterest样式发布网格的全部内容,希望文章能够帮你解决如何使用砌体在WordPress中添加Pinterest样式发布网格所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复