how to use the post ID in as a shortcode attribute? - php

I have created a custom post type in WordPress. I want use the post ID in a shortcode so I can pull specific posts to output the data, which is a Gallery using fields from Advanced Custom Fields.
Here's my function so far:
function mbgc_gallery_shortcode( $atts ) {
// $post_id = $atts['id'];
extract( shortcode_atts(
array(
'id' => '',
), $atts )
);
$html_out = '123';
// $post = get_post( $id );
// if ( $post ) :
if( have_rows('mbgc_gallery') ):
$html_out .= '<div class="mbgc-gallery owl-carousel owl-theme">';
while( have_rows('mbgc_gallery') ): the_row();
// vars
$image = get_sub_field('mbgc_image');
$caption = get_sub_field('mbgc_caption');
$title = get_sub_field('mbgc_title');
$sub_title = get_sub_field('mbgc_sub_title');
if ( $image ) :
$html_out .= '<div class="mbgc-gallery-item">';
if ( $caption ) :
$html_out .= '<div class="mbgc-slide-caption">';
$html_out .= '<h4>' . $caption . '</h4>';
$html_out .= '<div class="mbgc-slide-titles">';
$html_out .= '<h6>' . $title . '</h6>';
$html_out .= '<h6>' . $sub_title . '</h6>';
$html_out .= '</div>';
$html_out .= '</div>';
endif;
$html_out .= '<div class="mbgc-slide">';
$html_out .= '<img src="' . $image['url'] . '" alt="' . $image['alt'] . '" />';
$html_out .= '</div>';
$html_out .= '</div>';
endif;
endwhile;
$html_out .= '</div>';
endif;
// endif;
return $html_out;
}
add_shortcode('mbgc_gallery', 'mbgc_gallery_shortcode');
I'm hoping the shortcode can look like [mbgc_gallery id="401"], as an example. The main thing is I am not sure how to exactly write it in the function to pull the ID.

You need to pass the ID from the shortcode attributes to the ACF have_rows() function so that the correct data is retrieved.
<?php
function mbgc_gallery_shortcode( $atts ) {
$attributes = shortcode_atts(
array(
'id' => null
), $atts );
// $attributes['id'] is now the passed-in ID
$html_out = '';
if( have_rows('mbgc_gallery', $attributes['id']) ):
$html_out .= '<div class="mbgc-gallery owl-carousel owl-theme">';
while( have_rows('mbgc_gallery', $attributes['id']) ): the_row();
// vars
$image = get_sub_field('mbgc_image');
$caption = get_sub_field('mbgc_caption');
$title = get_sub_field('mbgc_title');
$sub_title = get_sub_field('mbgc_sub_title');
if ( $image ) :
$html_out .= '<div class="mbgc-gallery-item">';
if ( $caption ) :
$html_out .= '<div class="mbgc-slide-caption">';
$html_out .= '<h4>' . $caption . '</h4>';
$html_out .= '<div class="mbgc-slide-titles">';
$html_out .= '<h6>' . $title . '</h6>';
$html_out .= '<h6>' . $sub_title . '</h6>';
$html_out .= '</div>';
$html_out .= '</div>';
endif;
$html_out .= '<div class="mbgc-slide">';
$html_out .= '<img src="' . $image['url'] . '" alt="' . $image['alt'] . '" />';
$html_out .= '</div>';
$html_out .= '</div>';
endif;
endwhile;
$html_out .= '</div>';
endif;
return $html_out;
}
add_shortcode('mbgc_gallery', 'mbgc_gallery_shortcode');
Use the shortcode like this: [mbgc_gallery id="123"].
Personally I don't like using extract() - this turns an array into individual variables, named according to the array element key, and can make debugging difficult. Instead, just access your id like this: $attributes['id'] as shown above.
Good luck!

Related

Wordpress display custom taxonomy image on single post - php

