wordpress plugin accessing post info - php

I am a novice to wordpress plugin development. I am trying to access the post information and based on if it is having a featured image I am creating a slide show. But the image url and post title are going out of my div tag. Below is my code.
//function to display post info
function postsinfo_collage_display($attr, $content) {
$plugins_url = plugins_url();
$html = '<div id="pscanvas" class="row">
<div class="row__inner mThumbnailScroller">';
// The Query
query_posts( array ('orderby' => 'date' ) );
// The Loop
while ( have_posts() ) : the_post();
if ( has_post_thumbnail() ) {
$html .= '<div class="tile">
<div class="tile__media">';
$html .='<a href="'.esc_url(get_permalink()).'">';
$html .='<img class="tile__img"';
$html .="src='".esc_url(the_post_thumbnail_url()). "'/>";
$html .='</a></div><div class="tile__details">
<div class="tile__title">';
$html .= the_title();
$html .='</div></div></div>';
}
endwhile;
// Reset Query
wp_reset_query();
$html .= '</div>
</div>
<script>
window.jQuery || document.write(\'<script src="minified/jquery-1.11.0.min.js"><\/script>\')
(function($){
$(window).load(function(){
});
})(jQuery);</script>';
return $html;
}
The output I am getting is:
<div class="entry-content">
http://localhost:9085/wordpress/wp-content/uploads/2016/04/call-of-duty-ghosts-20517-1366x768-1200x675.jpgpscanvashttp://localhost:9085/wordpress/wp-content/uploads/2016/04/Call-Of-Duty-Ghost-Background-For-Wallpaper-652-1200x675.jpgkwofkwc
<div id="pscanvas" class="row">
<div class="row__inner mThumbnailScroller ">
<div id="mTS_1" class="mTSWrapper mTS_horizontal">
<div class="mTSAutoContainer mTSContainer" ">
<div class="tile">
<div class="tile__media">
<a href="http://localhost:9085/wordpress/2016/09/04/pscanvas/">
<img class="tile__img" src=""></a>
</div><div class="tile__details">
<div class="tile__title"></div></div></div>
<div class="tile"><div class="tile__media">
<a href="http://localhost:9085/wordpress/2016/05/03/kwofkwc/">
<img class="tile__img" src=""></a></div><div class="tile__details">
<div class="tile__title"></div></div></div>
</div>
</div>
</div>
</div>
<script>
window.jQuery || document.write('<script src="minified/jquery-1.11.0.min.js"><\/script>')
(function($){
$(window).load(function(){
});
})(jQuery);</script>
<strong>Album Rating:</strong> <div class="genericon genericon-star"></div><br> </div>
I can see the image url should be inside the img tag but its coming out of the entire div tag.

You're using functions that directly output the image and title rather than appending it to your $html variable. You need to switch to functions that return a value instead.
Change the image from:
$html .="src='".esc_url(the_post_thumbnail_url()). "'/>";
To:
$html .= "src='" . esc_url( get_the_post_thumbnail_url() ) . "'/>";
And the title from:
$html .= the_title();
To:
$html .= get_the_title();
Docs:
https://developer.wordpress.org/reference/functions/get_the_title/
https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/

Try
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
<img src="<?php echo $url; ?>"/>

Related

Wordpress use query as AJAX

I have a custom field selectbox where I chose which Posts I want to be displayed. Now I want the query, where I get the selected Posts and its custom fields, to somehow be used as an AJAX-call so that I can use the data-output to build a masonry-grid. Is that possible?
here is my data/query:
$posts = get_field('choose_artist');
if( $posts ): ?>
<?php foreach( $posts as $p ): ?>
<div class="artist">
<a href="<?php echo get_permalink( $p->ID ); ?>">
<div style="position: relative;">
<?php $image = get_field('artist_image', $p->ID); ?>
<div class="artist-image" style="background-image:url('<?php echo $image['url']; ?>')"></div>
<div class="overlay">
<div class="content">
<p><?php the_field('artist_name', $p->ID); ?></p>
</div>
</div>
</div>
</a>
</div>
<?php endforeach; ?>
So, my goal is something like:
$.ajax({
url: '/the query above',
success: function(data){
data is the query html
}})
Is that even possible?
ajax.php
$content = '';
if( $posts ) {
foreach( $posts as $p ) {
$image = get_field('artist_image', $p->ID);
$content .= '<div class="artist">';
$content .= '<a href="' . get_permalink( $p->ID ) . '">';
$content .= '<div style="position: relative;">';
$content .= '<div class="artist-image" style="background-image:url("' . $image['url'] . '")"></div>';
$content .= '<div class="overlay">';
$content .= '<div class="content">';
$content .= '<p>' . get_the_field('artist_name', $p->ID). '</p>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</a>';
$content .= '</div>';
}
}
echo $content;
main.js / .php (whereever you have the ajax call)
$.ajax({
url: '/ajax.php', //Path to the ajax.php script
success: function(data){
console.log(data);
}});
Check the documentation for how to catch errors, check for success etc. etc: http://api.jquery.com/jquery.ajax/
There are better ways to do the AJAX page, so refactor it and make it neater, but something similar to the above should work for you if I am understanding your needs, though you'll probably need to tweak it to get what you want.

Displaying Connected Posts in a Grid using PHP Loop

I've been searching through the forums and Google for a few days on how to resolve this and have yet to find a solution. Any assistance would be greatly appreciated.
Bottom line, I am looking to achieve this:
Speaker Section
Using Firebug to inspect the element, I've determined which classes apply:
<div class="et_pb_section et_pb_section_8 et_pb_with_background et_section_regular">
<div class=" et_pb_row et_pb_row_6">
<div class="et_pb_column et_pb_column_4_4 et_pb_column_10">
<div class="et_pb_blog_grid_wrapper">
<div class="et_pb_blog_grid clearfix et_pb_module et_pb_bg_layout_ et_pb_cpt_loop_archive_0 et_pb_cpt_archive_grid" data-columns="">
<div class="et_pb_row et_pb_row_cpt et_pb_row_4col">
<div class="et_cpt_container_column et_pb_column et_pb_column_1_4 et_pb_column_0">
<div class="et_pb_section et_pb_section_10 et_section_regular">
<div class=" et_pb_row et_pb_row_7">
<div class="et_pb_column et_pb_column_4_4 et_pb_column_11">
<div class="et_pb_module et-waypoint et_pb_image et_pb_animation_off desaturate et_pb_cpt_featured_image2_0 et_always_center_on_mobile et-animated">
<a href="http://meetingoftheminds.org/speaker/scot-rourke"><img src="http://meetingoftheminds.org/wp-content/uploads/2017/03/Scot-Rourke.jpg" alt="">
</a>
</div>
<div class="clearfix et_pb_module et_pb_bg_layout_light et_pb_text_align_left et_pb_cpt_title_0">
<h2 itemprop="name" class="cpt_title page_title entry-title">Scot Rourke</h2>
</div>
<div class="clearfix et_pb_module et_pb_acf_single_item_0">
<div class="sb_mod_acf_single_item clearfix">
<p>‎Chief Information and Transformation Officer, Technology, Innovation & Performance</p>
</div>
</div>
<div class="clearfix et_pb_module et_pb_acf_single_item_1">
<div class="sb_mod_acf_single_item clearfix">
<p>Cuyahoga County</p>
</div>
</div>
</div>
<!-- .et_pb_column -->
</div>
<!-- .et_pb_row -->
</div>
<!-- .et_pb_section -->
</div>
I then tried to tailor this to my PHP Loop but the result is radically different than expected.
Here is the snippet of the original loop:
<?php
// Get the connected posts
$my_connected_posts = Post_Connector::API()->get_children( "sessions-to-speakers", get_the_id() );
// Check
if ( count( $my_connected_posts ) > 0 ) {
// Loop
foreach ( $my_connected_posts as $my_connected_post ) {
// Display the featured image, title with link, job, and company
echo get_the_post_thumbnail( $my_connected_post, 'thumbnail') . "<br/>";
echo "<a href='" . get_permalink( $my_connected_post->ID ) . "'>" . $my_connected_post->post_title . "</a>" . "<br/>";
echo get_field("job", $my_connected_post) . "<br/>";
echo get_field("company", $my_connected_post) . "<br/>";
}
}
?>
Original loop displays posts vertically down the page as shown here:
Connected Posts
Here is the snippet of the modified loop, using the "Speaker Section" classes, which only seems to resize the thumbnails:
<!-- Speaker Section -->
<div class="et_pb_section et_pb_section_8 et_pb_with_background et_section_regular">
<div class=" et_pb_row et_pb_row_6">
<div class="et_pb_column et_pb_column_4_4 et_pb_column_10">
<div class="et_pb_blog_grid_wrapper">
<div class="et_pb_blog_grid clearfix et_pb_module et_pb_bg_layout_ et_pb_cpt_loop_archive_0 et_pb_cpt_archive_grid" data-columns="">
<div class="et_pb_row et_pb_row_cpt et_pb_row_4col">
<?php
// Get the connected posts
$my_connected_posts = Post_Connector::API()->get_children( "sessions-to-speakers", get_the_id() );
// Check
if ( count( $my_connected_posts ) > 0 ) {
// Loop
foreach ( $my_connected_posts as $my_connected_post ) {
// #speaker section
echo '<div class="et_cpt_container_column et_pb_column et_pb_column_1_4 et_pb_column_0"><div class="et_pb_section et_pb_section_10 et_section_regular">';
echo '<div class=" et_pb_row et_pb_row_7">';
echo '<div class="et_pb_column et_pb_column_4_4 et_pb_column_11">';
// Display the featured image, title with link, job, and company
echo '<div class="et_pb_module et-waypoint et_pb_image et_pb_animation_off desaturate et_pb_cpt_featured_image2_0 et_always_center_on_mobile et-animated">';
echo get_the_post_thumbnail( $my_connected_post, 'thumbnail') . "<br/>";
echo '</div>';
echo '<div class="clearfix et_pb_module et_pb_bg_layout_light et_pb_text_align_left et_pb_cpt_title_0">';
echo "<a href='" . get_permalink( $my_connected_post->ID ) . "'>" . $my_connected_post->post_title . "</a>" . "<br/>";
echo '</div>';
echo '<div class="clearfix et_pb_module et_pb_acf_single_item_0">';
echo '<div class="sb_mod_acf_single_item clearfix">';
echo get_field("job", $my_connected_post) . "<br/>";
echo '</div>';
echo '</div>';
echo '<div class="clearfix et_pb_module et_pb_acf_single_item_1">';
echo '<div class="sb_mod_acf_single_item clearfix">';
echo get_field("company", $my_connected_post) . "<br/>";
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>

Dynamically change background image in the CSS during WordPress loop (media queries)

I currently have a carousel on my page inside a Wordpress loop. So as it loops through it changes the background image according to which post I am currently on in the loop. However, I want to use media queries to load smaller images if for instance I the screen size is smaller.
This is what I currently have:
while( $loop->have_posts() ) : $loop->the_post();
$class = '';
// Custom Posts
$carousel_image_1 = get_field('carousel_image_1');
$image_1_title = get_field('image_1_title');
if( $slide_counter == 0 ) { $class .= ' active'; }
?>
<div class="item <?php echo $class ?> <?php echo "slide_" . $slide_counter ?>">
<!-- Set the first background image using inline CSS below. -->
<a href="<?php echo get_post_permalink(); ?>" target="_blank">
<div class="fill" style="background-image:url(<?php echo $carousel_image_1['url']; ?>); background-size:cover;" alt="<?php echo $carousel_image_1['alt']; ?>"> </div>
<div class="carousel-caption">
<h2><?php echo $image_1_title; ?></h2>
<img width="80" class="book" src="<?php bloginfo('stylesheet_directory'); ?>/assets/img/book.png" alt="">
</div>
</a>
</div>
<?php $slide_counter++; ?>
<?php endwhile; wp_reset_query(); ?>
You can't use media queries inline, and you won't be able to have the dynamic flexibility of your variables in CSS, because PHP is server-side.
But, you could do this with JavaScript as long as the JS is able to get the PHP variables (my example uses jQuery):
<?php
while( $loop->have_posts() ) : $loop->the_post();
$class = '';
// Custom Posts
$carousel_image_1 = get_field('carousel_image_1');
$carousel_image_2 = get_field('carousel_image_2'); // added this, for different size image
$image_1_title = get_field('image_1_title');
if( $slide_counter == 0 ) { $class .= ' active'; }
?>
<div class="item <?php echo $class ?> <?php echo "slide_" . $slide_counter ?>">
<a href="<?php echo get_post_permalink(); ?>" target="_blank">
<div class="fill" style="background-size:cover;" alt="<?php echo $carousel_image_1['alt']; ?>"> </div>
<div class="carousel-caption">
<h2><?php echo $image_1_title; ?></h2>
<img width="80" class="book" src="<?php bloginfo('stylesheet_directory'); ?>/assets/img/book.png" alt="">
</div>
</a>
</div>
<script>
var resizeTimer;
function resizer() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
var windowWidth = $(window).width();
if (windowWidth >= 992) { // for width 992 pixels and up
$('.fill').css({
'background-image': 'url(<?php echo $carousel_image_1["url"]; ?>)';
});
} else { // smaller sizes
$('.fill').css({
'background-image': 'url(<?php echo $carousel_image_2["url"]; ?>)';
});
}
}, 200);
}
resizer();
$(window).on('resize', resizer);
</script>
<?php $slide_counter++; ?>
<?php endwhile; wp_reset_query(); ?>
I haven't tested it but I think it should work. You can also adjust the timeout to your preference (right now it's 200ms).
Or if you wanted to not make it truly responsive, and just set the background on page load, you could just write:
<script>
if (windowWidth >= 992) { // for medium size width and up
$('.fill').css({
'background-image': 'url(<?php echo $carousel_image_1["url"]; ?>)';
});
} else { // smaller sizes
$('.fill').css({
'background-image': 'url(<?php echo $carousel_image_2["url"]; ?>)';
});
}
</script>
The following Html CSS will show image in mobile view only
Html:
foreach($data as $item):
echo "
<div class='col-lg-4'>
<div class='panel panel-primary backImg' style='background-image:url({$item['imageLink']}); background-size:100% 100%;'>
Some Text
</div>
</div>";
endforeach;
Css:
#media(min-width: 480px){
.backImg{
background-image:none !important;
}
}

