Adding the_post_thumbnail(); via css - php

I'm trying to set my posts page so that each post item loads with it's featured image as it's background. My code is working properly, but how do I add the post thumbnail as the background for each post? My code is attached below
<?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* #package Clean Blog
*/
get_header(); ?>
<?php
// Custom loop that adds a clearing class to the first item in each row
$args = array('numberposts' => -1, 'order' => 'ASC' ); //For this example I am setting the arguments to return all posts in reverse chronological order. Odds are this will be a different query for your project
$allposts = get_posts($args);
$numCol = 2; // Set number of columns
// Start Counter
$counter = 0;
foreach ($allposts as $post) {
$content = '<div class="col-md-6 columns-'.$numCol.($counter % $numCol == 0 ? ' first' : '').'">'; // Add class to first column
$content .= '<h3>'.$post->post_title.'</h3>';
$content .= $post->post_content;
$content .= '</div>';
echo $content;
$counter ++;
}
?>
<style type="text/css">
/* Added styles here for the demo, but ideally you would put this in a stylesheet.*/
.columns-2 {
float:left;
}
.first {
clear:both;
margin-left:0;
}
</style>
<!-- /.col-lg-8.col-lg-offset-2.col-md-10.col-md-offset-1 -->
<?php get_footer(); ?>
UPDATE
I've now tried adding it as an inline style, but the raw style is showing up on the page. I feel like I'm missing something easy
http://imgur.com/kkATCAC
<?php
// Custom loop that adds a clearing class to the first item in each row
$args = array('numberposts' => -1, 'order' => 'ASC' ); //For this example I am setting the arguments to return all posts in reverse chronological order. Odds are this will be a different query for your project
$allposts = get_posts($args);
$numCol = 2; // Set number of columns
$thumbnail = get_the_post_thumbnail( $page->ID, 'thumbnail' );
// Start Counter
$counter = 0;
foreach ($allposts as $post) {
$content = '<div class="col-md-6 columns-'.$numCol.($counter % $numCol == 0 ? ' first' : '').'" style="background: url("${thumbnail}") center center/cover no-repeat;">'; // Add class to first column
$content .= '<h3>'.$post->post_title.'</h3>';
$content .= $post->post_content;
$content .= '</div>';
echo $content;
$counter ++;
}
?>
UPDATE 2
I've checked the quotes but now I'm getting a parse error and the page doesn't load at all.
$content = '<div style="background: url('${thumbnail}') center center/cover no-repeat;" class="col-md-6 columns-'.$numCol.($counter % $numCol == 0 ? ' first' : '').'">'; // Add class to first column

You could add it as an inline style:
<?php
$thumbnail = get_the_post_thumbnail( $page->ID, 'thumbnail' );
$content = "<div class='your-post-thing' style='background: url('${thumbnail}') center center/cover no-repeat;'>...stuff...</div>';
echo $content;
?>
OR
Depending on your browser support, you could use object-fit:
<?php
$content .= "<div class='your-post-thing'>";
$content .= "<img class='background-image' src='${thumbnail}' />";
$content .= "</div>";
echo $content;
?>
CSS:
.your-post-thing {
position: relative;
}
.background-image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}

$content = '<div style="background-image:url('.wp_get_attachment_url(get_the_post_thumbnail()).')" class="col-md-6 columns-'.$numCol.($counter % $numCol == 0 ? ' first' : '').'">'; // Add class to first column
you can try something like this, and in your css you can add the rules to view correctly the background.

Related

Dynamic ID with JQUERY functions