I´m trying to display a custom taxonomy image in the frontend on a single post.
Following situation:
Created a CPT for "Weine"
Added a taxonomy "winzer"
Added the following code to my functions.php to display the "winemaker" taxonomy with its description in the single post using a shortcode:
function wpb_catlist_desc() {
$string = '<div>';
$catlist = get_terms( 'winzer' );
if ( ! empty( $catlist ) ) {
foreach ( $catlist as $key => $item ) {
$string .= '<div>'. $item->name . '<br />';
$string .= '<em>'. $item->description . '</em></div>';
}
}
$string .= '</div>';
return $string;
}
add_shortcode('wpb_categories', 'wpb_catlist_desc');
Added an Image fieled to the "winzer" taxonomy using ACF. --> Here´s where I´m stuck now.
I need to add another line to the php snippet to also display the image using the shortcode.
Any hints how to get this done? :)
Cheers!!!!
function wpb_catlist_desc() {
$string = '<div>';
$catlist = get_terms( 'winzer' );
if ( ! empty( $catlist ) ) {
foreach ( $catlist as $key => $item ) {
$image = get_field('Your_image_field_ID');
if(!empty($image)) {
$imgurl = $image['url'];
}
$string .= '<div>';
$string .= '<img src="' . $imgurl . '" alt="' . $item->name . '"/><br />';
$string .= $item->name . '<br />';
$string .= '<em>'. $item->description . '</em></div>';
}
}
$string .= '</div>';
return $string;
}
add_shortcode('wpb_categories', 'wpb_catlist_desc');
Here's how I got it solved:
function wpb_catlist_desc() {
global $post;
$string = '<div>';
$catlist = wp_get_post_terms($post->ID, 'winzer');
if ( ! empty( $catlist ) ) {
foreach ($catlist as $item ) {
$image = get_field('winzer_bild', 'winzer_'.$item->term_id);
if(!empty($image)) {
$imgurl = $image['url'];
}
$string .= '<div>';
$string .= '<img class="winzer-bild-klein" src="' . $imgurl . '" alt="' . $item->name . '"style="width:100%;"/>';
$string .= '<h3 class="winzer-name-n">'. $item->name . '</h3>';
$string .= '<p>'. $item->description . '</p></div>';
}
}
$string .= '</div>';
return $string;
}
add_shortcode('wpb_categories', 'wpb_catlist_desc');

How do I call post objects (products) custom fields using shortcodes on posts

I'm trying to show 'featured products' on blog posts. These featured products are to be selected with custom fields post objects on the back end for each post.
I have written up what I think the PHP should be - where am I going wrong? When I try to use the shortcode no code appears (but the shortcode text doesn't show so it's definitely added). Thanks :)
<?php
add_shortcode('featuredproducts' , 'printfeaturedprod');
function printfeaturedprod(){
$html = '';
$instruments = get_field('featuredprod');
if( $instruments ):
$html .= '<div class="featuredproducts">';
$html .= '<h2 style="font-size:18px; font-family:poppins;">Featured in this video</h2>';
foreach( $instruments as $instruments ):
$permalink = get_permalink( $instruments->ID );
$title = get_the_title( $instruments->ID );
$product = wc_get_product( $instruments->ID );
$price = $product->get_price();
$featured_img_url = get_the_post_thumbnail_url($instruments->ID, 'full');
$html .= '<div class="featuredproduct">';
$html .= '<img class="featuredproductimg" src="' . $featured_img_url . '">';
$html .= '<div class="proddetails">';
$html .= '<a class="producttitle" href="' . $permalink . '"><?php echo esc_html( $title ); ?></a>';
$html .= '<br><span class="productprice">£' . $price . '</span>';
$html .= '</div>';
$html .= '</div>';
endforeach;
$html .= '</div>';
endif;
}
You have built your HTML in the $html variable but then you don’t do anything with it. The shortcode doesn’t automatically know that you want to display the $html variable so you need to return ( or echo) it at the end before the function finishes:
add_shortcode('featuredproducts' , 'printfeaturedprod');
function printfeaturedprod(){
$html = '';
/* your code here... */
return $html;
}
Reference: See the add_shortcode WP documentation

Pulling featured image as a background on Wordpress