Declare inline background image in functions.php

I'm not sure if this can be done as I cannot find anything to help me anywhere no matter how hard i try. I'm using Ajax to load to in posts on the press of the button. the posts that are loaded in are formatted by my function inside my functions.php. That all works perfetly,the issue i'm having is the background-image: property needs to be inline css so that it can pull the image from my custom field. This all works perfectly in the template file, however. no matter what I try the functions.php rejects my inline style for background image no matter what I try.
Here's my If statement in it's entirety:
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
if ($_SESSION["load_type"] == 'home')
{
$out .= '<div class="small-6 large-3 columns end thumb">
<div class="grid">
<figure class="effect-zoe">
'.get_the_post_thumbnail( get_the_ID(), $size, $attr ).'
<figcaption>
<h2>'.get_the_title().'</h2>
<hr class="light">
<p class="description">'.get_the_content().'</p>
</figcaption>
</figure>
</div>
</div>';
}
else
if ($_SESSION["load_type"] == 'category')
{
$out .= '<div class="small-6 large-6 columns end thumb under">
<div id="case">
<div class="th" id="element" >
<a class="fill-div" href="'. get_permalink($post->ID) .'"></a>
</div>
</div>
<div class="brief">
'.get_the_title().'
<p class="suppy">Supplier</p>
<p>'.get_the_excerpt().'</p>
<a class="more-btn" href="'. get_permalink($post->ID) .'">More</a>
</div>
</div>';
}
else
if ($_SESSION["load_type"] == 'product')
{
$out .= '<div class="small-6 large-3 columns">
<div class="small-6 large-12 columns end no-pad morepro" style="background-image: url(''.the_field(product_image).'')">
<a class="fill-div" href="'. get_permalink($post->ID) .'"></a>
</div>
<h2 class="product-load">'.get_the_title().'</h2>
</div>';
}
endwhile;
endif;
wp_reset_postdata();
die($out);
and heres the part of it that I'm having trouble with and crashes the whole site every time I try to load in a background-image:
if ($_SESSION["load_type"] == 'product')
{
$out .= '<div class="small-6 large-3 columns">
<div class="small-6 large-12 columns end no-pad morepro" style="background-image: url(' '.the_field(product-image).' ')">
<a class="fill-div" href="'. get_permalink($post->ID) .'"></a>
</div>
<h2 class="product-load">'.get_the_title().'</h2>
</div>';
}
enter code here
Can anyone see where I'm going wrong?
Change the following
style="background-image: url(' '.the_field(product-image).' ')"
into the
style="background-image: url('.the_field("product-image").')"
This should work if:
Your "product-image" is custom defined size (if its constant use it without quotes) - or edit your question and explain what it is.
the_field() function need to "return" value and not to echo it. I am mentioning this because by wordpress codex usually use "the_something()" function will not return value, it will just display something. If you want to to return a value it is usually "get_the_something()". It is important because it will break your json object (if that is what you are using on js side)
Example: the_content() vs get_the_content(), or get_the_title() vs the_title() etc...
Quotes within background-image should be optional by this.
if ($_SESSION["load_type"] == 'product'){
$image = the_field(product_image);
$out .= '<div class="small-6 large-3 columns">
<div class="small-6 large-12 columns end no-pad morepro" style="background-image: url('"'.$image.'"')">
<a class="fill-div" href="'. get_permalink($post->ID) .'"></a>
</div>
<h2 class="product-load">'.get_the_title().'</h2>
</div>';
}
and see if it works

