Categories
Tutorial WordPress

Using is_multisite to loop in a post from another blog

Multisite is a powerful feature that allows us to manage multiple blogs within a single WordPress installation. In this post I briefly describe how to post content from the main site to a sub-site.

// Check if WordPress is using multisite
if ( is_multisite() ) {

global $switched;

// Switch to another blog by ID number 1 for the first site
switch_to_blog( 1 );

// Get a WP_Query that loops in a post from the main site
get_template_part('template-parts/notice-wp-query');

// Switch back to current blog
restore_current_blog();

}

We can use any method you like to query a post from the main site. In this example I’m using WP_Query and Advanced Custom Fields to display a post using the notice category.

<?php
$current_post_ID = get_the_ID(); // the post's id is assigned to $current_post_ID


$args = array(
	'post_type'		=> 'post',
	'orderby'		=> 'date',
	'order'			=> 'DESC',
	'category_name'		=> 'notice',
);

// the query
$the_query = new WP_Query( $args );
?>

<?php if ( $the_query->have_posts() ) : ?>

	<!-- pagination here -->
<div id="notice" class="row">
	<div class="small-12 columns">
	<!-- the loop -->
	<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 
		<article>
		<div class="notice">
		<?php
			if ( function_exists( 'get_field' ) ) {  

				echo '<a href="' . get_field( 'redirect_to_url' ) . '">'; 
					echo '<h1 class="entry-title"><span class="dashicons dashicons-warning"></span>' . get_the_title() .'</h1>';
					echo '<div class="notice-content">';
						echo the_content();
					echo '</div>';
				echo '</a>';
			} else {
				echo '<a href="' . get_permalink() . '">'; 
					echo '<h1 class="entry-title"><span class="dashicons dashicons-warning"></span>' . get_the_title() .'</h1>';
					echo '<div class="notice-content">';
						echo the_content();
					echo '</div>';
				echo '</a>';
			}

		?>
		</div>
		</article>

	<?php endwhile; ?>
	<!-- end of the loop -->
	</div>
</div>
	<!-- pagination here -->
<?php endif; ?>

<?php wp_reset_postdata();

Allowing the site to post a custom message that links to another page for additional information. When the post isn’t available the blue box below will simply not appear on the page. I built this feature a long time ago but didn’t really have a practical use of until March when the pandemic required notification banners above everything on my 100+ site multisite.

Categories
Tutorial WordPress

Disable Lazy Loading Images Using the_post_thumbnail() in WordPress

The introduction of lazy-loading of images as of WordPress 5.5 improves site performance by delaying them until the user scrolls into view making our pages feel faster by only loading images as we need to see them.

The Problem

However, I needed a way to disable lazy loading for specific features like this image carousel where the last few slides would not load as they rotated into view. 🙁

Image not loading on reveal in a carousel
A blank space where an image should appear. Lazy Loading somehow prevented the image from displaying on first pass while using Foundation 6’s Orbit Carousel.

The Solution

Disable lazy loading of the carousel images using this template part.

the_post_thumbnail( 'carousel', [ 'class' => 'orbit-image' , 'loading' => false ] );

The code above is inspired by modifying the attr argument using an array.

Adding ‘loading’ => false to the array disables the feature for this homepage image carousel.

The Orbit carousel now loads all images at page load.

Before and After

loading=”lazy” appears within the image HTML tag.
loading=”lazy” no longer displays with the image.

Disabling lazy loading for a specific use of the_post_thumbnail() allows us to benefit from the feature everywhere else. 😀

Categories
Tutorial WordPress

If post hasn’t been modified recently in WordPress

Today an issue came up where a reader of one of a site I manage was referring to content that was out of date. Normally that’s not a problem but in this case it is a timely pandemic documentation page where the content is very likely to be out of date within a couple months if its not routinely updated.

To solve this challenge I decided to write a small function that will check the last modified date of a post and place an alert below the title and above the content. That notice would read…

This page has not been updated in 60 days. The information below may be outdated.

Which is a casual way of alerting the reader that if this information is timely perhaps check elsewhere on the site for a newer post. Likewise, if that person is looking for an older post they can safely disregard the notice. posting a discrete notice can come in handy depending on the context that brought a reader to the post.

Functions.php

<?php
// If post is older than 60 days return true
function jd_is_old_post($days = 60 ) {
	$days = (int) $days;
	$offset = $days*60*60*24;
	if ( get_post_modified_time() < date('U') - $offset )
		return true;
	
	return false;
}
?>

Place within the WordPress Loop