I'm trying to figure out how to pull the featured post image as a background (on Wordpress) but cannot get it to work.
See below the code I'm using. $thumbimg should be pulling the featured image but obviously i am doing something wrong there.
$lessons = get_posts( $args );
if( count( $lessons ) > 0 ) {
$html .= '<section class="module-lessons">';
$html .= '<header><h3>' . __( 'Lessons', 'sensei_modules' ) . '</h3></header>';
$thumbimg = wp_get_attachment_image_src( get_post_thumbnail_id($lesson->ID), array( 200,200 ), false, '' );
$html .= '<ul>';
foreach( $lessons as $lesson ) {
$html .= '<li class="lesson-items" style="background: url(<?php echo $thumbimg[0]; ?>)>';
$html .= '' . get_the_title( intval( $lesson->ID ) ) . '';
$html .= '</li>';
// Build array of displayed lesson for exclusion later
$displayed_lessons[] = $lesson->ID;
}
$html .= '</ul>';
$html .= '</section>';
}
I cannot also seem to get the style="background.." to read the php as I would like to.
It will not work because you are getting the ID wrong. The code for the thumbnail should be something like:
wp_get_attachment_image_src( get_post_thumbnail_id($post_ID), 'large' ) ;
you are doing it right except for the fact that you are calling the $lesson->ID on an object $lesson that doesn't exist outside of the loop after it :)
Editing your code:
$lessons = get_posts( $args );
if( count( $lessons ) > 0 ) {
$html .= '<section class="module-lessons">';
$html .= '<header><h3>' . __( 'Lessons', 'sensei_modules' ) . '</h3></header>';
$html .= '<ul>';
foreach( $lessons as $lesson ) {
// This should be inside the loop
$thumbimg = wp_get_attachment_image_src( get_post_thumbnail_id($lesson->ID), array( 200,200 ), false, '' );
$html .= '<li class="lesson-items" style="background-image: url("'. $thumbimg[0] . '")>';
$html .= '' . get_the_title( intval( $lesson->ID ) ) . '';
$html .= '</li>';
// Build array of displayed lesson for exclusion later
$displayed_lessons[] = $lesson->ID;
}
$html .= '</ul>';
$html .= '</section>';
}
As for the background in CSS, use background-image: url ()

WP Query pagination on shortcode

