shortcode from Custom post in wordpress - wordpress

I want to show my custom post using shortcode
my custom post code is below-
/Custom Post/
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'service_items',
array(
'labels' => array(
'name' => __( 'Service Items' ),
'singular_name' => __( 'Service Items' ),
'add_new' => __( 'Add New' ),
'add_new_item' => __( 'Add New Service Items' ),
'edit_item' => __( 'Edit Service Items' ),
'new_item' => __( 'New Service Items' ),
'view_item' => __( 'View Service Items' ),
'not_found' => __( 'Sorry, we couldn\'t find the Service Items you are looking for.' )
),
'public' => true,
'publicly_queryable' => true,
'exclude_from_search' => true,
'menu_position' => 14,
'has_archive' => false,
'hierarchical' => false,
'capability_type' => 'page',
'rewrite' => array( 'slug' => 'custompost_id' ),
'supports' => array( 'title', 'editor', 'custom-fields','thumbnail' )
)
);
}
And Shortcode code is below -
function service_item_shortcode() {
$args = array(
'post_type' => 'service_items',
'order' => 'DESC',
'posts_per_page'=> -1
);
$service_items = new WP_Query( $args );
if( $service_items->have_posts() ):
while ( $service_items->have_posts() ) : $service_items->the_post();
$service_output = '<div class="span3 serv">';
$service_output .='<div class="serv-img">' ;
$service_output .=get_the_post_thumbnail( $service_items->post->ID, service-image) ;
$service_output .='</div>';
$service_output .= '<h3>' . get_the_title() . '</h3> ';
$service_output .= '<p>' . get_the_content() . '</p> ';
$service_output .= '</div>';
endwhile;
endif;
return $service_output;
}
add_shortcode( 'service_item', 'service_item_shortcode' );
I want to show on my post 4 custom post items per page.
But when I put [service-item] shortcode output only show 1 post.
I need 4 post per page. Please help.

You should write the output from all posts in a variable, instead of resetting the variable on each iteration. To do this, define an empty variable before the loop, and simply add to it all of the output of each post. Here is the changed code that should work for you (untested):
function service_item_shortcode() {
$service_output = '';
$paged = !empty($_GET['service_item_page']) ? absint($_GET['service_item_page']) : 1;
if (!$paged) {
$paged = 1;
}
$args = array(
'post_type' => 'service_items',
'order' => 'DESC',
'posts_per_page'=> 4,
'paged' => $paged
);
$service_items = new WP_Query( $args );
if( $service_items->have_posts() ):
while ( $service_items->have_posts() ) : $service_items->the_post();
$service_output .= '<div class="span3 serv">';
$service_output .= '<div class="serv-img">' ;
$service_output .= get_the_post_thumbnail( get_the_ID(), 'service-image');
$service_output .= '</div>';
$service_output .= '<h3>' . get_the_title() . '</h3> ';
$service_output .= '<p>' . get_the_content() . '</p> ';
$service_output .= '</div>';
endwhile;
endif;
if ($service_items->max_num_pages > 1) {
$service_output .= '<div class="pagination">';
for($i = 1; $i <= $service_items->max_num_pages; $i++) {
$service_output .= '' . $i . ' ';
}
$service_output .= '</div>';
}
wp_reset_postdata();
return $service_output;
}
add_shortcode( 'service_item', 'service_item_shortcode' );

Related

How To Filter and Display ONLY Simple WooCommerce Products using Shortcode

