I’m using bellow function for related post shortcode and I have a question about it. It’s supposed to display posts with related tag (I don't why it shows just random posts) but I want to use something like [rps tag=google] and the function just return a post has a tag as “google”, I mean nothing related to the current post tags. How can I do that?
This is the code:
add_shortcode('rps', 'fphp_get_related_posts');
function fphp_get_related_posts() {
$reset_post = $post;
global $post;
$post_tags = wp_get_post_tags($post->ID);
if ($post_tags) {
$post_tag_ids = array();
foreach($post_tags as $post_tag) $post_tag_ids[] = $post_tag->term_id;
$args=array(
'tag__in' => $post_tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => 1,
'orderby' => 'rand',
);
$related_query = new wp_query( $args );
if (intval($related_query->post_count) === 0) return '';
$html = '<div class="rps"><ul><h3>Also read:</h3>';
$related_query->the_post();
$html .= '<li style="width:250px">';
$html .= '<div class="relatedthumb"><a rel="external" href="'. get_the_permalink(). '">';
$html .= get_the_title() . '</a>';
$html .= '</div></li>';
}
$post = $reset_post;
wp_reset_query();
$html .= '</ul></div>';
return $html;
}
If you want to show given tag post, then no need to use wp_get_post_tags(), because its return multi tags. try this code,
function fphp_get_related_posts( $atts ) {
$atts = shortcode_atts( [
'tag' => '',
], $atts );
$args = [ 'posts_per_page' => 1, 'tag' => $atts['tag'], 'orderby' => 'rand' ];
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
ob_start(); ?>
<!-- your html here -->
<?php endwhile; endif; wp_reset_postdata();
return ob_get_clean();
}
add_shortcode( 'rps','fphp_get_related_posts' );
Related
I tried to query products by WP_query and it was all fine. But when i tried query it with category argument nothing happenned. When i trying add new shortcode with category args it doesn't work too. I can't see where the problem is. I don't think that swiper.js could make a error. When i enter empty 'category_name' it shows all products. Others argument work as they should
function test_short($attr) {
$content = '';
$content .= "<script src='https://unpkg.com/swiper/swiper-bundle.min.js'></script>";
$sharg = shortcode_atts( array(
'cat' => '',
), $attr );
$args = array(
'post_type' => 'product',
'category_name' => 'gry',
'suppress_filters' => true
);
$wc_query = new WP_Query($args);
$content .= '<div class="swiper slidee">
<div class="swiper-wrapper">';
if($wc_query->have_posts()) {
while($wc_query->have_posts()) {
$content .= '<div class="swiper-slide">';
$wc_query->the_post();
$id = get_the_ID();
$url = wp_get_attachment_image_src(get_post_thumbnail_id($id), 'full')[0];
$content .= '<img class="product_img" src="'.$url.'">';
$title = get_the_title();
$content .= "<div class='title'>".$title."</div>";
$product = wc_get_product( $id );
$content .= number_format(($product->get_price()),2)." zł";
$content .= '
<div class="koszyk_ikona"></div><div class="koszyk_tekst">Dodaj do koszyka</div>
';
$content .= '</div>';
}
}
$content .= '
</div>
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div';
$content .= "<script>";
$content .= file_get_contents(get_site_url().'/javascript.js');
$content .= "</script>";
$content .= '<script type="text/javascript"> var swiper = new Swiper(".slidee", {
slidesPerView: 3.5,
spaceBetween: 30,
autoplay: {
delay: 3000,
},
speed: 1700,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev"
}
});
</script>';
wp_reset_query();
return $content;
}
add_shortcode("test_short","test_short");
EDIT!!!!
I discovered that no of my products have category when i check them by get_the_category(). How is possible when i added them to category and at products admin panel they all have some of category
$category = array('Clothing', 'Bed');
$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'name',
'terms' => $category
)
)
);
$loop = new WP_Query($args);
if ($loop->have_posts()):
while ($loop->have_posts()) : $loop->the_post();
global $product;
echo '<pre>';
print_r($product->get_name());
echo '</pre>';
endwhile;
endif;
I'm new to creating wordpress shortcodes and have one just about working the way I want. Missing something specific. Currently I am able to put the following on any page - [children] and it pulls a query of all posts from the custom post type "children" I would like to add the option to add the category id within the shortcode - something like [children category="8"] Here is the code I have so far:
add_shortcode( 'children', 'display_custom_post_type' );
function display_custom_post_type(){
$args = array(
'post_type' => 'children',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
$string .= '<div id="childWrapper"><div id="childImage">' . get_the_post_thumbnail() . '</div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
}
}
wp_reset_postdata();
return $string;
}
Secondary - is it possible for it to show posts in multiple categories, but only where the posts are in each of the categories. For example showing a list of children, who fall under a category for critical care and surgery needed.
Any help would be greatly appreciated.
You should refer Shortcode function from WordPress Codex. Assuming your taxonomy name is category, I made some changes in your current code it should work as per your requirements.
/**
* [children category="5,7,8"]
*/
add_shortcode( 'children' , 'display_custom_post_type' );
function display_custom_post_type($atts) {
$atts = shortcode_atts( array(
'category' => ''
), $atts );
//If category is multiple: 8,9,3
$categories = explode(',' , $atts['category']);
$args = array(
'post_type' => 'children',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page'=> -1,
'tax_query' => array( array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $categories
) )
);
$string = '';
$query = new WP_Query( $args );
if( ! $query->have_posts() ) {
return false;
}
while( $query->have_posts() ){
$query->the_post();
$string .= '<div id="childWrapper"><div id="childImage">' . get_the_post_thumbnail() . '</div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
}
wp_reset_postdata();
return $string;
}
I've been searching this forum for help for 2 days now but I can't find a solution for what I'm trying to achieve.
I have a custom post type called "product" and inside each post in that post type there are two custom fields called produktnamn(a textfield with product name) and produktbild(a product image). that's it.
Now I need a shortcode to display a particular post in that post type by entering it's slug (which is the same as it's name).
like this:
[product name="myproduct"]
That will render the name and product image inside some HTML tags.
Please help!
My code so far:
//Product image
function cpt_content_func($atts){
extract( shortcode_atts(['name' => null], $atts ) );
$args = [
'name' => $slug,
'post_type' => 'product',
'numberposts' => 1
];
$posts = get_posts( $args );
$post = $post[0];
$title = $post->title;
$id = $post->ID;
get_post_meta('produktbild', $id);
$content = $post[0]->post_title;
return '<h3>'.$content.'</h3>';
}
add_shortcode('product','cpt_content_func');
Solved it. Here's the code!
function display_custom_post_type( $atts ){
// Handle the attributes
$atts = shortcode_atts(
array(
'cat' => ' '
),
$atts, 'products_by_cat' );
// Set default values for the post
$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
'post_status' => 'publish',
'category' => $atts['cat']
);
// Get posts
$posts_array = get_posts( $args );
// Check if posts exist
if( !empty($posts_array) ){
$string = '<div class="row">';
foreach( $posts_array as $post ){
$string .= '<div class="col-sm-3 text-center">';
$string .= '<div class="product-container">';
$string .= '<a href="' . get_field( "order_link", $post->ID ) . '">';
$string .= '<img class="product-img" src="' . get_field( "produktbild", $post->ID ) . '">';
$string .= '</a>';
$string .= '</div>';
$string .= '<p class="product-btn">' . get_field( "produktnamn", $post->ID ) . '</p>';
$string .= '</div>';
}
$string .= '</div>';
} else {
// Didn't find any posts.
}
// Return HTML
return $string;
I agree with James--I'd just use woocommerce.
But you first step has to be learning how to build a shortcode: http://code.tutsplus.com/tutorials/wordpress-shortcodes-the-right-way--wp-17165
Once you've attempted creating your own shortcodes, if things still aren't working, that's the time to ask for help.
Hi my code is below for adding shortcode in posts. when i am adding shortcode two times it shows me heading two times that i added in code "Recent Posts" is there is way to show this heading only top means one time?
/*shortcode start*/
add_shortcode( 'recent-posts', 'PL_recent_posts' );
function PL_recent_posts( $atts ) {
extract( shortcode_atts( array(
'numbers' => '5',
'order' => 'ASC',
), $atts ) );
$rposts = new WP_Query( array( 'posts_per_page' => $numbers, 'orderby' => 'date' , 'colorss' => $color ) );
if ( $rposts->have_posts() ) {
$html = '<h3>Recent Posts</h3><ul class="recent-posts">';
while( $rposts->have_posts() ) {
$rposts->the_post();
$html .= sprintf(
'<li>%s</li>',
get_permalink($rposts->post->ID),
get_the_title(),
get_the_title()
);
}
$html .= '</ul>';
}
wp_reset_query();
return $html;
}
Define a global variable to detect whether title is already added.
function PL_recent_posts( $atts ) {
global $title_added;
...
if ( $rposts->have_posts() ) {
if ( $title_added ) {
$html = '<ul class="recent-posts">';
} else {
$html = '<h3>Recent Posts</h3><ul class="recent-posts">';
$title_added = true;
}
Hope that helps..!
I have spent hours on this - hoping someone who knows a bit of PHP can solve it painlessly.
I have a Wordpress query loop which needs to be concatenated together. It kind of works, but I have requested 6 posts, and all 6 are the same!
Here's the code snippet which returns the duplicate posts:
////* New tab *//////
$args = array( 'numberposts' => 6, 'orderby' => 'post_date' );
$postslist = get_posts( $args );
$content .= '<div class="tab" id="new"><ul>';
foreach ($postslist as $post) : setup_postdata($post);
$content .= '<li><a href="' . get_permalink() . '"</a>' . get_the_title() . '</a></li>';
endforeach;
$content .= '</ul></div>';
return $content; // prints all the contents stringed together
This code produces this list:
Any help appreciated...at all! Thanks.
It looks like your code example is taken from inside a function.
a) Please try this:
// ... cut ...
global $post;
$args = array( 'posts_per_page' => 6, 'orderby' => 'post_date' );
$postslist = get_posts( $args );
$content .= '<div class="tab" id="new"><ul>';
foreach ( $postslist as $post ) : setup_postdata( $post );
$content .= sprintf( '<li>%s</li>',
get_permalink(),
get_the_title() );
endforeach;
$content .= '</ul></div>';
wp_reset_postdata();
return $content; // prints all the contents stringed together
where I added the global $post declaration so setup_postdata( $post ) can modify the global $post object.
b) Or try this:
// ... cut ...
$args = array( 'posts_per_page' => 6, 'orderby' => 'post_date' );
$postslist = get_posts( $args );
$content .= '<div class="tab" id="new"><ul>';
foreach ( $postslist as $post ) :
$content .= sprintf( '<li>%s</li>',
get_permalink( $post->ID ),
get_the_title( $post->ID ) );
endforeach;
$content .= '</ul></div>';
return $content; // prints all the contents stringed together
where I used the post id as an input argument for get_permalink() and get_the_title().
c) You can also use the raw post title: $post->post_title or if you want to take it through the the_title filter with:
echo apply_filters( 'the_title', $post->post_title );
So to wrap it up:
Notice that get_the_title() is based on get_post(), and if you don't use an input argument, then it will try to use the global $post object:
if ( empty( $post ) && isset( $GLOBALS['post'] ) )
$post = $GLOBALS['post'];
Therefore you always get the same global post object title (usually from the main query) if you don't modify the global object within the secondary loop.
Hope this helps.