I am creating a shortcode to display the most recent posts in the homepage, however I cannot get the pagination working.
When you click on 'older posts' the page refreshes but the same 2 original posts are displayed.
if ( ! function_exists('vpsa_posts_shortcode') ) {
function vpsa_posts_shortcode( $atts ){
$atts = shortcode_atts( array(
'per_page' => 2,
'order' => 'DESC',
'orderby' => 'date'
), $atts );
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post',
'posts_per_page' => $atts["per_page"],
'order' => $atts["order"],
'orderby' => $atts["orderby"],
'paged' => $paged
);
$query = new WP_Query($args);
if($query->have_posts()) : $output;
while ($query->have_posts()) : $query->the_post();
$output .= '<article id="post-' . get_the_ID() . '" class="' . implode(' ', get_post_class()) . '">';
$output .= '<h4 class="post-title"><span>' . the_title('','',false) . '</span></h4>';
$output .= '<div class="row">';
$output .= '<div class="col-md-3">';
$output .= '<a href="' . get_permalink() . '" title="' . the_title('','',false) . '">';
if ( has_post_thumbnail() ) {
$output .= get_the_post_thumbnail( get_the_id(), 'featured', array('class' => 'img-responsive aligncenter'));
} else {
$output .= '<img class="img-responsive aligncenter" src="' . get_template_directory_uri() . '/images/not-available.png" alt="Not Available" height="150" width="200" />';
}
$output .= '</a>';
$output .= '</div>';
$output .= '<div class="col-md-9">';
$output .= get_the_excerpt();
$output .= '<span class="post-permalink">Read More</span>';
$output .= '</div>';
$output .= '</div>';
$output .= '<div class="post-info">';
$output .= '<ul>';
$output .= '<li>Posted: ' . get_the_time("F j, Y") . '</li>';
$output .= '<li>By: ' . get_the_author() . '</li>';
$output .= '<li>Categories: ' . get_the_category_list(", ") . '</li>';
$output .= '</ul>';
$output .= '</div>';
$output .= '</article>';
endwhile;
$output .= '<div class="post-nav">';
$output .= '<div class="prev-page">' . get_previous_posts_link( "« Newer Entries" ) . '</div>';
$output .= '<div class="next-page">' . get_next_posts_link( "Older Entries »", 3 ) . '</div>';
$output .= '</div>';
else:
$output .= '<p>Sorry, there are no posts to display</p>';
endif;
wp_reset_postdata();
return $output;
}
}
add_shortcode('vpsa_posts', 'vpsa_posts_shortcode');
You need to call paginate function.Try following code:
if ( ! function_exists('vpsa_posts_shortcode') ) {
function vpsa_posts_shortcode( $atts ){
$atts = shortcode_atts( array(
'per_page' => 2,
'order' => 'DESC',
'orderby' => 'date'
), $atts );
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post',
'posts_per_page' => $atts["per_page"],
'order' => $atts["order"],
'orderby' => $atts["orderby"],
'paged' => $paged
);
$query = new WP_Query($args);
if($query->have_posts()) : $output;
while ($query->have_posts()) : $query->the_post();
$output .= '<article id="post-' . get_the_ID() . '" class="' . implode(' ', get_post_class()) . '">';
$output .= '<h4 class="post-title"><span>' . the_title('','',false) . '</span></h4>';
$output .= '<div class="row">';
$output .= '<div class="col-md-3">';
$output .= '<a href="' . get_permalink() . '" title="' . the_title('','',false) . '">';
if ( has_post_thumbnail() ) {
$output .= get_the_post_thumbnail( get_the_id(), 'featured', array('class' => 'img-responsive aligncenter'));
} else {
$output .= '<img class="img-responsive aligncenter" src="' . get_template_directory_uri() . '/images/not-available.png" alt="Not Available" height="150" width="200" />';
}
$output .= '</a>';
$output .= '</div>';
$output .= '<div class="col-md-9">';
$output .= get_the_excerpt();
$output .= '<span class="post-permalink">Read More</span>';
$output .= '</div>';
$output .= '</div>';
$output .= '<div class="post-info">';
$output .= '<ul>';
$output .= '<li>Posted: ' . get_the_time("F j, Y") . '</li>';
$output .= '<li>By: ' . get_the_author() . '</li>';
$output .= '<li>Categories: ' . get_the_category_list(", ") . '</li>';
$output .= '</ul>';
$output .= '</div>';
$output .= '</article>';
endwhile;global $wp_query;
$args_pagi = array(
'base' => add_query_arg( 'paged', '%#%' ),
'total' => $query->max_num_pages,
'current' => $paged
);
$output .= '<div class="post-nav">';
$output .= paginate_links( $args_pagi);
// $output .= '<div class="next-page">' . get_next_posts_link( "Older Entries »", 3 ) . '</div>';
$output .= '</div>';
else:
$output .= '<p>Sorry, there are no posts to display</p>';
endif;
wp_reset_postdata();
return $output;
}
}
add_shortcode('vpsa_posts', 'vpsa_posts_shortcode');
WP_Query with pagination inside a shortcode
Here I will show you how to create a [shortcode] containing a custom new WP_Query with pagination links.
To create a [shortcode] with a new WP_Query post loop with pagination links built in to turn any is_singular() page or single post into a custom archive based on the WP_Query arguments you set. Lets call it [wp_query_pagination_inside_shortcode], so we add with the following add_shortcode() in functions.php.
Or in my case I create separate /functions/ folder for files to stay organized with the appropriates names and have a require_once include file structure.
root/functions.php ->
require_once 'functions/shortcode-wp-query-pagination-inside-shortcode.php';
root/functions/shortcode-wp-query-pagination-inside-shortcode.php->
add_shortcode('wp_query_pagination_inside_shortcode', 'my_shortcode_function_tag');
if (!function_exists('my_shortcode_function_tag')) {
function my_shortcode_function_tag($atts)
{
ob_start(); // Turn output buffering on, helps with complicated template and theme structures
// Note: https://developer.wordpress.org/reference/functions/get_query_var/#used-by
// Custom query_vars translates to Getting an "archive" on any current page that contains a query with corresponding pagination number in the url
// example.com/page-shortcodes-on/page/2/ ...etc see below how to manipulate this
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$atts = shortcode_atts(
array(
'post_type' => 'post',
// Set attributes here you want in your shortcode
// like [shortcode post_types="post"]
),
$atts
);
// set up the default args you wont change and the ones you will by accessing the value of $atts passed into the shortcode function from your WYSIWYG content editor
$args = array(
'posts_per_page' => 3,
'paged' => $paged, // Important to receive page data
'post_type' => $atts['post_type'], // This is how you get the values of your shortcode attributes passed in
'orderby' => 'date',
'order' => 'DESC',
);
$the_query = new WP_Query($args);
// Da loop
// match your themes loop structure this below is just boiler plate stuff ignore or use your choice its not important how you create the post loop, just do it
if ($the_query->have_posts()) {
while ($the_query->have_posts()) {
$the_query->the_post();
get_template_part('template-parts/loop');
} //end while
} // endif
$big = 999999999; // need an unlikely integer for how many pages are possible
// I've tested example.com/page-shortcodes-on/page/999999999999999999/ and the custom query_var still works
echo paginate_links(
array(
'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))), // referrence the url
'format' => '?paged=%#%', // used for replacing the page number
'current' => max(1, get_query_var('paged')), // grabs the page data
'total' => $the_query->max_num_pages //$the_query is your custom query
)
);
return ob_get_clean(); // Silently discard the buffer contents
wp_reset_query(); // Lets go back to the main_query() after returning our buffered content
}
}
In a WYSIWYG Content editor in pages or posts content editor
[wp_query_pagination_inside_shortcode post_type="posts"]
URL structure for this query_var 'paged'
example.com/page-shortcode-is-on/page/2/
You will need to stylize the pagination links a bit to be acceptable but this should give you a highly useful tool to build custom WP_Query loops with multiple different post_types from anywhere in your site through your WYSIWYG editor. Add more attributes to really make this thing valuable.
// Ignore below, these are just possible search queries for this issue
WP_Query pagination inside a shortcode / add_shortcode with pagination / shortcode with custom attributes / Paginated custom post type wp_query shortcode / custom post type wp_query archive posts per page / page / pagination wont work