I have a functional shortcode that outputs all products. Problem is, I need this to only "find" simple products.
add_shortcode('product_list', 'simple_product_list');
function simple_list_shortcode() {
$query = new WP_Query( array(
'posts_per_page' => -1,
'post_type' => 'product',
'post_status' => 'publish',
'hide_empty' => 0,
'orderby' => 'title',
'post_id' => 'id'));
$output = '<ul style="list-style-type:none">';
while ( $query->have_posts() ) : $query->the_post();
$product = wc_get_product($query->post->ID);
$price = $product->get_regular_price();
$output .= '<li>' . $query->post->post_title . ' costs '.wc_price($price) . ', <a class="atc" href="'. $product->add_to_cart_url() .'">order now</a>.</li>';
endwhile;
wp_reset_postdata();
return $output.'</ul>';
}
Since it is already using 'post_type' => 'product', I cannot add another with simple.
I tried using a if statement for ->is_type('simple'), but doing so turned the page white and nothing is displayed.
Your shortcode callback function and your actual function name is different.
You can get product type using $product->get_type() function.
UPDATE 1: Using WP_Query().
add_shortcode('product_list', 'simple_list_shortcode');
function simple_list_shortcode()
{
ob_start();
$query = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'product',
'post_status' => 'publish',
'hide_empty' => 0,
'orderby' => 'title',
'post_id' => 'id'
));
$output = '<ul style="list-style-type:none">';
while ($query->have_posts()) : $query->the_post();
$product = wc_get_product($query->post->ID);
if($product->get_type() == 'simple'){
$price = $product->get_regular_price();
$output .= '<li>' . $query->post->post_title . ' costs ' . wc_price($price) . ', <a class="atc" href="' . $product->add_to_cart_url() . '">order now</a>.</li>';
}
endwhile;
wp_reset_postdata();
echo $output . '</ul>';
$contents = ob_get_clean();
return $contents;
}
UPDATE 2: you can also use wc_get_products() function to get products with arguments.
add_shortcode('product_list', 'simple_product_list');
function simple_product_list()
{
$arg = array(
'type' => 'simple',
'orderby' => 'date',
'order' => 'DESC',
) ;
$products = wc_get_products($arg);
ob_start();
$output = '<ul style="list-style-type:none">';
foreach( $products as $product){
$price = $product->get_regular_price();
$output .= '<li>' . $product->get_name() . ' costs ' . wc_price($price) . ', <a class="atc" href="' . $product->add_to_cart_url() . '">order now</a>.</li>';
}
echo $output . '</ul>';
$contents = ob_get_clean();
return $contents;
}

How to use the visual composer attach_images as in a shortcode

I am trying to create a custom image slider using visual composers attach_images but cant quite work out how to get the URLs from the array of image IDs.
Any help would be appreciated.
var_dump($bg_images) returns
string(9) "19,6,1692"
vc_map( array(
"name" => __( "Fading Background Block", "farrat_vc" ),
"base" => "block_background",
"class" => "",
"category" => __( "Farrat Shortcodes", "farrat_vc"),
"as_parent" => array('except' => 'farrat_panel'), // Use only|except attributes to limit child shortcodes (separate multiple values with comma)
"content_element" => true,
"show_settings_on_create" => true,
"is_container" => true,
'admin_enqueue_css' => array(get_template_directory_uri().'/wp-content/themes/unite/inc/css/gallery.css'),
"params" => array(
array(
"type" => "attach_images",
"heading" => __( "Backgroud Images", "farrat_vc" ),
"param_name" => "bg_images",
),
),
"js_view" => 'VcColumnView'
) );
// Hi try this one this is perfectly working
//Param Registration
function designas_partners() {
// Title
vc_map(
array(
'name' => __( 'Clients' ),
'base' => 'designas_partners_content',
'category' => __( 'Easy Component' ),
'params' => array(
array(
"type" => "attach_images",
"heading" => esc_html__( "Add Clients Images", "appcastle-core" ),
"description" => esc_html__( "Add Clients Images", "appcastle-core" ),
"param_name" => "screenshots",
"value" => "",
),
)
)
);
}
add_action( 'vc_before_init', 'designas_partners' );
// Short code
function designas_partners_content_function( $atts, $content ) {
$gallery = shortcode_atts(
array(
'screenshots' => 'screenshots',
), $atts );
$image_ids = explode(',',$gallery['screenshots']);
$return = '
<div class="clients">';
foreach( $image_ids as $image_id ){
$images = wp_get_attachment_image_src( $image_id, 'company_logo' );
$return .='<div class="images"><img src="'.$images[0].'" alt="'.$atts['title'].'"></div>';
$images++;
}
$return .='</div>';
return $return;
}
add_shortcode( 'designas_partners_content', 'designas_partners_content_function' )
I got a neet workaround for this one on the loop, theres no need for the counter, loop over wp_get_attachment_image( $image_id, 'full' ); will get you every information u use on the wordpress panel.
I'll thank to #sushovan bhowmik was looking for this, I think this will help to avoid lots of variables calling the images :)
<?php
function vc_gallery_carrousel($atts, $content) {
// Attributes
$gallery = shortcode_atts(
array(
'carrousel_images' => 'carrousel_images',
),
$atts );
// Attributes in var
$image_ids=explode(',',$gallery['carrousel_images']);
// Output Code
$output .= '<section class="loopclientsimg">';
$output .= '<article>';
$output .= '<div>';
$output .= '<ul>';
foreach( $image_ids as $image_id ){
$output .='<li>';
$output .= wp_get_attachment_image( $image_id, 'full' );
$output .='</li>';
}
$output .= '</ul>';
$output .= '</div>';
$output .= '</article>';
$output .= '</section>';
return $output;
}
add_shortcode( 'vc_img_carrousel', 'vc_gallery_carrousel' );