Why is my wordpress shortcode not following closing tag?

This is my plugin:
add_shortcode('twitter', function($atts, $content) {
// print_r($atts); die();
if (!isset($atts['username']) ) $atts['username'] = 'att';
if ( empty($content) ) $content = 'Follow me on Twitter';
// shortcode_atts
$content .= '<div style="font-family: Arial, sans-serf">';
$content .= '<h2 style="color:orange">My Plugin here!</h2>';
$content .= '<a style="color:blue" href="http://twitter.com/' . $atts['username'] .'">' . $content .'</a></div>';
return $content;
});
I'm expecting just a div with
<div>
<h2>My Plugin here!</h2>
Please follow me everybody!
</div>
But instead I'm getting the following:
<div>
<h2>My Plugin here!</h2>
Please follow me everybody!
<div>
<a href="http://twitter.com/envatowebdev">
<h2>My Plugin here!</h2>
</a>
</div>
I think it's because Wordpress is reading my closing `[/twitter]' tag as a new shortcode:
[twitter username="envatowebdev"]Please follow me everybody![/twitter]
But the same problem isn't happening for the author of this tutorial I'm following, and I am in HTML text edit mode so I'm not sure why this is going on.
Link to post: http://attapi.com/new-post/
[twitter username="envatowebdev"]Please follow me everybody![/twitter]
Try this way:
function testf($atts, $content = "") {
// print_r($atts); die();
if (!isset($atts['username']) ) $atts['username'] = 'att';
if ( empty($content) ) $content = 'Follow me on Twitter';
// shortcode_atts
ob_start();
?>
<div style="font-family: Arial, sans-serf">
<h2 style="color:orange">My Plugin here!</h2>
<a style="color:blue" href="http://twitter.com/<?php echo $atts['username']; ?>"><?php echo $content; ?></a></div>
</div>
<?php
$content = ob_get_contents();
ob_end_clean();
return $content;
}

Categories