I want to check the class of the html (there are posts and every category got a own class for background color) and then set the background.
I wanted to to it with jQuery but it doesn't work because the first one is true so all get the same background.
My php code:
<div class="grid" >
<?php
$args = array( 'post_type' => 'post' );
$query = new WP_Query( $args );
while ($query->have_posts()) : $query->the_post() ; ?>
<div class="post grid-item <?php foreach((get_the_category()) as $category) { echo $category->cat_name; } ?>" style='background: url("<?php if (has_post_thumbnail()) { the_post_thumbnail_url(); } ?>"); background-color:<?php ?>' >
<h1><?php the_title(); ?></h1>
</div>
<?php endwhile;
wp_reset_query();
?>
</div>
my jQuery code that doesn't work
//post background
var back_engagement = jQuery('.grid div').hasClass('engagement');
var back_unternehmen = jQuery('.grid div').hasClass('unternehmen');
var back_forum = jQuery('.grid div').hasClass('forum');
if (back_engagement){
jQuery('.grid-item').css({"backgroundColor": "#959595"});
}
else if (back_unternehmen) {
jQuery('.grid-item').css({"backgroundColor": "#96A306"});
}
else if (back_forum) {
jQuery('.grid-item').css({"backgroundColor": "#215270"});
}
For me it doesn't mater if the solution is with php or jQuery
You can set the CSS property based on simple selector.
jQuery('.grid div.engagement').css({"backgroundColor": "#959595"});
jQuery('.grid div.unternehmen').css({"backgroundColor": "#96A306"});
jQuery('.grid div.forum').css({"backgroundColor": "#215270"});
However I would recommend you to set them using classes in CSS
.engagement{ background-color: #959595;}
Related
I am checking if there is a Thumbnail image in a blog post using has_post_thumbnail(), if no thumbnail image, a JavaScript script function is called to change the layout of .blog-post to display from flex to block.
To do this: I am using a JavaScript function with the conditional statement. Like below:
content.php
<div class="blog-post">
<?php /* POST FEATURED THUMBNAIL*/
if(has_post_thumbnail()) { ?>
<div class="post-thumbnail">
<?php the_post_thumbnail('feature-image'); ?>
</div>
<?php } else { ?>
<script type="text/javascript"> alert("asdsas"); xfullWidthPostWithThumbnail(); </script>
<?php } ?>
<article class="post-article para-text">
<p id="blog-title"><?php the_title(); ?></p>
<p id="blog-info-text"><?php the_time('F jS, Y'); ?> | By <?php the_author();?> | Posted In
<?php
$categories = get_the_category();
$seperator = ", ";
$output = '';
if($categories) {
foreach ($categories as $category) {
$output .= '' . $category->cat_name . '' . $seperator;
}
echo trim($output, $seperator);
}
?></p>
<p><?php echo get_the_excerpt(); ?> Read more ยป</p>
<p></p>
</article>
</div>
JavaScript function
/* INDEX PAGE -- ADD DISPLAY BLOCK FOR FULL WIDTH OF POST EXCERPT IF NOT POST THUMBNAIL */
function xfullWidthPostWithThumbnail() {
alert("hhhhhhhhhhhhhhhh");
jQuery(".blog-post").css("display","block !important");
jQuery(".blog-post").css("color","red !important");
}
The problem: Currently the error I am getting:
Uncaught ReferenceError: xfullWidthPostWithThumbnail is not defined
at (index):155
Why is the function not defined? Any ideas??
There is no need to use Javascript to do this - its adding unnecessary processing on the client side.
All you want to do is change the CSS for .blog-post, so create a separate CSS class, and apply it if there is no thumbnail.
Create a new CSS class for the rules you want to apply
Check if the thumbnail exists.
If it doesn't, add your new class to the div
If it does, display as normal
CSS:
Create a class called no_thumbnail to add your styles. FYI You should avoid using !important.
.blog-post.no_thumbnail{
display: block !important;
color: red !important;
}
PHP:
/* declare a variable for your extra class */
$blogpostclass = "";
/* If thumbnail doesn't exist, add your 'no_thumbnail' class */
if(!has_post_thumbnail()) $blogpostclass = "no_thumbnail"; ?>
/* add the class variable to your blog-post div */
<div class="blog-post <?php echo $blogpostclass; ?>">
/* If there is a thumbnail, add it as usual */
<?php
if(has_post_thumbnail()) { ?>
<div class="post-thumbnail">
<?php the_post_thumbnail('feature-image'); ?>
</div>
<?php } ?>
[...]
</div>
you should do in this way
$("".blog-post"").css("display","block !important");
What I'm trying to do is the following.
I have a link on my wordpress page that opens a fancybox window and show the content. No header/footer or anything just the content with a thumbnail.
But, and here is my problem, I also would like visitors to be able to visit that page like normal. But now with the header/navigation/footer and all the stuff you would normally see on a webpage.
I tried using media queries (fancybox window is 900x700) but that didn't work. I tried some javascript:
$(window).resize(function() {
if ($(this).width() < 1024) {
$('.single-incl-opt-out').hide();
} else {
$('.single-incl-opt-out').show();
}
});
Still not luck!
Does anyone know what I can do to get this to work?
Update:
Some code examples.
How I load my fancybox content:
<?php echo get_the_term_list_inclusief( $post->ID, 'inclusief', '<p class="extra-text"><i class="fa fa-check"></i> ', '<br><i class="fa fa-check"></i> ', '</p>'); ?>
Some CSS that doesn't work:
#media only screen and (max-width:85em) and (min-width:50em) {
.fancybox-inner .single-incl-opt-out {display: none;}
}
The CSS works when I change my main window size but not like I want it in the fancybox window.
Here is the function to execute the fancybox:
function get_the_term_list_inclusief( $id, $taxonomy, $before = '', $sep = '', $after = '') {
$args_incl = array('order' => 'ASC');
$terms = wp_get_object_terms( $id, $taxonomy, $args_incl );
if ( is_wp_error( $terms ) )
return $terms;
if ( empty( $terms ) )
return false;
$links = array();
usort($terms, function($a, $b) {
return strcmp($a->name, $b->name);
});
foreach ( $terms as $term ) {
$link = get_term_link( $term, $taxonomy, $args_incl );
if ( is_wp_error( $link ) ) {
return $link;
}
$links[] = '<a class="fancybox-incl fancybox.ajax" title="inclusief" href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
Code for the single-[post-type].php:
<?php get_header(); ?>
<?php the_post(); ?>
<script>
$(window).resize(function() {
if ($(this).width() < 1024) {
$('.single-incl-opt-out').hide();
} else {
$('.single-incl-opt-out').show();
}
});
</script>
<section id="inclusief" style="margin-top:15px;">
<div class="col-sm-5 mobile">
<h1 class="extra-title"><?php the_title(); ?></h1>
<div class="tabcontent" id="tab-<?php the_ID(); ?>">
<p><?php the_content(); ?></p>
</div>
</div>
<div class="col-sm-1"></div>
<div class="col-sm-6 no-padding">
<div class="incl">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?>
</div>
</div>
</section>
Your current approach to hiding the content based on media queries and window size is not very mobile friendly and it appears that FancyBox already supports this since it's using jQuery's ajax method. More info on that here: http://www.w3schools.com/jquery/jquery_ajax_load.asp
Update your PHP function that loads the FancyBox to include the id of the div you want to load inside of it:
$links[] = '<a class="fancybox-incl fancybox.ajax" title="inclusief" href="' . esc_url( $link ) . '#inclusief" rel="tag">' . $term->name . '</a>';
A similar question/answer can be found here: Jquery FancyBox target specific DIV ID?
I made a simple image gallery, I'm adding a password protected upload. With some help I'm using this php (thanks to sulthan-allaudeen). Attached the code I'm using.
The problem is that I can't find a way to have on the left side the thumbnails of all the images in the folder, but with this code I have the full-width images only. any idea?
thanks
<body>
<div id="containerfoto">
<div id="gallery">
<div id="minipics">
<?php
$dir = 'Images/photo/';
$files = scandir($dir);
$i = 1;
foreach ($files as $key)
{
if ($i>3)
{
$j = $i-3;
echo "<a href='Images/photo/".$key."'><img src ='Images/photo/".$key."'>".$key."</a>";
}
$i++;
}
?>
<div style="clear:left"> </div>
</div>
<div id="zoom">
<img src="Images/foto/foto7.jpg" id="bigimage" alt="">
<h3 id="titolo">Click to enlarge images.</h3>
</div>
</div>
</div>
<script>
window.onload=function(){
if(!document.getElementById || !document.getElementsByTagName) return;
links=document.getElementById("minipics").getElementsByTagName("a");
for(i=0;i<links.length;i++)
links[i].onclick=function(){Show(this);return(false)}
}
function Show(obj){
bigimg=document.getElementById("bigimage");
bigimg.src=obj.getAttribute("href");
smallimg=obj.getElementsByTagName("img")[0];
t=document.getElementById("titolo");
t.removeChild(t.lastChild);
t.appendChild(document.createTextNode(smallimg.title));
}
</script>
</body>
Scandir() put's the file names within your directory into an array. Therefore, we can print each image using a for loop. I've given you an example below:
<?php
$dir = 'Images/photo/';
$files = scandir($dir);
for($number = 0; $number <= count($files); $number++) { ?>
<div class="thumbnail">
<img src="<?php echo $dir; echo $files{$number} ?>">
</div>
<?php } ?>
Now you just need to apply some css to the .thumbnail class and it should do the trick. For starters, you just need to apply some width and height to .thumbnail img, let me know if you need help with that too.
I am trying to load wordpress post in div using ajax but the jQuery inside it wont work after loading the content. For example i have accordian and slider in loaded page, they also dont work. And also the close button for the loaded div not working too.
I checked this post too Jquery event handler not working on dynamic content
But no sucess.
portfolio.php
<div id="fff">
</div>
<h2 class="ow-heading"><?php the_title(); ?></h2>
<?php the_content(); ?>
<ul class="projectlist clearfix" id="<?php global $post; $post_slug=$post->post_name; echo $post_slug; ?>">
<?php
global $wp_query;
query_posts( array('post_type' => array( 'portfolio' ),'showposts' => 12, 'paged'=>$paged )
);
if (have_posts()) : while (have_posts()) : the_post();
?>
<li class="project">
<a href="<?php the_permalink(); ?>" data-post="" rel="<?php the_ID(); ?>" class="ajax" data-toggle="modal" data-target="#myModal">
<?php if ( has_post_thumbnail() ) { ?>
<?php the_post_thumbnail(); ?>
<?php } ?>
<div class="projectinfo">
<div class="meta">
<h4><?php the_title(); ?></h4>
<h6><em><?php echo get_post_meta($post->ID, "spq_portfolio_tag", true) ?></em></h6>
</div>
</div>
</a>
</li>
<?php endwhile; ?>
<?php else: ?>
<p><?php _e("Sorry, no posts matched your criteria.","arclite"); ?></p>
<?php endif; wp_reset_query(); ?>
</ul>
single-portfolio.php
<?php get_header(); ?>
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<div class="sparq-main">
<div class="insparq-main">
<h1 class="portfolio-single-title"><?php the_title(); ?></h1>
<?php the_content(); ?>
</div>
</div>
<?php endwhile; endif; ?>
<?php get_footer(); ?>
custom.js
jQuery.noConflict();
jQuery(document).ready(function(){
/*----------------------------------------------------*/
/* Sticky Navigation
/*----------------------------------------------------*/
jQuery(".bottommenu").sticky({ topSpacing: 0 });
/*----------------------------------------------------*/
/* Slab Text
/*----------------------------------------------------*/
function slabTextHeadlines() {
jQuery("h1.tagline").slabText({
"viewportBreakpoint":380
});
};
jQuery(window).load(function() {
setTimeout(slabTextHeadlines, 1000);
});
/*----------------------------------------------------*/
/* Parallax
/*----------------------------------------------------*/
jQuery('.sep, .header').each(function(){
jQuery(this).parallax("100%", 0.3);
});
/*----------------------------------------------------*/
/* Accordion
/*----------------------------------------------------*/
jQuery('.accordion').each(function(){
var acc = jQuery(this).attr("rel") * 2;
jQuery(this).find('.accordion-inner:nth-child(' + acc + ')').show();
jQuery(this).find('.accordion-inner:nth-child(' + acc + ')').prev().addClass("active");
});
jQuery('.accordion .accordion-title').click(function() {
if(jQuery(this).next().is(':hidden')) {
jQuery(this).parent().find('.accordion-title').removeClass('active').next().slideUp(200);
jQuery(this).toggleClass('active').next().slideDown(200);
}
return false;
});
/*----------------------------------------------------*/
/* Custom Scroll
/*----------------------------------------------------*/
jQuery("html").niceScroll({cursorborder:"0px solid #fff",cursorwidth:"10px",scrollspeed:"70"});
/*----------------------------------------------------*/
/* Flex Slider
/*----------------------------------------------------*/
jQuery('.testi').flexslider({
selector: ".slides > li",
directionNav: false
});
/*----------------------------------------------------*/
/* Navigation Scroll to Section
/*----------------------------------------------------*/
var device = navigator.userAgent.toLowerCase();
var ios = device.match(/(iphone|ipod|ipad)/);
//function that returns element's y position
jQuery("a[href*=#]").on('click', function(e) {
var scrollTarget = jQuery(this.hash).offset().top;
if(scrollTarget)
e.preventDefault();
if(parseInt(scrollTarget) !== parseInt(jQuery(window).scrollTop())) {
var nav2 = jQuery("nav");
if (ios) nav2.hide();
jQuery('html,body').animate({scrollTop:scrollTarget}, 1000, "swing", function(evt) {
if (ios) {
if(scrollTarget == 0)
nav2.css({position:'absolute', top:jQuery("#intro").height()});
else
nav2.css({position:'absolute', top:scrollTarget});
var nav2clone = jQuery("nav")
nav2clone.show();
}
});
}
});
if (ios) {
jQuery(document).bind('touchmove',function(){
var intro = jQuery("#intro"), nav2 = jQuery("nav");
console.log(nav2.position().top);
if(intro.height() != nav2.position().top)
{
nav2.css({position:'fixed', top:'0px'});
console.log(nav2.position().top);
}
else
{
nav2.css({position:'relative', top: ''});
}
});
}
/*----------------------------------------------------*/
/* Fit Video Responsive
/*----------------------------------------------------*/
jQuery(".spq-video").fitVids();
});
Ajax Call
jQuery("a.ajax").on('click', function(e) {
e.preventDefault();
var url = jQuery(this).attr("href");
jQuery.get(url, function(data) {
jQuery("#fff").show(600).html(data);
var scrollTarget = jQuery("#fff").offset().top;
jQuery('html,body').animate({scrollTop:scrollTarget-80}, 1000, "swing");
});
});
After the page content load with ajax, all the elements associated with custom.js not working, like slider, accordion etc.. which are on loaded content stopped working.
Your code works as-as if you wrap it in a jQuery "ready".
I mocked up a JSFiddle of your page here:
http://jsfiddle.net/NEest/
jQuery(function () {
jQuery(document.body).on('click', 'a.ajax', function () {
var post_url = jQuery(this).attr("href");
var post_id = jQuery(this).attr("rel");
alert(post_url + " - " + post_id);
jQuery("#fff").html('<div class="loading">loading...</div>');
jQuery("#fff").load(post_url).fadeIn(500);
return false;
});
jQuery("a.pclose").click(function () {
jQuery("#fff").fadeOut();
});
});
Please note: JSFiddles do not require the "ready" code as it is a built-in feature (drop-down option on left), but it does not hurt to add it for demonstration purposes.
If you can update the JSFiddle with any remaining issues that will make it easier for everyone to help.
All jquery plugins read the dom of the document when the page load, so n order to enable the jquery functionality on ajax loaded content you have to re initialize the jquery plugins. then your code will work.
Please check my answer on this post as well
I have a news (blog) page where there are only ever three posts shown at a time (this is the page, how far I have now: http://thewhiteoak.fluroltd.com/our-news/). When a user clicks on a post the main header image at the top of the page will reflect the post thumbnail but a larger version (at the top of the page).
I don't want the post to go through to their own page i.e. single.php as there is no need for it. Can this be done from the generic blog page that displays the three posts? The code below is what I have already which links to a larger image but not in place of the news page.
Can anyone shed some light on this situation please. As I'm getting an Uncaught ReferenceError: img_paths is not defined... But I can't seem to get past this.
This is the import for the mooTools scripts:
<?php if (is_page_template('page-ournews.php')) { ?>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/moo_12.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/moo_12_more.js"></script>
<?php } ?>
The Javascript which will find the link and make it replace the current header image for the post thumbnail.
<script>
window.addEvent('domready', function() {
var images = [];
var loadingimages = [];
var loadingimg_path = ['images/loading-bar-black.gif'];
loadingimg_path.each(function(im) {
loadingimages[im] = new Element('img', {
'src': im,
'styles': {
'visibility': 'visible',
'opacity': '0',
'width': '961px',
'height': '382px',
'border': 'none'
}
});
});
<?php $description = get_post_meta($post->ID, "news-image-thumb", $single = true);
if($description !== '') {
//echo $description;
$pattern = '/href=(?<first>[\'|"])(?<href>[^\1]*?)(?P=first)/i';
preg_match_all($pattern, $description, $matches);
$descr = "'".implode("','", $matches['href'])."'";
?>
var img_paths = [<?php echo $descr; ?>];
<?php
}
?>
var loader = new Asset.images(img_paths, {
onProgress: function(counter,index) {
loadingimages[ loadingimg_path[0] ].set('opacity','0').inject($('frame')).fade(1);
},
onComplete: function() {
//fill our img array
img_paths.each(function(im) {
images[im] = new Element('img', {
'src': im,
'styles': {
'visibility': 'hidden',
'width': '961px',
'height': '382px',
'opacity': '0',
'border': 'none'
}
});
});
//assign click events
$$('#sidenav-content a').addEvent('click', function(e) {
e.stop();
$('frame').empty();
images[this.rel].set('opacity','0').inject($('frame')).fade(1);
});
//show first img in frame
$('frame').empty();
//loadingimages[ loadingimg_path[0] ].set('opacity','0').inject($('frame')).fade(1);
images[ img_paths[0] ].set('opacity','0').inject($('frame')).fade(1);
}
});
});
</script>
The code that displays the posts:
<div id="frame" >
<?php $description = get_post_meta($post->ID, "news-image-large", $single = true);
if($description !== '') {
echo str_replace('<img ','<img width="961" height="382" id="laptopimage" ',$description);
}?>
</div>
<div class="post post-page" id="post-<?php the_ID(); ?>">
<div class="post-content our-news">
<?php the_content(); ?>
<ul id="news">
<?php $page = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts("category_name=Our News&showposts=3&paged=$page"); while ( have_posts() ) : the_post(); $loopcounter++; ?>
<li id="postNews" class="post-<?php the_ID(); ?>">
<div class="box">
<?php
<?php if($feature_image_position == 'above'): ?>
<?php if($enable_feature_image == 'yes' && has_post_thumbnail()): ?>
<!--<?php echo theme_TIM_Thumb(317, $feature_image_height); ?>-->
<div id="sidecol">
<div id="sidenav">
<div id="sidenav-content">
<?php if((get_post_meta($post->ID, "news-image-thumb", true))) { ?>
<?php echo get_post_meta($post->ID, "news-image-thumb", true); ?>
<?php } ?>
<br/>
</div><!--sideanv-content-->
</div><!--sideanv-->
</div><!--sidecol-->
<?php endif; ?>
<?php endif; ?>
If I had to guess, this seems like a problem with the interaction between jQuery (which your site appears to be using already) and mooTools (which you added, if I understand correctly). You can start here: Google: mootools noconflict