Wordpress shortcode pagination

I've created a shortcode for custom post with advanced custom fields. All works correctly except the pagination. I've tried all of the options I can see on other posts, but none work for me. Pagination is working on custom post pages.
function link_carstwo( $atts ) {
extract(shortcode_atts(array(
'cartype' => 'porsche',
'section' => 'make'
), $atts));
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $the_query->max_num_pages
) );
$list = ' ';
echo '<div id="car-container">
<ul id="carlist">';
//Setup the query to retrieve the posts that exist under each term
global $post;
$posts = new WP_Query (array(
'post_type' => 'cars',
'orderby' => 'menu_order',
'order' => 'ASC',
$section => $cartype,
'post_status' => 'publish',
'posts_per_page' => 9,
'paged' => $paged,
));
// Here's the second, nested foreach loop that cycles through the posts associated with this category
while ( $posts->have_posts() ) { $posts->the_post();
////set up post data for use in the loop (enables the_title(), etc without specifying a post ID--as referenced in the stackoverflow link above)
$price = get_field('price', $post->ID);
$car_image = get_field('car_image', $post->ID);
$image_position = get_field('image_position', $post->ID);
$make = get_field('make', $post->ID);
$year = get_field('year', $post->ID);
$date_purchased = get_field('date_purchased', $post->ID);
$finance_type = get_field('finance_type', $post->ID);
$job_title = get_field('job_title', $post->ID);
$model = get_field('model', $post->ID);
$list .= '<li class="carbox">
<p>TEST</p>
<div class="image2" style="background-image:url(' . $car_image .');background-position: ' . $image_position . ' center;"></div>
<p class="car"> '.$make.' ' . $model . ' ' . $year . ' </br> £ ' . $price . ' ' . $date_purchased . '</p>
<p class="finance">' . $finance_type . '</p>
<p class="fademeSmall"> ' . $job_title . '</p>
<p class="linked"></p>
</li>';
}
'</ul></div>';
return
'<div class="navigation centerWidth">'
. $list
.the_posts_pagination( array(
'mid_size' => 2,
'prev_text' => __( '<', 'textdomain' ),
'next_text' => __( '>', 'textdomain' ),
) )
. '<div class="nav-previous">' . get_next_posts_link( __( '<span class="meta-nav">←</span> Older posts' ) ) . '</div>'
. '<div class="nav-next">' . get_previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>' ) ) . '</div>'
. 'TEST</div>' .
wp_reset_query();
}
add_shortcode( 'car-gridtwo', 'link_carstwo' );
Try this for your pagination
<?php
global $wp_query;
$big = 999999999;
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages
) );
?>
The way you are using wp_query and the global variables is extremely convoluted and wrong.
while ( $post->have_posts() ) { $posts->the_post();
On the while condition you should have $posts->have_posts() rather than $post->have_posts()
You also don't need the setup_postdata($post);
I'm not sure that this will solve the issue, everything else seems "fine" to me.
EDIT
Having a closer look at the code I just noticed that your return statement is within the loop, that's wrong and might be the reason why you are having the pagination issue. Just close the While block before the return statement (and obviously remove the last closing bracket, before wp_reset_query). Don't forget to do the change I suggested before as well.

Wordpress: hierarchical list of taxonomy terms

I am hitting a wall here, although it sounds pretty simple: I want to return a hierarchical list of custom post type taxonomy terms. What I get is the first level of terms and nested uls. But the sub terms are not showing. Any ideas?
Here's the code:
function return_terms_index() {
$taxonomies = array(
'taxonomy_name',
);
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'fields' => 'all',
'parent' => 0,
'hierarchical' => true,
'child_of' => 0,
'pad_counts' => false,
'cache_domain' => 'core'
);
$terms = get_terms($taxonomies, $args);
$return .= '<ul>';
foreach ( $terms as $term ) {
// return terms (working)
$return .= sprintf(
'<li id="category-%1$s" class="toggle">%2$s <span class="cat-description">%3$s</span>',
$term->term_id,
$term->name,
$term->description
);
$subterms = get_terms( array(
'parent' => $term->term_id,
'hide_empty' => false
));
$return .= '<ul>';
foreach ( $subterms as $subterm ) {
//return sub terms (not working :( )
$return .= sprintf(
'<li id="category-%1$s" class="toggle">%2$s <span class="cat-description">%3$s</span>',
$subterm->term_id,
$subterm->name,
$subterm->description
);
$return .= '</li>'; //end subterms li
}
$return .= '</ul>'; //end subterms ul
$return .= '</li>'; //end terms li
} //end foreach term
$return .= '</ul>';
return $return;
}
Thanks!
Edit: here's the output.
<ul>
<li id="category-176">
1. <span class="post-count">0</span><span class="cat-description" style="display: none;">Description</span>
<ul id="subTerm-176" style="display: block;"></ul>
</li>
<li id="category-49">
2. <span class="post-count">0</span><span class="cat-description" style="display: none;">Langtitel/Beschreibung</span>
<ul id="subTerm-49" style="display: none;"></ul>
</li>
</ul>
Edit: taxonomies are returned in hierarchical list now, YAY!
But I want to query and display posts of third level taxonomy terms as well and this bit of code doesn't do the trick.
$post_query = new WP_Query($taxonomies, array(
'term' => $subsubterm->term_id
)); ?>
<?php if ( $post_query->have_posts() ) :
$return .= '<ul>';
while ( $post_query->have_posts() ) : $post_query->the_post();
$return .= '<li><a class="link" href="' . get_permalink() . '">' . get_the_title() . '</a></li>' . "\n";
endwhile;
$return .= '</ul>';
wp_reset_postdata();
else:
endif;
It has to be dynamic, so I can't specify a term by name/slug. But is this even possible?
'term' => $subsubterm->term_id
Thanks again.
You have missed to pass $taxonomies in
$subterms = get_terms($taxonomies, array(
'parent' => $term->term_id,
'hide_empty' => false
));
Try following code
function return_terms_index() {
$taxonomies = array(
'taxonomy_name',
);
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'fields' => 'all',
'parent' => 0,
'hierarchical' => true,
'child_of' => 0,
'pad_counts' => false,
'cache_domain' => 'core'
);
$terms = get_terms($taxonomies, $args);
$return .= '<ul>';
foreach ( $terms as $term ) {
// return terms (working)
$return .= sprintf(
'<li id="category-%1$s" class="toggle">%2$s <span class="cat-description">%3$s</span>',
$term->term_id,
$term->name,
$term->description
);
$subterms = get_terms($taxonomies, array(
'parent' => $term->term_id,
'hide_empty' => false
));
$return .= '<ul>';
foreach ( $subterms as $subterm ) {
//return sub terms (not working :( )
$return .= sprintf(
'<li id="category-%1$s" class="toggle">%2$s <span class="cat-description">%3$s</span>',
$subterm->term_id,
$subterm->name,
$subterm->description
);
$return .= '</li>'; //end subterms li
}
$return .= '</ul>'; //end subterms ul
$return .= '</li>'; //end terms li
} //end foreach term
$return .= '</ul>';
return $return;
}
Just use the wp_list_categories() function :
https://developer.wordpress.org/reference/functions/wp_list_categories/
$tax_args = array(
'taxonomy' => 'my_custom_taxonomy',
'orderby' => 'name',
'show_count' => 1,
'hierarchical' => 1,
'title_li' => 'My list title'
);
wp_list_categories($tax_args);