<?php
// If post is older than 60 days display this notice
if ( jd_is_old_post() ) {
	echo '<div class="old-post-notice">';
        echo '<p><strong>This page has not been updated in 60 days. The information below may be outdated.</p></strong>';
    echo '</div>';
} 
?>
Categories
Tutorial WordPressaside

Attachment Image Snippet

This snippet for wp_get_attachment_image_src frequently appears in my theme development to select an image by its unique ID in the WordPress media library.

Handy for instances where logos, banners, or any other image frequently recurs on a website and you’d rather store that image in the media library where it can be replaced or modified dynamically.

// replace 7 with unique ID number of image
$image_attributes = wp_get_attachment_image_src( $attachment_id = 7, 'full' );

// retrieves alternative text from image information 
$alt = get_post_meta( $attachment_id , '_wp_attachment_image_alt', true );

if ( $image_attributes ) {
	echo '<img src="'. $image_attributes[0] .'" width="' . $image_attributes[1] . '" height="' . $image_attributes[2] . '" alt="' . $alt . '" />';
}

How it works

  • Set the unique id number in the snippet
  • Displays the image and relevant attributes

This code is based on the official Code References at WordPress.org for wp_get_attachment_image_src() and as get_post_meta().

Categories
Tutorial WordPress

Restrict post to WordPress user

Over the that weekend I had been using WordPress to take notes at WordCamp Orange County and realized that WordPress’ block editor is useful as a note taking environment. But what If I don’t want these notes to be public?

Using a template to restrict access

I duplicated TwentyNineteen’s single.php template and wrapped the loop in a conditional tag is_user_logged_in().

The code

<?php
/**
 * Single post and page template for restricting the title and content unless the user is logged in
 * Sources: 
 * https://www.wpbeginner.com/wp-themes/create-custom-single-post-templates-for-specific-posts-or-sections-in-wordpress/
 * https://codex.wordpress.org/Conditional_Tags
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
 *
 * @package WordPress
 * @subpackage Twenty_Nineteen
 * @since 1.0.0
 *
 * License: GPL 2 or later
 *
 * Template Name: Log in Required
 * Template Post Type: post, page
 *
 */

get_header();
?>

	<div id="primary" class="content-area">
		<main id="main" class="site-main">

<?php
	if ( is_user_logged_in() ) {  // check if user is logged in

/* * 
 * Start the Loop 
 * This example  uses TwentyNineteen for the loop, if using a different theme subsitute that loop here.
 * */
		while ( have_posts() ) :
			the_post();

			get_template_part( 'template-parts/content/content', 'single' );

			if ( is_singular( 'attachment' ) ) {
				// Parent post navigation.
				the_post_navigation(
					array(
						/* translators: %s: parent post link */
						'prev_text' => sprintf( __( '<span class="meta-nav">Published in</span><span class="post-title">%s</span>', 'twentynineteen' ), '%title' ),
					)
				);
			} elseif ( is_singular( 'post' ) ) {
				// Previous/next post navigation.
				the_post_navigation(
					array(
						'next_text' => '<span class="meta-nav" aria-hidden="true">' . __( 'Next Post', 'twentynineteen' ) . '</span> ' .
							'<span class="screen-reader-text">' . __( 'Next post:', 'twentynineteen' ) . '</span> <br/>' .
							'<span class="post-title">%title</span>',
						'prev_text' => '<span class="meta-nav" aria-hidden="true">' . __( 'Previous Post', 'twentynineteen' ) . '</span> ' .
							'<span class="screen-reader-text">' . __( 'Previous post:', 'twentynineteen' ) . '</span> <br/>' .
							'<span class="post-title">%title</span>',
					)
				);
			}

			// If comments are open or we have at least one comment, load up the comment template.
			if ( comments_open() || get_comments_number() ) {
				comments_template();
			}

		endwhile; // End of the TwentyNineteen  loop.
    
	} else { // If not logged in present a link to log into the site
		echo '<p style="text-align: center;"><a href="' .  wp_login_url( get_permalink() ) . '" title="Login">Log in to view this post</a></p>';
	}
		?>

		</main><!-- #main -->
	</div><!-- #primary -->

<?php
get_footer();

View this code in my GitHub gist.

How does this code work?

Simply put, is_user_logged in() will check if the user is logged before it displays the post. If not they’re presented with a link to log in.

Left, the user is logged in. Right, post content and title will not display.

What it doesn’t do?

Using this post and page template will only restrict the post page. The excerpt or content will still display on archive pages unless those loops run a similar conditional check.