Skip to content

Instantly share code, notes, and snippets.

@tajidyakub
Last active October 26, 2017 12:49
Show Gist options
  • Save tajidyakub/2f7bfee89bda71961039adb3970e8c3c to your computer and use it in GitHub Desktop.
Save tajidyakub/2f7bfee89bda71961039adb3970e8c3c to your computer and use it in GitHub Desktop.
Mendefinisikan constructor css (background-image) secara dinamis melalui featured-image di WordPress Themes

Constructor Background image CSS dari Featured Image di WordPress Themes

Melakukan registrasi style, dan memasukkan inline style melalui fungsi yang diletakkan di functions.php, url yang diperlukan adalah url gambar yang menjadi featured-image di post dengan ID tertentu.

Template File eg. single.php

# WordPress Loop
<?php post_header_background(); ?>
<div class="post-header post-header-<?php echo get_the_ID(); ?>">
  <h1><?php the_content(); ?><small><?php get_post_meta( get_the_ID(), 'Subtitle', true ); ?></small></h1>
</div>
# End of WordPress Loop

Theme's Function functions.php

/**
 * Post Header background-image
 */
function post_background_header() {
	$post_id = get_the_ID();
	if ( has_post_thumbnail() ) {
		$img_url = get_the_post_thumbnail_url( get_the_ID(), 'full' );
	} else {
		$img_url = bloginfo( 'template_url' ) . '/img/default-post-header-background.jpg';
	}
	$css = '.post-header-' . $post_id . ' { background-image: url(' . $img_url . '); }';
	wp_register_style( 'justthat-inline', false );
	wp_enqueue_style( 'justthat-inline' );
	wp_add_inline_style( 'justthat-inline', $css );
}

Inline style tersebut akan muncul di bagian bawah html dengan id='justthat-inline'.

<style id='justthat-inline-inline-css' type='text/css'>
	.post-header-98 { background-image: url(http://tjlocalwww.dev/wp-content/uploads/2017/10/aplikasi-icon-slate-pengolah-icon-macos.jpg); }
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment