Deep linking issue with flexslider - javascript

I'm using flexslider for showing custom post type posts. I've managed to get the deep linking to work by adding the post id to each li element and using this to update the url with that id when clicking previous/next.
However I can't get this new link to work when it's pulled up in the browser. The goal is to use this url for sharing on facebook for example. When someone clicks the url it should go to that specific slide.
$(document).ready(function(){
var $flexslider = $('.flexslider');
$flexslider.flexslider({
before:function (slider) {
// get the ID of the slide we are animating to
id = slider.slides[slider.animatingTo].id
// set the URL path to #slideID
history.pushState(null, null, "#" + id);
},
animation: "fade",
touch: false,
slideshow: false,
manualControls: ".flex-control-nav li",
useCSS: false /* Chrome fix*/
});
});
<section id="slider">
<div class="flexslider">
<ul class="slides">
<?php query_posts(array('post_type' => 'juweel','orderby' => 'rand')); if(have_posts()) : while(have_posts()) : the_post();?>
<li data-thumb="<?php the_post_thumbnail_url(); ?>" class="slide" id="<?php the_ID(); ?>">
<?php the_title(); ?>
<?php the_post_thumbnail(); ?>
</li>
<?php endwhile; endif; wp_reset_query(); ?>
</ul>
</div>
</section>
I know I can get the current location hash by using
var hash = window.location.hash;
But I have no clue how to check if the value matches the id of one of my slides and make it go there

Related

Results in words with space don't show in php gallery

I'm creating a gallery in php, where it has a filter divided into categories. But when a word has a space it doesn't show the associated images.
I'm working on two tables, one that creates the categories and the other that is from the gallery.
This is my code and the sql queries:
Querys:
$sql = "selec categoria AS categoria_formatted from cat_lar";
$galerialar = $connect->query($sql);
$sql = "select foto,categoria_lar from galeria_lar,cat_lar Where categoria_lar=categoria";
$galerialarconde = $connect->query($sql);
Code:
<div class="popular page_section">
<div class="container">
<div class="row">
<div align="center">
<button class="filter-button" data-filter="all">All</button>
<?php mysqli_data_seek($galerialar, 0);
while( $galerialarc = $galerialar -> fetch_assoc()){ ?>
<button class="filter-button" data-filter="<?php echo $galerialarc['categoria_formatted']?>"><?php echo $galerialarc['categoria_formatted']?></button>
<?php } ?>
</div>
<br/>
<?php
while( $galerialarc = $galerialarconde -> fetch_assoc()){ ?>
<div class="gallery_product col-sm-3 col-xs-6 filter <?php echo $galerialarc['categoria_lar']?>">
<a class="fancybox" rel="ligthbox" href="admin/galeria/uploads/<?php echo $galerialarc['foto']?>">
<img class="img-responsive" alt="" src="admin/galeria/uploads/<?php echo $galerialarc['foto']?>" width="150px" />
</a>
</div>
<?php }?>
</div>
</div>
</div>
SCRIPT:
<script>
$(document).ready(function(){
$(".filter-button").click(function(){
var value = $(this).attr('data-filter');
if(value == "all")
{
$('.filter').show('1000');
}
else
{
$(".filter").not('.'+value).hide('3000');
$('.filter').filter('.'+value).show('3000');
}
if ($(".filter-button").removeClass("active")) {
$(this).removeClass("active");
}
$(this).addClass("active");
});
});
/* end gallery */
$(document).ready(function(){
$(".fancybox").fancybox({
openEffect: "none",
closeEffect: "none"
});
});
</script>
Can they help me? Because I've already tried to put the words with "_" and replace and it remained the same
As you suggest yourself, the image URLs can't contain whitespaces. If you already tried to replace whitespaces with underscores (_) , remember to upload the image files with that name and replace the foto url in the database with the new images.
If it doesn't work, try to investigate where exactly the problem occurs. Is the queries returning the right results (try to var_dump() the result and see if they are missing. If you think the problem happends in the HTML, try using your "inspect" feature in your browser and see if a source URL is provided for the image element and check if this URL really has an image.