I have a problem with my JQUERY code. Here's the code:
$maxcounter = $( '.testimonio-popup[id^="popup-"]' ).length;
var i = 0;
while (i < $maxcounter) {
$('#open-'+i).on('click', function() {
$('#popup-'+i).fadeIn('slow');
$('.testimonio-overlay').fadeIn('slow');
$('.testimonio-overlay').height($(window).height());
return false;
});
$('#close-'+i).on('click', function(){
$('#popup-'+i).fadeOut('slow');
$('.testimonio-overlay').fadeOut('slow');
return false;
});
i++;
}
It takes correctly the total of times the .testimonio-popup div is appearing in the site, and the fadeIn action for .testimoniooverlay class works.
But the fadeIn action for #popup-[number] is not working. Any help why?
For further assistance, I attach the PHP code that makes the query:
function get_the_content_with_formatting ($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
add_shortcode( 'testimonios', 'display_testimonios' );
function display_testimonios($atts){
$atributos = shortcode_atts([ 'grupo' => 'PORDEFECTO', ], $atts);
$buffer = '<div class="testimonio-overlay"></div> ';
$contadorid = 0;
$q = new WP_Query(array(
'post_type' => 'test',
'tax_query' => array(
array(
'taxonomy' => 'grupos_testimonios',
'field' => 'slug',
'terms' => $atributos['grupo']
//'terms' => 'grupo-1'
)
)
) );
while ($q->have_posts()) {
$q->the_post();
$buffer .= '<div class="testimonio">';
$buffer .= '<div class="testimonio-img">' . get_the_post_thumbnail($_post->ID).'</div>';
$buffer .= '<div class="testimonio-titulo"><p>' . get_the_title() .'</p></div>';
$buffer .= '<div class="testimonio-intro"><div class="testimonio-parrafo">' . get_the_excerpt() . '</div><button class="testimonio-boton" id="open-'.$contadorid.'">Leer más</button></div></div>';
$buffer .= '<div class="testimonio-popup" id="popup-'.$contadorid.'"><div class="testimonio-popup-contenido"><div class="testimonio-cerrar"><button class="testimonio-boton-cerrar" id="close-'.$contadorid.'">x</button></div>';
$buffer .= '<div class="testimonio-popup-titulo"><p>' . get_the_title() .'</p></div>';
$buffer .= '<div class="testimonio-popup-contenido">' . get_the_content_with_formatting() . '</div></div></div>';
$contadorid = $contadorid + 1;
}
wp_reset_postdata();
return $buffer;
}
Thank you!
Frede
#Rory McCrossan is right (see comment).
I'm not sure what goes wrong there, but I would suggest you change this logic:
$("#open-1").on(....);
$("#open-2").on(....);
$("#open-3").on(....);
$("#close-1").on(....);
$("#close-2").on(....);
$("#close-3").on(....);
$("#popup-1").fadeIn()
$("#popup-2").fadeIn()
to using classes and attributes:
$(".popup-handler").on(.. check if open/close -> then action..);
$(".popup").filter(.. check for specific reference..).fadeIn()
And if you want to interact elements with different classes, add data attributes to them so you can find them when needed. Here is a simple example:
<!-- popup nr 1 -->
<div class="popup-handler" data-rel="1" data-action="open"></div>
<div class="popup" data-rel="1">
<div class="popup-handler" data-rel="1" data-action="close"></div>
</div>
<!-- popup nr 2 -->
<div class="popup-handler" data-rel="2" data-action="open"></div>
<div class="popup" data-rel="2">
<div class="popup-handler" data-rel="2" data-action="close">x</div>
</div>
<!-- jQuery -->
$(".popup-handler").on("click", function() {
/* get popup reference & action */
var rel = $(this).data("rel"),
action = $(this).data("action");
/* find the target popup */
var $popup = $(".popup").filter("[data-rel=" + rel + "]");
if (action == "open") {
$popup.fadeIn("slow");
/* ... other code when opening a popup... */
}
if (action == "close") {
$popup.fadeOut("slow");
/* ... other code when closing a popup... */
}
});
Demo here - 4 popups, working: jsfiddle
(Defining the same functions inside a while loop is generally a bad idea.)

putting in a separator between posts in loop

I have the following loop which brings in the title of each post onto my page
html
<?php
if (have_posts()) {
while (have_posts()) {
the_post();
echo '<div class="cell">'.get_the_title().'</div>';
} // end while
} // end if
?>
css
.cell {
display: inline-block;
margin: 0 10px;
}
I want to put a separator between each title/link brought in (not on the ends)
example output
link <div class="separate"></div>
link <div class="separate"></div> link
simple solution using additional flag variable $first
<?php
if ( have_posts() ) {
$first = true;
while ( have_posts() ) {
the_post();
if($first){
$first = false;
} else {
// echo separator
}
echo '<div class="cell">'.get_the_title().'</div>';
} // end while
} // end if
?>
You could put in a <hr> element at the end of your echo like this:
echo '<div class="cell">'.get_the_title().'</div><hr>';
You have to put a counter and compare the counter with posts per page to check if you have reached last post.
You can get posts per page from options table like this:
$default_posts_per_page = get_option( 'posts_per_page' );
Check if you have reached the last post, then don't print out the separator.
$counter = 1;
while ( have_posts() ) {
//your stuffs
if ($counter != $default_posts_per_page) {
//print separator
}
$counter++;
}

dynamically changing CSS background-image

I'm fairly new to both PHP and Javascript, so please forgive my ignorance and poor use of terminology, but I'll do my best to explain exactly what I'm struggling to achieve.
I have information stored in a PHP array that I call to my index page using the function below (the code below is in a separate PHP file called articles.php that's included in my index.php) :
<?php
function get_news_feed($article_id, $article) {
$output = "";
$output .= '<article class="img-wrapper">';
$output .= '<a href="article.php?id=' . $article_id . '">';
$output .= '<div class="news-heading">';
$output .= "<h1>";
$output .= $article["title"];
$output .= "</h1>";
$output .= "<p>";
$output .= "Read more...";
$output .= "</p>";
$output .= "</div>";
$output .= '<div id="news-img-1">';
$output .= "</div>";
$output .= "</a>";
$output .= "</article>";
return $output;
}
$articles = array();
$articles[] = array(
"title" => "Andy at NABA",
"description" => "Docendi, est quot probo erroribus id.",
"img" => "img/gym-01.jpg",
"date" => "05/04/2013"
);
$articles[] = array(
"title" => "Grand Opening",
"description" => "Docendi, est quot probo erroribus id.",
"img" => "img/gym-01.jpg",
"date" => "05/04/2013"
);
?>
My index.php looks like the following minus some HTML that plays no role in this process:
<?php
include("inc/articles.php");
?>
<?php
$pageTitle = "Home";
include("inc/header.php");
?>
<section class="col-4 news">
<?php
$total_articles = count($articles);
$position = 0;
$news_feed = "";
foreach($articles as $article_id => $article) {
$position = $position + 1;
if ($total_articles - $position < 2) {
$news_feed .= get_news_feed($article_id, $article);
}
}
echo $news_feed;
?>
</section>
I am aiming to dynamically change the CSS Background-Image property of the div element with ID news-img-1 using Javascript.
I have tried such things as:
document.getElementById('news-img-1').style.backgroundImage = 'url('<?php $article["img"]; ?>')';
document.getElementById('news-img-1').style.backgroundImage = 'url('http://www.universalphysique.co.uk/' + '<?php $article["img"]; ?>')';
document.getElementById('news-img-1').style.backgroundImage = 'url('window.location.protocol + "//" + window.location.host + "/" + '<?php $article["img"]; ?>')';
.....but I'm getting nowhere!! My code in practise works because the following Javascript inserts an image correctly:
document.getElementById('news-img-1').style.backgroundImage = 'url("img/gym-01.jpg")';
Here is my site up and running, the images should be placed in the empty circles you'll see! Any help would be great, this ones tough for me!!
comparing the hard coded javascript to ones that don't work, I notice that you are not including the double-quotes around the <?php $article["img"]; ?> snippet. The hard coded one shows
= 'url("img/gym-01.jpg")'
but the ones with the php snippet will produce
= 'url(img/gym-01.jpg)'
so perhaps if you modify it to
document.getElementById('news-img-1').style.backgroundImage = 'url("'<?php $article["img"]; ?>'")';
OR
edit the get_news_feed function as follows:
replace these lines
$output .= '<div id="news-img-1">';
$output .= "</div>";
with
$output .= '<div class="news-img"><img src="' . $article["img"] . '"></div>' ;
and change your css like so:
article.img-wrapper {
position: relative;
}
div.news-img {
position: absolute;
top: 0;
z-index: -1000;
}
OR
Modify your get_news_feed function, change the statement for the <div id="news-img-1"> output to include a data-url attribute like:
$output .= '<div class="news-img" data-url="' . $article["img"] . '">';
Then add a jquery statement like:
$(".news-img").each( function() {
$(this).css("background-image", "url(" + $(this).data("url") +")" );
});
The jquery statement goes in a static js file as opposed to generating the script in php.
You need to remove the quotes from your PHP tags and see if it works!
Do it like this:
document.getElementById('news-img-1').style.backgroundImage = 'url(' + <?php $article["img"]; ?> + ')';
Hope it helps.

limit the word count and add a read more link

Ok i have this code so far which is in my wordpress template so precisely this a wordpress stuff.
<?php
$post_id = 266;
echo "<div id='widgets-wrapper3'><div id='marginwidgets' style='overflow: auto; max-width: 100%; margin: 0 auto; border: none !important;'>";
$queried_post = get_post($post_id);
echo "<div class='thewidgets'>";
echo $queried_post->post_content;
echo '</div>';
echo "</div></div>";
?>
as you can see into the code, the routine is, to display the post which has an id of 266, now all i want is to limit the word count in the post content of that post, let say I want to limit the word to 300 and then add a read more link. how to make that please?
hope there's someone here who figured out how to make that.
I am open in, Ideas, recommendation and suggestion. Hope someone here could help, thank you.
try this:
http://codex.wordpress.org/Function_Reference/the_excerpt
or use php substr:
echo get_sub($queried_post->post_content, 300);
function get_sub($str, $max=300)
{
$ar = explode($str);
$count = 0;
$new_str = "";
$del = " ";
foreach($ar as $a)
{
if($count == 0)
{
//no space
$del = "";
}
if($count < $max)
{
$new_str .= $del.$a;
}
$count++;
}
return $new_str;
}
if the content contains html elements, its a problem.
hope it helps

wordpress random tag issue

I am having issue with a wordpress Tag CLoud Plugin.
I want to show random tags but i am confused how to do this.
the codes are given below.
I want to show random tags. like if i select to show just 5 tags and when each time i refrest the screen the tags should appear randomly.
function widget_tagcloud($args){
$option_value = retrieve_options($opt_val);
extract($args);
echo $before_widget;
echo $before_title;
echo $option_value['title'];
echo $after_title;
global $wpdb;
$tags_list = get_terms('post_tag', array(
'orderby' => 'count',
'hide_empty' => 0
));
if(sizeof($tags_list)!=0){
$max_count = 0;
if(!empty($option_value['height'])) $canvas_height = $option_value['height'];
else $canvas_height = "250";
if(!empty($option_value['width'])) $canvas_width = $option_value['width'];
else $canvas_width = "250";
foreach($tags_list as $tag) if($tag->count > $max_count) $max_count = $tag->count;?>
<div id="myCanvasContainer">
<canvas width="<?php echo $canvas_width;?>" height="<?php echo $canvas_height;?>" id="myCanvas">
<p>Tags</p>
</canvas>
</div>
<div id="tags">
<ul style="
font-family: <?php if(!empty($option_value['font_name'])) echo $option_value['font_name'];
else echo "Calibri";?>;
height:
<?php
if(!empty($option_value['height'])) echo $option_value['height'];
else echo "250";
?>px;
width:
<?php
if(!empty($option_value['width'])) echo $option_value['width'];
else echo "250";
?>px;
background-color: #<?php if(!empty($option_value['bg_color'])) echo $option_value['bg_color'];
else echo "FFF";?>;
">
<?php
if(empty($option_value['no_of_tags'])) $option_value['no_of_tags'] = 15;
if(empty($option_value['txt_color'])) $option_value['txt_color'] = "000";
if(empty($option_value['max_font_size'])) $option_value['max_font_size'] = 40;
if(empty($option_value['min_font_size'])) $option_value['max_font_size'] = 3;
$i=1;
foreach($tags_list as $tag){
if($i <= $option_value['no_of_tags']){
$font_size = $option_value['max_font_size'] - (($max_count - $tag->count)*2);
if($font_size < $option_value['min_font_size']) $font_size = $option_value['min_font_size'];
echo '<li><a href="'.$_SERVER['PHP_SELF'].'?tag='.$tag->slug.'"
style="font-size:'.$font_size.'px;color: #'.$option_value['txt_color'].';">'
.$tag->name.'</a></li>';
$i++;
}
}
echo '</ul></div>';
}
else echo "No tags found";
echo $after_widget;
}
Accordind to your code: (this part especially)
$tags_list = get_terms('post_tag', array(
'orderby' => 'count',
'hide_empty' => 0
));
The tags which you get are ordered by count , therefore - they are not randomly picked.
You can try and use the next code:
$tags_list = get_terms('post_tag', array(
'number' => 5,
'orderby' => 'none',
'hide_empty' => 0
));
And if that doesn't work , build a customized query using the RAND function of mysql.
EDIT: based on your code , you can do is even easier by using the shuffle() php function.
Just replace:
$max_count = 0;
With:
$max_count = 5;
shuffle($tags_list);

Categories