PHP - adding function to string

I'm relatively new to PHP and don't even really know how to ask the question for which i need help with, so please excuse my lack of technical knowledge - or referring to terms correctly for that matter.
I cannot figure out a way to add the "if(function_exists("the_ratings"))" code below to a string as in the PHP i have below. I know that the way it is below is not correct, but i've placed it there to show how and where i need it to display - help is greatly appreciated.
function latestreleases() {
$args = array( 'posts_per_page' => 30, 'cat' => '-1, -2' );
$last_5_posts_query = new WP_Query( $args );
while($last_5_posts_query->have_posts()) :
$last_5_posts_query->the_post();
$link = get_permalink();
$title = get_the_title();
$description = excerpt(16);
$details = 'Watch ';
$readmore = 'Read more...';
$content .= '<div class="all-latest-movies">';
$content .= '<h3>'.$title.'</h3>';
$content .= '<div class="thumbnail"><a href=" '.$link. ' ">'
. get_the_post_thumbnail( null, "home-movie-thumbnail")
. '</a></div>';
$content .= '<div class="description">' .$description. ' <a href= '.$link.' >' .$readmore. '</div>';
$content .= '<div class="view-listing"><a href= '.$link.' target="_blank" >' .$details. $title. '</a></div>';
$content .= '<div class="ratings">' if(function_exists("the_ratings")) { the_ratings(); } '</div>';
$content .= '</div><!-- .fetured-movies -->';
endwhile;
return $content;
}
add_shortcode('LatestReleases', 'latestreleases' );
Use a ternary operator:
$content .= '<div class="ratings">'. ( function_exists("the_ratings") ? the_ratings() : '' ) .'</div>';
If you want to do it inline you can use the ternary operator
$content .= '<div class="ratings">'.(function_exists("the_ratings")?the_ratings():'').'</div>';
If you want to use the if syntax
$content .= '<div class="ratings">';
if(function_exists("the_ratings")){
$content.=the_ratings();
}
$content.='</div>';

Categories