Wordpress shortcode issues with output

Hi I am trying to workout how to use shortcodes on a plugin but I am stuck with this .. Its a plugin I found on http://www.wpbeginner.com/wp-tutorials/how-to-add-rotating-testimonials-in-wordpress/
It is working a little but not outputting the code correctly and not sure why this is happening.
I Have upgraded the code and removed the css and jquery code as I will add this separate files..
Any help will be great!
<?php
/*
Plugin Name: Shortcode test
Version: 0.1
Plugin URI: http://www.websiteplugin.com/
Description: Adding theatre edits to the resume page
Author: Auther name
Author URI: http://www.websiteauther.com/
*/
add_action( 'init', 'wpb_register_cpt_testimonial' );
function wpb_register_cpt_testimonial() {
$labels = array(
'name' => _x( 'Testimonials', 'testimonial' ),
'singular_name' => _x( 'testimonial', 'testimonial' ),
'add_new' => _x( 'Add New', 'testimonial' ),
'add_new_item' => _x( 'Add New testimonial', 'testimonial' ),
'edit_item' => _x( 'Edit testimonial', 'testimonial' ),
'new_item' => _x( 'New testimonial', 'testimonial' ),
'view_item' => _x( 'View testimonial', 'testimonial' ),
'search_items' => _x( 'Search Testimonials', 'testimonial' ),
'not_found' => _x( 'No testimonials found', 'testimonial' ),
'not_found_in_trash' => _x( 'No testimonials found in Trash', 'testimonial' ),
'parent_item_colon' => _x( 'Parent testimonial:', 'testimonial' ),
'menu_name' => _x( 'Testimonials', 'testimonial' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'custom-fields', 'revisions' ),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => true,
'capability_type' => 'post'
);
register_post_type( 'testimonial', $args );
}
$key = "testimonial";
$meta_boxes = array(
"person-name" => array(
"name" => "person-name",
"title" => "Person's Name",
"description" => "Enter the name of the person who gave you the testimonial."),
"position" => array(
"name" => "position",
"title" => "Position in Company",
"description" => "Enter their position in their specific company."),
"company" => array(
"name" => "company",
"title" => "Company Name",
"description" => "Enter the client Company Name"),
"link" => array(
"name" => "link",
"title" => "Client Link",
"description" => "Enter the link to client's site, or you can enter the link to your portfolio page where you have the client displayed.")
);
function wpb_create_meta_box() {
global $key;
if( function_exists( 'add_meta_box' ) ) {
add_meta_box( 'new-meta-boxes', ucfirst( $key ) . ' Information', 'display_meta_box', 'testimonial', 'normal', 'high' );
}
}
function display_meta_box() {
global $post, $meta_boxes, $key;
?>
<div class="form-wrap">
<?php
wp_nonce_field( plugin_basename( __FILE__ ), $key . '_wpnonce', false, true );
foreach($meta_boxes as $meta_box) {
$data = get_post_meta($post->ID, $key, true);
?>
<div class="form-field form-required">
<label for="<?php echo $meta_box[ 'name' ]; ?>"><?php echo $meta_box[ 'title' ]; ?></label>
<input type="text" name="<?php echo $meta_box[ 'name' ]; ?>" value="<?php echo (isset($data[ $meta_box[ 'name' ] ]) ? htmlspecialchars( $data[ $meta_box[ 'name' ] ] ) : ''); ?>" />
<p><?php echo $meta_box[ 'description' ]; ?></p>
</div>
<?php } ?>
</div>
<?php
}
function wpb_save_meta_box( $post_id ) {
global $post, $meta_boxes, $key;
foreach( $meta_boxes as $meta_box ) {
if (isset($_POST[ $meta_box[ 'name' ] ])) {
$data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ];
}
}
if (!isset($_POST[ $key . '_wpnonce' ]))
return $post_id;
if ( !wp_verify_nonce( $_POST[ $key . '_wpnonce' ], plugin_basename(__FILE__) ) )
return $post_id;
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
update_post_meta( $post_id, $key, $data );
}
add_action( 'admin_menu', 'wpb_create_meta_box' );
add_action( 'save_post', 'wpb_save_meta_box' );
function wpb_display_testimonials() {
$return_string .= "<div id=\"testimonials\">";
$args = array( 'post_type' => 'testimonial', 'posts_per_page' => 100, 'orderby' => 'menu_order', 'order' => 'ASC' );
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post();
$data = get_post_meta( $loop->post->ID, 'testimonial', true );
static $count = 0;
if ($count == "1") {
$pn_data = $data[ 'person-name' ];
$p_data = $data[ 'position' ];
$l_data = $data[ 'link' ];
$c_data = $data[ 'company' ];
$con_the = get_the_content( $more_link_text, $stripteaser );
$return_string .= '<div class="slide" style="display: none">
<div class="client-contact-info">'; $return_string .= $pn_data; $return_string .=', '; $return_string .= $p_data; $return_string .=', '; $return_string .= $c_data ; $return_string .='</div>';
$return_string .= '<div class="clear"></div>
<div class="testimonial-quote">'; $return_string .= $con_the; $return_string .='</div>
</div>';
}
else {
$pn_data = $data[ 'person-name' ];
$p_data = $data[ 'position' ];
$l_data = $data[ 'link' ];
$c_data = $data[ 'company' ];
$con_the = get_the_content( $more_link_text, $stripteaser );
$return_string .= '<div class="slide" >
<div class="client-contact-info">';
$return_string .= $pn_data;
$return_string .=', ';
$return_string .= $p_data;
$return_string .=', <a href="';
$return_string .= $l_data;
$return_string .='" title="';
$return_string .= $c_data ; $return_string .= '">';
$return_string .= $c_data ; $return_string .='</a></div>';
$return_string .= '<div class="clear"></div><div class="testimonial-quote">';
$return_string .= $con_the;
$return_string .='</div></div>';
$count++;
}
endwhile;
endif;
$return_string .='</div>';
return $return_string;
}
function register_shortcodes(){
add_shortcode('testme', 'wpb_display_testimonials');
}
add_action( 'init', 'register_shortcodes');
?>
If you look at the Shortcode API "Shortcode handlers ... they accept parameters (attributes) and return a result (the shortcode output)." in your function wpb_display_testimonials() EVERYTHING you want to return should be inside the value of $return_string .. the echo statements and the inline JS can't be used as you have it.
So instead of
?> <div> misc html </div> <?
you want to do something more like:
$return_string += '<div> misc html </div>';
you could also use output buffering though given you are already assembling $return_string best to use that and get it working then you can refactor later.

Resources