Use Slick Slider as WP Post Navigation

I'm trying to use slick slider as the Previous and Next buttons on a WordPress single CPT page.
So the slider would call all the posts of a specific CPT and show the featured image of the current post and on either side it would show the featured image of the previous and next posts.
As you navigate through the slide the corresponding content would appear.
The problem is that as you slide through you'll get the correct images and content, but the URL stays the same. Also you can't link to a specific post because it'll just go to the beginning of the slide.
Right now, this is what my single-CPT.php looks like
<?php
get_header();
rewind_posts();
if (have_posts()) {
while ( have_posts() ) : the_post();
$post_id = get_the_ID();
?>
// BEGIN SLIDER (WHERE FEATURED IMAGES ARE THE SLIDES)//
<section class="slider center">
<?php
$index = 0;
$carousel_args = array(
'post_type' => 'CPT',
'posts_per_page' => -1,
);
$carousel_query = new WP_Query( $carousel_args );
if ( $carousel_query->have_posts() ) {
while ( $carousel_query->have_posts() ) {
$carousel_query->the_post();
$title = get_the_title();
$link = get_permalink();
if ( has_post_thumbnail() ) {
$post_thumbnail_id = get_post_thumbnail_id();
$post_thumbnail_image = wp_get_attachment_image_src( $post_thumbnail_id, 'large' );
$post_thumb = $post_thumbnail_image[0];
} else {
$post_thumb = '';
}
$content = get_the_content();
$excerpt = get_the_excerpt();
// output//
?>
<div class="wow slide-in slide">
<div class="active">
<a href="<?php echo $link; ?>">
<img src="<?php echo $post_thumb; ?>" />
</a>
</div>
</div>
<?php $index++;
}
}
wp_reset_postdata();
endwhile;
?>
</section>
//END SLIDER - BEGIN CONTENT//
<div id="archive-post">
<div class="row">
<div class="columns small-12 medium-10 medium-offset-1 large-offset-0 large-8">
<article id="post-<?php the_ID(); ?>" role="article">
<div class="post-title">
<div class="row">
<div class="columns">
<h3><?php the_title(); ?></h3>
</div>
</div>
</div>
<div class="post-content">
<div class="row">
<div class="columns">
<?php the_content(); ?>
</div>
</div>
</div>
</article>
</div>
</div>
</div>
Basically I need the URL to update along with the slide without refreshing the page. Is there any way to accomplish this?
Okay, so with a ton of help from a friend, I found a way to do this with the magic of AJAX and HTML5 Apis
Basically what you have to do is use the HTML5 Api to manipulate the browser's history, and use AJAX to load the desired content without refreshing. Here's what it ended up looking like:
The single post template stayed pretty much the same except I changed the slide query output a little from
<a href="<?php echo $link; ?>">
to
<a href="<?php echo $link; ?>" class="js-switchSlide" data-ajaxurl="<?php echo admin_url('admin-ajax.php'); ?>" data-title="<?php echo get_the_title(); ?>" data-id="<?php echo get_the_ID(); ?>">
I added the js-switchSlide class to be able to call it in my JS and AJAX functions later.
I added a couple of data attributes (data-ajaxurl,data-title, and data-id) that I will use in the ajax function.
The content section has been changed too, notice the new classes and id's
<div id="archive-post">
<div class="row">
<div class="columns small-12 medium-10 medium-offset-1 large-offset-0 large-8">
<article id="post-<?php the_ID(); ?>" <?php post_class( array('post-page', 'js-slideContainer') ); ?> role="article">
<input type="hidden" id="currentSlide" value="<?php the_ID(); ?>">
<div class="post-title">
<div class="row">
<div class="columns">
<h3 class="js-slideTitle"><?php the_title(); ?></h3>
</div>
</div>
</div>
<div class="post-content">
<div class="row">
<div class="columns js-slideContent">
<?php the_content(); ?>
</div>
</div>
</div>
</article>
</div>
</div>
</div>
Here is the JS:
$(document).ready(function() {
This is used later to see whether the actual slide or the button was clicked
`var clickedSlide = true;`
Initiate the slide
$navslider = $('.slider').slick({
centerMode: true,
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
arrows: true,
focusOnSelect: true,
Here I make the slide responsive
`responsive: [
{
breakpoint: 1068,
settings: {
initialSlide: 0,
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
}
},
{
breakpoint: 768,
settings: {
initialSlide: 0,
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
}
},
{
breakpoint: 480,
settings: {
initialSlide: 0,
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
}
},]
});`
Here is my Ajax call
`function slidesAjaxCall(slideID, slideTitle, slideHref, ajaxurl) {`
This part just makes the loading of the content a little smoother by fading it in and out.
`$( '.js-slideContainer' ).animate({
opacity: 0
}, 320);`
This is where I manipulate the browser history
`history.pushState(null, slideTitle, slideHref);
document.title = slideTitle;`
Here is where I place the values from the data attributes using POST method. Type is just the custom post type and action is the name of the Ajax function.
$.ajax({
url : ajaxurl,
method: 'POST',
data: {
id: slideID,
type : 'CPT',
action: 'hc_load_slide'
},
Self explanatory
`error : function( response ){
console.log('error');
},`
If successful:
`success : function( response ){
if( response === 0 ){
console.log('no slide found');
$( '.js-slideContainer' ).animate({
opacity: 1
}, 320);
} else {`
The post data is collected in the Ajax function in JSON format so it has to be parsed and inserted into the html
`var data = JSON.parse(response);
$( '.js-slideTitle' ).text(data.title);
$( '.js-slideContent' ).html(data.content);`
Make it behave nicely
`setTimeout(function(){
$( '.js-slideContainer' ).animate({
opacity: 1
}, 320);
}, 100);
}
}
});
}`
.js-switchSlide is the class in the a tag so I prevent it from going refreshing the page when clicked.
`$('.js-switcSlide').click(function(e){
e.preventDefault();`
This says that the slide was clicked, this will keep it from calling the ajax function twice
`clickedSlide = true;`
Collect all the values from the data attributes:
`var babyID = e.currentTarget.dataset.id;
var babyTitle = e.currentTarget.dataset.title;
var babyHref = e.currentTarget.href;
var ajaxurl = e.currentTarget.dataset.ajaxurl;`
Call the function
`babiesAjaxCall(babyID, babyTitle, babyHref, ajaxurl);
});`
Okay this next part loads the appropriate slide and content using the permalink. Remember, one of the issues was that I could get the slide to work fine, but when I navigated to a specific post the slide would start from the beginning.
`var currentSlideID = $( '#currentSlide' ).val();
var $slide = $(".slider [data-id='" + currentSlide + "']");
var slideIndex = $slide.parents('.slide').data("slick-index");
$babyslider.slick("goTo", slideIndex);
/* Trigger Ajax call if Chevron is clicked and not Slide */
$slider.on('afterChange', function(event, slick, currentSlide, nextSlide){
// Stop if clieckedSlide === true;
if (clickedSlide) {
clickedSlide = false;
return;
}
var slideIndex = $('[data-slick-index="' + currentSlide + '"]').find('.js-switchSlide');
var slideID = slideIndex.data('id');
var slideTitle = slideIndex.data('title');
var slideHref = slideIndex.attr('href');
var ajaxurl = slideIndex.data('ajaxurl');
babiesAjaxCall(babyID, babyTitle, babyHref, ajaxurl);
});
});`
Meanwhile, the Ajax function looks like this
`add_action( 'wp_ajax_nopriv_hc_load_slide', 'hc_load_slide' );
add_action( 'wp_ajax_hc_load_slide', 'hc_load_slide' );
function hc_load_baby() {
$id = $_POST["id"];
$type = $_POST["type"];
// echo $id . ' - ' . $type;
$args = array(
'post_type' => $type,
'p' => $id,
);
$slide = new WP_Query( $args );
if ( $slide->have_posts() ) :
while ( $slide ->have_posts() ) : $slide->the_post();
$title = get_the_title();
$content = apply_filters('the_content', get_the_content() );
endwhile;
endif;
echo json_encode([ 'title' => $title, 'content' => $content ]);
die();
}`
I know it's a long answer, but I hope that makes sense. It accomplishes exactly what I wanted. Thanks alecaddd for the lessons.

how to redirect to other page and dynamically load content of corresponding id on click

i'm working on a project and i want to do following: on the home page i have divs which are dynamically loaded from database, now when i click on the div i want it to redirect to new page and then load corresponding content only, from database, just like a blog website, when you click on an article on homepage and it loads an article from database on the new page, i know it must be a simple process but i couldn't find how to write all that code, so can anyone help me with that?
thank you in advance
this is my home page:
<?php
require_once 'core/init.php';
include 'includes/head.php';
include 'includes/nav.php';
include 'includes/section1.php';
$sql = "SELECT * FROM topics WHERE featured = 1";
$featured = $db->query($sql);?>
<section class="s2">
<div class="grid_container">
<?php while($article = mysqli_fetch_assoc($featured)) : ?>
<div class="floating-box" onclick="loadart(<?= $article ['id']; ?>)">
<img src="<?= $article ['image']; ?>" class="img-responsive" alt="<?= $article ['title']; ?>">
<div class="grid_content_wrapper">
<br>
<p><?= $article ['subtitle']; ?></p>
<h3><?= $article ['title']; ?></h3>
<p><?= $article ['description']; ?></p>
</div>
</div>
<?php endwhile; ?>
</div>
</section>
<section class="s3">
<button class="more_posts"><h3>MORE AMAZING THINGS</h3></button>
</section>
<?php
include 'includes/footer.php';?>
now when i click on the div floating box i want it to redirect to this page and load content from database depending on the div i clicked i used this script but it only redirects and loads all content from database but i want it to load based on id of the corresponding div:
function loadart(id) { var data = {"id" : id}; window.location.href = "single.php";}
So let's say you have <div class="clickDiv">www.somedomain.com</div>
You want to set up an event handler that will listen for it, find out what domain is in the div and then redirect the user to that URL.
'$(".clickDiv").mousedown(function(){
var url = $(this).text();
window.location.href = url;
});
So what has happened here is that if all of your divs have the class "ClickDiv", the event listener knows when it's been clicked on and then redirects to the URL in that div.

jQuery - Get Dynamic (*) Element By Id and put on array

I'm working to create a classifieds site. On the search page will be presented multiple products cards. Each product card can have more than one image. When that happens, I will uses a slider.
To build this slider, I'm using a jquery library (bxslider). The application is based on WordPress.
So far, everything was going well. Cards and slider working. But when I have more than one card (post), the slider controls change the position on all cards. Of course, since the selector is the same for everyone.
Then I added the post ID to the ID selector, making every single card. But now must do jQuery understand that there are several unique cards for him to apply the function that creates the slides within each card.
My PHP Code
<?php
$id = get_the_ID();
?>
<div id="card-slider-<?php echo $id?>">
<?php
$images = get_post_meta($post->ID, 'vdw_gallery_id', true);
foreach ($images as $image) { ?>
<li>
<div class="card-slide-item">
<img src="<?php echo wp_get_attachment_url( $image, 'imob-thumbs' ); ?>">
</div>
</li>
<?php }
?>
</div>
<div class="card-slide-prev"></div>
<div class="card-slide-next"></div>
My jQuery
(function( $ ){
$.fn.sliderID = function() {
var sliders = [];
sliders = $('[idˆ=card-slider-]').length;
console.log('sliders ids', sliders);
};
})( jQuery );
$(document).ready(function(){
$.fn.sliderID();
});
Instead of giving each slider an individual id card-slider-{id}, consider to give them all a common class card-slider and initiate the slider plugin on all elements that have that class. You can pass along the ids of the prev/next selectors (which you can e.g. store in a data attribute) in the initialization arguments of the slider:
Slider initiation
$( ".card-slider" ).each(function( index ) {
var slider_id = $(this).data('id');
$( this ).bxSlider({
nextSelector: '#card-slide-'+slider_id+'-next',
prevSelector: '#card-slide-'+slider_id+'-prev',
});
});
Markup:
<?php
$id = get_the_ID();
?>
<div class="card-slider" data-id="<?php echo $id; ?>">
<?php
$images = get_post_meta($post->ID, 'vdw_gallery_id', true);
foreach ($images as $image) { ?>
<li>
<div class="card-slide-item">
<img src="<?php echo wp_get_attachment_url( $image, 'imob-thumbs' ); ?>">
</div>
</li>
<?php }
?>
</div>
<div id="card-slide-<?php echo $id; ?>-prev"></div>
<div id="card-slide-<?php echo $id; ?>-next"></div>

Bring a WordPress post dynamically

I've been trying to make this feature work for many days now and it's driving me nuts!
I have a single page theme in WP and in one of them there is a div on the left with a list of the posts in the site and on the right, a div that should display the content of the clicked post.
I found this question and followed up the linked tutorial and was partially successful.
I managed to bring the content dinamically, and all I want is being displayed but it seems the order of the tasks are wrong. Heres how it's acting:
I click on the link.
the current content goes away.
the loading span appears correctely.
the SAME content fades in.
after 1 second or so the current content is replaced with the new content and the address bar does not change at all.
Here's the code I have:
atracoes.js
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('.controle nav li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href)){
var aCarregar = hash+'.html #atr-conteudo';
$('#atr-conteudo').load(aCarregar)
}
});
$('.controle nav li a').click(function() {
var aCarregar = $(this).attr('href')+' #atr-conteudo';
$('#atr-conteudo').hide('fast',carregarConteudo);
$('#carregando').remove();
$('#atracoes').append('<span id="carregando">Carregando...</span>');
$('#carregando').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href'));
function carregarConteudo () {
$('#atr-conteudo').load(aCarregar,'',mostrarNovoConteudo());
}
function mostrarNovoConteudo () {
$('#atr-conteudo').show('normal',esconderCarregando());
}
function esconderCarregando () {
$('#carregando').fadeOut('normal');
}
return false;
});
});
index.php (the dynamic content part)
<div class="main" id="atracoes">
<div class="controle">
<nav>
<?php
$args = array( 'posts_per_page' => 20);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<li>
<?php the_title(); ?>
</li>
<?php endforeach;
wp_reset_postdata();?>
</nav>
</div>
<div id="atr-conteudo">
<?php the_post_thumbnail(); ?>
<div id="atr-texto">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</div>
</div>
</div>
single.php (the part I'm plucking with ajax)
<!-- article -->
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<!-- post thumbnail -->
<?php if ( has_post_thumbnail()) : // Check if Thumbnail exists ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail(); // Fullsize image for the single post ?>
</a>
<?php endif; ?>
<!-- /post thumbnail -->
<div id="atr-texto">
<!-- post title -->
<h1>
<?php the_title(); ?>
</h1>
<!-- /post title -->
<?php the_content(); // Dynamic Content ?>
<?php edit_post_link(); // Always handy to have Edit Post Links available ?>
</div>
</article>
You're calling the functions before you pass them to jQuery to execute, instead of allowing jQuery to execute them:
function carregarConteudo () {
$('#atr-conteudo').load(aCarregar,'',mostrarNovoConteudo);
}
function mostrarNovoConteudo () {
$('#atr-conteudo').show('normal',esconderCarregando);
}
(Notice they no longer have () after the function names)

Categories

Resources