I am trying to create my own theme in WordPress. I converted the PSD file to HTML and now I want to make it dynamic with WordPress, I used the mix it up plugin as you know it's not a WordPress plugin so I tried to make it dynamic myself, I used this tutorial which provides codes and video for this issue.
as you can see in the pic, it must show my category but show 'array' and I cant find why?
here is my code
first I create post type named book with taxonomy named books_category
function p2p2_register_book(){
$labels = array(
'name' => _x( 'کتابخانه', 'books'),
'singular_name' => _x( 'کتاب', 'book' ),
'add_new' => _x( 'افزودن کتاب', '' ),
'add_new_item' => __( 'افزودن کتاب جدید' ),
'edit_item' => __( 'ویرایش کتاب' ),
'new_item' => __( 'کتاب جدید' ),
'all_items' => __( 'همه کتاب ها' ),
'search_items' => __( 'جست و جو کتاب' ),
'not_found' => _( 'کتاب یافت نشد' ),
'not_found_in_trash' => __( 'کتاب در زباله دان یافت نشد' ),
'parent_item_colon' => '',
'menu_name' => 'کتابخانه'
);
$args=array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'menu_position' => 2,
'rewrite' => array( 'slug' => 'book' ),
'capability_type' => 'page',
'has_archive' => true,
// 'hierarchical' => false,
'supports' => array( 'title', 'editor', 'thumbnail', 'comments' ,'custom-fields'),
// 'taxonomies' => array( 'Books_category' ),
);
register_post_type('Book',$args);
}
add_action('init', 'p2p2_register_book');
// ============================== Adding post toxonomy to library post ================
function wp_library_post_taxonomy() {
register_taxonomy(
'books_category', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
'book', //post type name
array(
'hierarchical' => true,
'label' => 'book Category', //Display name
'query_var' => true,
'show_admin_column' => true,
'rewrite' => array(
'slug' => 'books_category', // This controls the base slug that will display before each term
'with_front' => true // Don't display the category base before
)
)
);
}
add_action( 'init', 'wp_library_post_taxonomy');
include_once( 'mixitup-plug.php' );
add_theme_support('post_thumbnails');
add_image_size('Books_small_image',150,200,true);
then as the tutorial said I added this code for make it dynamic
<?php
function books_shortcode($atts){
extract( shortcode_atts( array(
'category' => ''
), $atts, '' ));
$q= new WP_Query(
array('posts_per_page'=> 30, 'post_type' => 'Book')
);
//library taxonomy query
global $paged;
global $post;
$args = array(
'post_type' => 'Book',
'paged' => $paged,
' posts_per_page' => -1,
);
$Books = new WP_Query($args);
if(is_array($Books->posts) && !empty($Books->posts)) {
foreach($Books->posts as $Books_post) {
$Books_taxs = wp_get_post_terms($Books_post->ID, 'Books_category', array("fields" => "all"));
if(is_array($Books_taxs) && !empty($Books_taxs)) {
foreach($Books_taxs as $Books_tax) {
$Books_taxs[$Books_tax->slug] = $Books_tax->name;
}
}
}
}
?>
<!--Category Filter-->
<div class="filter-book">
<ul>
<li class="filter active" data-filter="all">همه</li>
<?php foreach($Books_taxs as $Books_tax_slug => $Books_tax_name): ?>
<li class="filter" data-filter=".<?php echo $Books_tax_slug; ?>"><?php echo $Books_tax_name; ?></li>
<?php endforeach; ?>
</ul></div>
<!--End-->
<?php
$list = '<div class="library-item">';
while($q->have_posts()) : $q->the_post();
$idd = get_the_ID();
$small_image_url=wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'Books_small_image');
//Get Texanmy class
$item_classes = '';
$item_cats = get_the_terms($post->ID, 'Books_category');
if($item_cats):
foreach($item_cats as $item_cat) {
$item_classes .= $item_cat->slug . ' ';
}
endif;
$single_link =
$list .= '
<div class="mix single-library cycology '.$item_classes.'">
<div>
<img src="'.$small_image_url[0].'">
<p class="text-center">کتاب جیبی موفقیت یک</p>
</div>
</div>
<div class="mix '.$item_classes.'" >'.get_the_content().'</div>
';
endwhile;
$list.= '</div>';
wp_reset_query();
return $list;
}
add_shortcode('Books', 'Books_shortcode');
?>
it must be some problem with this part of my code because this part show category
<div class="filter-book">
<ul>
<li class="filter active" data-filter="all">همه</li>
<?php foreach($Books_taxs as $Books_tax_slug => $Books_tax_name): ?>
<li class="filter" data-filter=".<?php echo $Books_tax_slug; ?>"><?php echo $Books_tax_name; ?></li>
<?php endforeach; ?>
</ul></div>
Please check you have used echo array function
<li class="filter" data-filter=".<?php echo $Books_tax_slug; ?>"><?php echo $Books_tax_name; ?></li>
You can check it
<?php
# Dynamic Portfolio With Shortcode
function portfolio_shortcode($atts){
extract( shortcode_atts( array(
'category' => ''
), $atts, '' ) );
$q = new WP_Query(
array('posts_per_page' => 50, 'post_type' => 'portfolios')
);
//Portfolio taxanomy query
global $paged;
global $post;
$args = array(
'post_type' => 'portfolios',
'paged' => $paged,
'posts_per_page' => -1,
);
$portfolio = new WP_Query($args);
if(is_array($portfolio->posts) && !empty($portfolio->posts)) {
foreach($portfolio->posts as $gallery_post) {
$post_taxs = wp_get_post_terms($gallery_post->ID, 'portfolio_category', array("fields" => "all"));
if(is_array($post_taxs) && !empty($post_taxs)) {
foreach($post_taxs as $post_tax) {
$portfolio_taxs[$post_tax->slug] = $post_tax->name;
}
}
}
}
?>
<!--Category Filter-->
<div class="portfolio_button_area fix">
<button class="filter portfolio_button active" data-filter="all">Show All</button>
<?php foreach($portfolio_taxs as $portfolio_tax_slug => $portfolio_tax_name): ?>
<button class="filter portfolio_button" data-filter=".<?php echo $portfolio_tax_slug; ?>"><?php echo $portfolio_tax_name; ?></button>
<?php endforeach; ?>
</div>
<!--End-->
<?php
$list = '<div id="Container">';
while($q->have_posts()) : $q->the_post();
$idd = get_the_ID();
//Get Texanmy class
$item_classes = '';
$item_cats = get_the_terms($post->ID, 'portfolio_category');
if($item_cats):
foreach($item_cats as $item_cat) {
$item_classes .= $item_cat->slug . ' ';
}
endif;
$single_link =
$list .= '
<div class="mix '.$item_classes.'" >'.get_the_content().'</div>
';
endwhile;
$list.= '</div>';
wp_reset_query();
return $list;
}
add_shortcode('portfolio', 'portfolio_shortcode');
?>
code reference and more http://www.wp-tutorials.com/how-to-dynamic-mixitup-or-isotope-in-wordpress-step-by-step
I find the answer it's word problem. I use Book but call book so it didn't work.
Related
I have created a Custom Post Type named "products" and a Custom Taxonomy named "product_category" To this custom post type I also created a Cpt-Template file "single-products.php" for displaying individual posts and a Taxonomy-Template "taxonomy-product_category" for showing all of my post for a specific taxonomy.
I use the the_permalink() to get the url of the individual posts and when you click on a post you jump straight to "single-product.php"-page. I managed to get all of this to work, finding the cpt-template single page for a single post but for some reason my wp_query won't run from the "single-product.php"-page. The only thing it will grab is the title, editor and thumbnail-image content from the post, no other custom fields will be displayed. I have create a metabox with some custom fields in my CPT. Those fields works and displays as they should from the taxonomy-archive-page but not from the single-page and I'dont understand why?
Here is my code. I appreciate to get some help on this. Thanks in advance.
====== My Custom Post Type "Products" =======
function create_taxonomy_products() {
$labels = array(
'name' => _x( 'Produktkategorier', 'taxonomy singular name', 'products' ),
'singular_name' => _x( 'Produktkategori', 'taxonomy singular name', 'products' ),
'search_items' => __( 'Sök Produktkategori', 'products' ),
'all_items' => __( 'Alla Produktkategorier', 'products' ),
'parent_item' => __( 'Förälder Produktkategori', 'products' ),
'parent_item_colon' => __( 'Förälder Produktkategori:', 'products' ),
'edit_item' => __( 'Ändra Produktkategori', 'products' ),
'update_item' => __( 'Uppdatera Produktkategori', 'products' ),
'add_new_item' => __( 'Lägg till ny Produktkategori', 'products' ),
'new_item_name' => __( 'Nytt Produktkategorinamn', 'products' ),
'menu_name' => __( 'Produktkategori', 'products' ),
'not_found' => __( 'Inga Produktkategorier hittade.', 'products' ),
'view_item' => __( 'Se Produktkategorier', 'products' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'query_var' => true,
'show_admin_column' => true,
'rewrite' => array( 'slug' => 'produkter' ),
);
register_taxonomy(
// Name of our Taxonomy
'product_category', 'products', $args );
}
add_action('init', 'create_taxonomy_products', 0);
function register_custom_post_type_products() {
$labels = array(
'name' => _x( 'Produkter', 'post type general name', 'products' ),
'singular_name' => _x( 'Produkt', 'post type singular name', 'products' ),
'menu_name' => _x( 'Produkter', 'admin menu', 'products' ),
'name_admin_bar' => _x( 'Produkter', 'add new on admin bar', 'products' ),
'add_new' => _x( 'Lägg till nya Produkter', 'Produkter', 'products' ),
'add_new_item' => __( 'Lägg till ny Produkt', 'products' ),
'new_item' => __( 'Nya Produkter', 'products' ),
'edit_item' => __( 'Ändra Produkter', 'products' ),
'view_item' => __( 'Se Produkter', 'products' ),
'all_items' => __( 'Alla Produkter', 'products' ),
'search_items' => __( 'Sök Produkter', 'products' ),
'parent_item_colon' => __( 'Förälder Produkter:', 'products' ),
'not_found' => __( 'Ingen Produkter hittad.', 'products' ),
'not_found_in_trash' => __( 'Ingen Produkt hittad i papperskorgen.', 'products' ),
'featured_image' => __( 'Produktbild', 'products' ),
'set_featured_image' => __( 'Lägg till Produktbild', 'products' ),
'remove_featured_image' => __( 'Ta bort Produktbild', 'products' ),
'use_featured_image' => __( 'Använd Produktbild', 'products' ),
);
$features = array(
'title',
'thumbnail',
'editor',
);
$args = array (
'labels' => $labels,
'public' => true,
'supports' => $features,
'has_archive' => false,
'menu_icon' => 'dashicons-networking',
'taxonomies' => array(
'product_category',
),
);
// Name of our Custom Post Type
register_post_type('products', $args);
}
add_action( 'init', 'register_custom_post_type_products' );
function create_meta_box_products() {
add_meta_box(
'products_metabox',
'Produkter:',
'create_metabox_products',
'products',
'normal',
'default'
);
}
function products_metabox( $post ) {
echo 'Info here';
}
add_action( 'add_meta_boxes', 'create_meta_box_products' );
function create_metabox_products( $post ) {
?>
<form action="" method="post">
<?php
wp_nonce_field('kk_metabox_nonce', 'kk_nonce');
$products_name = get_post_meta($post->ID, 'products_name', true);
$products_desc = get_post_meta($post->ID, 'products_desc', true);
?>
<p>
<span><i>Type in name of product</i></span><br/>
<input type="text" name="products_name" value="<?php echo esc_attr( $products_name ); ?>" placeholder="..." />
</p>
<p>
<span><i>Type in description of product</i></span><br/>
<input type="text" name="products_desc" value="<?php echo esc_attr( $products_desc ); ?>" placeholder="..." />
</p>
</form>
<?php
}
add_action( 'save_post', 'save_meta_products_name' );
function save_meta_products_name( $post_id ) {
if(!isset($_POST['kk_nonce']) ||
!wp_verify_nonce($_POST['kk_nonce'],
'kk_metabox_nonce')) return;
if(isset($_POST['products_name'])) {
$new_value_products_name = ($_POST['products_name']);
update_post_meta($post_id, 'products_name', $new_value_products_name);
}
}
add_action( 'save_post', 'save_meta_products_desc' );
function save_meta_products_desc( $post_id ) {
if(!isset($_POST['kk_nonce']) ||
!wp_verify_nonce($_POST['kk_nonce'],
'kk_metabox_nonce')) return;
if(isset($_POST['products_desc'])) {
$new_value_products_desc = ($_POST['products_desc']);
update_post_meta($post_id, 'products_desc', $new_value_products_desc);
}
}
====== Custom Post Type Template "single-product.php" =======
if ( have_posts() ) {
?>
<div class="container">
<div class="row">
<?php
global $wp_query;
$term = $wp_query->get_queried_object();
$post_type = get_post_type( $post->ID );
$wp_query = new WP_Query(array(
'post_type' => 'products',
'posts_per_page' => -1, // -1 = show all posts
'tax_query' => array(array('taxonomy' => 'product_category', 'field' => 'id', 'terms' => $term->term_id )),
));
?>
<?php
while( $wp_query->have_posts() ) {
$wp_query->the_post();
$products_name = get_post_meta($post->ID, 'products_name');
$products_desc = get_post_meta($post->ID, 'products_desc');
?>
<article class="products-col col-12 collapse entry-content">
<div class="col-12">
<?php
$productsName = $products_name[0] ? '<h2>'.$products_name[0].'</h2>' : '';
echo isset($productsName) ? $productsName : '';
$productsdesc = $products_desc[0] ? '<p>'.$products_desc[0].'</p>' : '';
echo isset($productsdesc) ? $productsdesc : '';
the_post_thumbnail();
the_content();
?>
</div>
</article>
<?php
} // while
wp_reset_postdata();
?>
</div> <!-- .row -->
</div> <!-- .container -->
<?php
} // if
Cheers, you can use the archive-products.php to realise an archive.
Wordpress provides you a WP_Query for your single-{post_typ}.php and your archive-{post-typ}.php
There is no need to redeclare the WP_Query:
global $wp_query;
$term = $wp_query->get_queried_object();
$post_type = get_post_type( $post->ID );
$wp_query = new WP_Query(array(
'post_type' => 'products',
'posts_per_page' => -1, // -1 = show all posts
'tax_query' => array(array('taxonomy' => 'product_category', 'field' => 'id', 'terms' => $term->term_id )),
));
Example for archive-{post-typ}.php:
<?php
get_header();
if(have_posts()) : while(have_posts()) : the_post();
the_title();
echo '<div class="entry-content">';
the_content();
echo '</div>';
endwhile; endif;
get_footer();
?>
Example for single-{post-typ}.php:
<?php get_header(); ?>
<main id="main" class="site-main" role="main">
<?php
// Start the loop
while ( have_posts() ) : the_post();
echo '<h1>';
the_title();
echo '</h1>';
echo '<a href="';
the_permalink();
echo '">That\'s me! -> '; the_title();
echo '</a>';
the_content();
// End the loop.
endwhile;
?>
</main><!-- .site-main -->
<?php get_footer(); ?>
The code-snippets aren't tested. Hope I could help you out
I finally got this to work! I figured out thanks to Lukas R. explanation of not redeclare wp_query-class in my single-page (single-products.php). I could not get the archive-products.php to work but instead I already had my Custom Taxonomy archive for this purpose, (taxonomy-product_category). All I had to do was include my fields in the loop
<?php get_header(); ?>
<main id="main" class="site-main" role="main">
<?php
// Start the loop
while ( have_posts() ) : the_post();
$products_intro = get_post_meta($post->ID, 'products_intro');
$products_desc = get_post_meta($post->ID, 'products_desc');
echo '<h1>';
the_title();
echo '</h1>';
the_post_thumbnail();
the_content();
// Custom Metabox-fields
$productsIntro = $products_intro[0] ? '<p class="products-title padd-bottom">'.$products_intro[0].'</p>' : '';
echo isset($productsIntro) ? $productsIntro : '';
$productsdesc = $products_desc[0] ? '<p class="products-title padd-bottom">'.$products_desc[0].'</p>' : '';
echo isset($productsdesc) ? $productsdesc : '';
// Advanced Custom Fields
the_field('innehall');
// End the loop.
endwhile;
?>
</main>
<?php get_footer(); ?>
I have found some solution on SO and some other site but my issue does not solve those way.Please anyone tell me where is the problem? I get pagination but do not get custom post (gallery section) content when i click on second page.What i have tried so far:
custom post (gallery) creation:
function jellythemes_media_gallery() {
$labels = array(
'name' => __('Gallery', 'framework'),
'singular_name' => __('Gallery', 'framework'),
'add_new' => __('Add media', 'framework'),
'add_new_item' => __('Add media', 'framework'),
'edit_item' => __('Edit media', 'framework'),
'new_item' => __('New media', 'framework'),
'view_item' => __('View media', 'framework'),
'search_items' => __('Search media', 'framework'),
'not_found' => __('No media found', 'framework'),
'not_found_in_trash' => __('No media found in Trash', 'framework'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'show_in_nav_menus' => false,
'capability_type' => 'post',
'hierarchical' => false,
'exclude_from_search' => true,
'menu_position' => 5,
'supports' => array('title')
);
register_post_type('media',$args);
}
and query :
function jellythemes_gallery($atts, $content=null) {
extract( shortcode_atts( array(
'limit' => -1
), $atts ) );
global $post;
$back=$post; //Backup post data
$return = '<div id="portfolio">
<div class="section portfoliocontent">
<section id="i-portfolio" class="clear">';
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$media = new WP_Query(array('post_type'=>'media', 'posts_per_page' => esc_attr($limit),'paged' => $paged,));
if($media->have_posts()) :
while ($media->have_posts()) : $media->the_post();
$image = get_post_meta( $post->ID, '_jellythemes_media_photo', true );
$video = get_post_meta( $post->ID, '_jellythemes_media_video', true );
$img = wp_get_attachment_image_src($image, 'media_thumb');
$return .= '<div class="ch-grid element">
<img class="ch-item" src="' . $img[0] .'" alt="' . get_the_title() . '" />';
if (empty($video)) {
$return .= '<a class="fancybox img-lightbox" rel="" href="' . $img[0] .'">';
} else {
$return .= '<a class="fancybox-media" rel="" href="' . $video.'">';
}
$return .= ' <div>
<span class="p-category ' . (empty($video) ? 'photo' : 'video') . '"></span>
</div>
</a>
</div>';
endwhile;
$total_pages = $media->max_num_pages;
if ($total_pages > 1){
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'current' => $current_page,
'total' => $total_pages,
'prev_text' => __('« prev'),
'next_text' => __('next »'),
));
}
else {echo "<h3>404 Error</h3>";}
endif;
wp_reset_postdata();
$post=$back; //restore post object
$return .= '</section>
</div>
</div>';
return $return;
}
add_shortcode( 'jellythemes_gallery', 'jellythemes_gallery' );
Please could anyone one tell me why in second pagination i do not get content of custom post (gallery) it is same as page one?
You can use wp-paginate plugin. https://wordpress.org/plugins/wp-paginate/
Or you can also use below mention code for pagination of custom post type.
<?php
$postsperpage = get_option('posts_per_page');
if($media->max_num_pages > $postsperpage){
?>
<nav role="navigation">
<ul class="cd-pagination no-space">
<li class="button"><?php echo get_previous_posts_link( '' ); ?></li>
<?php
for($count=1; $count<=$media->max_num_pages; $count++){
if($count == $paged){
$pagiClass="current";
}else{
$pagiClass="";
}
echo '<li><a class="'.$pagiClass.'" href="'.get_permalink($current_post_id).'page/'.$count.'">'.$count.'</a></li>';
}
?>
<li class="button"><?php echo get_next_posts_link( '', $media->max_num_pages ); ?></li>
</ul>
</nav>
<?php
}
?>
I am trying to get print names of custom taxonomy that i have created for products.
function create_product_taxonomies()
{
// Add new taxonomy, make it hierarchical (like categories)
$labels = array(
'name' => _x('product_categories', 'taxonomy general name'),
'singular_name' => _x('Product', 'taxonomy singular name'),
'search_items' => __('Search Product Category'),
'all_items' => __('All Product Categorie(s)'),
'parent_item' => __('Parent Product Category'),
'parent_item_colon' => __('Parent Product Category:'),
'edit_item' => __('Edit Product Category'),
'update_item' => __('Update Product Category'),
'add_new_item' => __('Add New'),
'new_item_name' => __('New Product Name'),
'menu_name' => __('Product Categories'),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array('slug' => 'product_categories', 'with_front' => true));
register_taxonomy('product_categories', array('products'), $args);
i have added data through the wordpress admin panel. Now i want to Display the names of the categories in product.php file.
function getLatestProducts()
{
$args = array(
'post_status' => 'publish',
'post_type' => 'products',
'posts_per_page' => 12,
'order' => 'ASC'
);
$result = '<div class="col-sm-3">';
$loop = new WP_Query($args);
$i=0;
while ($loop->have_posts())
{
$loop->the_post();
$clink=get_permalink($post->ID);
$desc=get_the_excerpt();
$categories = get_terms( 'product_categories');
$desc = strip_tags(str_replace(array("<p>", "</p>"), "", $desc));
$the_imgurl = get_post_custom_values('_cus_n__image');
$theimage=$the_imgurl[0];
$the_locurl = get_post_custom_values('_cus_n__location');
$theloc=$the_locurl[0];
echo $categories;
$result .='<div class="product-warp">';
$result .='<div class="product"> <img src="/wp-content/themes/cake/images/pro1.jpg" title="" alt=""> </div>';
$result .='<div class="product-name">';
$result .='<h5>'.$categories.'</h5>';
$result .='</div>';
$result .='</div>';
$i++;
}
$result .= '</div>';
if($i > 0){
return $result;
} else {
return "";
}
}
it is just printing this arrayarrayarrayarrayarrayarray
Ok bro you can use get_terms function for this purpose. Here is the example:
First Part
<?php
$args = array(
'orderby' => 'name'
);
$terms = get_terms('product_categories', $args);
foreach($terms as $term) {
?>
<a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
<?php echo $term->name; ?>
</a>
<?php
}
?>
I only give you an example. You can paste my code where you want.
Second Part
Now use the WordPress Taxonomy Template for that when user click on one of your category and next page show all the related products of clicked category and also you must read this.
If you read taxonomy Template link then we go to next step.
Now you create a file taxonomy-product_categories.php in your theme root folder.
This create template for you taxonomy.
Now in this file here is the complete code:
<?php
get_header();
$slug = get_queried_object()->slug; // get clicked category slug
$name = get_queried_object()->name; // get clicked category name
$tax_post_args = array(
'post_type' => 'products', // your post type
'posts_per_page' => 999,
'orderby' => 'id',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'product_categories', // your taxonomy
'field' => 'slug',
'terms' => $slug
)
)
);
$tax_post_qry = new WP_Query($tax_post_args);
if($tax_post_qry->have_posts()) :
while($tax_post_qry->have_posts()) :
$tax_post_qry->the_post();
the_title();
the_content();
endwhile;
endif;
get_footer();
?>
Once again I told you that I give you only a code you can merge this code in your theme.
Hope this'll help you.
I have created the custom post. I want to list down posts, but my shortcodes are not working.
Here is my code
function.php
// register a custom post type called 'Products'
function wptp_create_post_type() {
$labels = array(
'name' => __( 'Products' ),
'singular_name' => __( 'product' ),
'add_new' => __( 'New product' ),
'add_new_item' => __( 'Add New product' ),
'edit_item' => __( 'Edit product' ),
'new_item' => __( 'New product' ),
'view_item' => __( 'View product' ),
'search_items' => __( 'Search products' ),
'not_found' => __( 'No product Found' ),
'not_found_in_trash' => __( 'No product found in Trash' ),
);
$args = array(
'labels' => $labels,
'has_archive' => true,
'public' => true,
'hierarchical' => false,
'supports' => array(
'title',
'editor',
'excerpt',
'custom-fields',
'thumbnail',
'page-attributes'
),
'taxonomies' => array( 'post_tag', 'category' ),
);
register_post_type('product', $args );
}
add_action( 'init', 'wptp_create_post_type' );
product-page.php
add_shortcode( 'list-posts', 'rmcc_post_listing_parameters_shortcode' );
function rmcc_post_listing_parameters_shortcode( $atts ) {
ob_start();
extract( shortcode_atts( array (
'type' => 'product',
'order' => 'date',
'orderby' => 'title',
'posts' => -1,
'category' => '',
), $atts ) );
$options = array(
'post_type' => $type,
'order' => $order,
'orderby' => $orderby,
'posts_per_page' => $posts,
'category_name' => $category,
);
$query = new WP_Query( $options );
if ( $query->have_posts() ) { ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_title(); ?>
</li>
<?php endwhile;
wp_reset_postdata(); ?>
</ul>
<?php $myvariable = ob_get_clean();
return $myvariable;
}
}
I have created a page from dashboard and select product-page as template and when I preview or load the page, but I couldn't see my posts.
I have try these below shortcodes on my page. Nothing works out for me
[list-posts]
[list-posts type="products" category = "movies" orderby="name" order="ASC"]
I followed this tutorial
Hello you need to add all code in your function.php i am pasting my what i have done
function.php
<?php
function wptp_create_post_type() {
$labels = array(
'name' => __( 'News' ),
'singular_name' => __( 'News' ),
'add_new' => __( 'New News' ),
'add_new_item' => __( 'Add New News' ),
'edit_item' => __( 'Edit News' ),
'new_item' => __( 'New News' ),
'view_item' => __( 'View News' ),
'search_items' => __( 'Search News' ),
'not_found' => __( 'No News Found' ),
'not_found_in_trash' => __( 'No News found in Trash' ),
);
$args = array(
'labels' => $labels,
'has_archive' => true,
'public' => true,
'hierarchical' => false,
'supports' => array(
'title',
'editor',
'excerpt',
'custom-fields',
'thumbnail',
'page-attributes'
),
'taxonomies' => array( 'post_tag', 'category' ),
);
register_post_type('News', $args );
}
add_action( 'init', 'wptp_create_post_type' );
add_shortcode( 'list-posts', 'rmcc_post_listing_parameters_shortcode' );
function rmcc_post_listing_parameters_shortcode( $atts ) {
ob_start();
extract( shortcode_atts( array (
'type' => 'News',
'order' => 'date',
'orderby' => 'title',
'posts' => -1,
'category' => '',
), $atts ) );
$options = array(
'post_type' => $type,
'order' => $order,
'orderby' => $orderby,
'posts_per_page' => $posts,
'category_name' => $category,
);
$query = new WP_Query( $options );
if ( $query->have_posts() ) { ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_title(); ?>
</li>
<?php endwhile;
wp_reset_postdata(); ?>
</ul>
<?php $myvariable = ob_get_clean();
return $myvariable;
}
}
?>
product-page.php
echo do_shortcode('[list-posts]');
I think that would help you. Let me know if you want something else
Move the code for your shortcode out of product-page.php into functions.php. Also, [list-posts type="products" category = "movies" orderby="name" order="ASC"] should have type="product" since your post type is product.
Leave ob_* functions for when there's no alternative.
WP_Query can be changed for get_posts() and while ( has_posts() ) for a regular foreach(). The only trouble is post_class(), but the core function is just one line, so easy to adapt. Also, extract() is outdated.
add_shortcode( 'list-posts', 'rmcc_post_listing_parameters_shortcode' );
function rmcc_post_listing_parameters_shortcode( $atts ) {
$args = shortcode_atts( array(
'type' => 'News',
'order' => 'date',
'orderby' => 'title',
'posts' => -1,
'category' => '',
), $atts );
$options = array(
'post_type' => $args['type'],
'order' => $args['order'],
'orderby' => $args['orderby'],
'posts_per_page' => $args['posts'],
'category_name' => $args['category'],
);
$posts = get_posts( $options );
$html = 'No posts found.';
if ( $posts ) {
$html = '<ul>';
foreach( $posts as $post ) {
$html .= sprintf(
'<li id="post-%s" class="%s">%s</li>',
$post->ID,
join( ' ', get_post_class( '', $post->ID ) ), // simplified version of get_class()
get_the_permalink( $post->ID ),
$post->post_title
);
}
$html .= '</ul>';
}
return $html;
}
Do not use extract() in a shortcode. In fact, extract(), should never be used. Here is an example of a shortcode I've done recently on another answer on WPSE. Use and modify as needed
add_shortcode( 'news_box', 'newsbox_new_loading_shortcode' );
function newsbox_new_loading_shortcode($atts){
ob_start();
$a = shortcode_atts(
[
'posts_per_page' => '-1',
'news_box_title' => 'Latest News',
'news_box_more' => '',
'post_type' => 'post',
'taxonomy' => '',
'terms' => '',
'category' => '',
],
$atts
);
if( '' == $a['taxonomy'] || '' == $a['terms'] ) {
if( '' == $a['category'] ) {
$args = [
'posts_per_page' => $a['posts_per_page'],
'post_type' => $a['post_type'],
];
}else{
$args = [
'posts_per_page' => $a['posts_per_page'],
'post_type' => $a['post_type'],
'category_name' => $a['category'],
];
}
}else{
$args = [
'posts_per_page' => $a['posts_per_page'],
'post_type' => $a['post_type'],
'tax_query' => [
[
'taxonomy' => $a['taxonomy'],
'field' => 'slug',
'terms' => $a['terms'],
]
]
];
}
//The following lines is for the excerpt more text NEW!!
if( 'post' != $a['post_type'] && '' != $a['news_box_more'] ){
$read_more_text = $a['news_box_more'];
}else {
$read_more_text = "Read More »";
}
// end of excerpt more text code
$q = new WP_Query($args);
if ( $q->have_posts() ) :
while($q->have_posts()) : $q->the_post();
$newsbox_post_img_src = wp_get_attachment_image_src(get_post_thumbnail_id(), '', false, '' );
// wp_trim_words function NEW!!
$content = get_the_content();
$trimmed_content = wp_trim_words( $content, 55, ' ...' . $read_more_text . '' );
// wp_trim_words function
?>
<li class="news-item">
<table cellpadding="4">
<tr>
<td>
<?php if( !empty($newsbox_post_img_src)) { ?>
<img src="<?php echo $newsbox_post_img_src[0]; ?>" width="100" class="img-circle" />
<?php } ?>
</td>
<td>
<?php echo $trimmed_content; // Replaced the_excerpt() ?>
</td>
</tr>
</table>
</li>
<?php endwhile;
$list = ob_get_clean();
return $list;
endif;
wp_reset_postdata();
}
For support for PHP < 5.4, you can do the following for the shortcode function.
add_shortcode( 'news_box', 'newsbox_new_loading_shortcode' );
function newsbox_new_loading_shortcode($atts){
ob_start();
$a = shortcode_atts(
array(
'posts_per_page' => '-1',
'news_box_title' => 'Latest News',
'news_box_more' => '',
'post_type' => 'post',
'taxonomy' => '',
'terms' => '',
'category' => '',
),
$atts
);
if( '' == $a['taxonomy'] || '' == $a['terms'] ) {
if( '' == $a['category'] ) {
$args = array(
'posts_per_page' => $a['posts_per_page'],
'post_type' => $a['post_type'],
);
}else{
$args = array(
'posts_per_page' => $a['posts_per_page'],
'post_type' => $a['post_type'],
'category_name' => $a['category'],
);
}
}else{
$args = array(
'posts_per_page' => $a['posts_per_page'],
'post_type' => $a['post_type'],
'tax_query' => array(
array(
'taxonomy' => $a['taxonomy'],
'field' => 'slug',
'terms' => $a['terms'],
),
),
);
}
//The following lines is for the excerpt more text NEW!!
if( 'post' != $a['post_type'] && '' != $a['news_box_more'] ){
$read_more_text = $a['news_box_more'];
}else {
$read_more_text = "Read More »";
}
// end of excerpt more text code
$q = new WP_Query($args);
if ( $q->have_posts() ) :
while($q->have_posts()) : $q->the_post();
$newsbox_post_img_src = wp_get_attachment_image_src(get_post_thumbnail_id(), '', false, '' );
// wp_trim_words function NEW!!
$content = get_the_content();
$trimmed_content = wp_trim_words( $content, 55, ' ...' . $read_more_text . '' );
// wp_trim_words function
?>
<li class="news-item">
<table cellpadding="4">
<tr>
<td>
<?php if( !empty($newsbox_post_img_src)) { ?>
<img src="<?php echo $newsbox_post_img_src[0]; ?>" width="100" class="img-circle" />
<?php } ?>
</td>
<td>
<?php echo $trimmed_content; // Replaced the_excerpt() ?>
</td>
</tr>
</table>
</li>
<?php endwhile;
$list = ob_get_clean();
return $list;
endif;
wp_reset_postdata();
}
I have been following many tutorials on a portfolio which uses quicksand.js to do a filter animation. In the function i can create filters (categories) with slugs. I can't, after endless hour of reading, figure out how to only display the thumbnails from a certain filter.
I've included the parts of the portfolio from my functions.php
I know this is a lot of code, but this is a last resort. I can't get it working so i am hoping some php / wordpress guru might point out something i've missed.
Through reading up on it, i did managed to pull out JUST the featured images posted in 'featured' by using:
<?php
$args = array(
'post_type' => 'portfolio',
'tax_query' => array(
array(
'taxonomy' => 'filter',
'field' => 'slug',
'terms' => 'featured'
)
)
);
$query = new WP_Query( $args );
?>
However, this just pulls out the image and it's title, without the formatted HTML i need. But applying this to what i already use is where i get completely lost.
Thanks in advance.
My Index.php
h2>Featured Work</h2>
<ul id="image_gallery" class="group index_gallery filterable-grid">
<?php
// Query Out Database
$wpbp = new WP_Query(array( 'post_type' => 'portfolio', 'posts_per_page' =>'9' ) );
?>
<?php
$terms = get_terms("filter");
$count = count($terms);
if ( $count > 0 ){
echo "<ul>";
foreach ( $terms as $term ) {
echo "<li>" . $term->name . "</li>";
}
echo "</ul>";
}
?>
<?php
// Begin The Loop
if ($wpbp->have_posts()) : while ($wpbp->have_posts()) : $wpbp->the_post();
?>
<?php
// Get The Taxonomy 'Filter' Categories
$terms = get_the_terms( get_the_ID(), 'filter' );
?>
<?php
$large_image = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'fullsize', false, '' );
$large_image = $large_image[0];
?>
<?php
//Apply a data-id for unique indentity,
//and loop through the taxonomy and assign the terms to the portfolio item to a data-type,
// which will be referenced when writing our Quicksand Script
?>
<li class="gallery_image" data-id="id-<?php echo $count; ?>" data-type="<?php foreach ($terms as $term) { echo strtolower(preg_replace('/\s+/', '-', $term->name)). ' '; } ?>">
<?php
// Check if wordpress supports featured images, and if so output the thumbnail
if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) :
?>
<?php // Output the featured image ?>
<a rel="prettyPhoto[gallery]" class="zoom" href="<?php echo $large_image ?>">
<img class="mag" src="<?php bloginfo('template_url'); ?>/imgs/mag.png"/><div class="thumb_bg"></div><?php the_post_thumbnail('portfolio'); ?>
</a>
<?php endif; ?>
<!--<?php // Output the title of each portfolio item ?>
<p><?php echo get_the_title(); ?></p>-->
</li>
<?php $count++; // Increase the count by 1 ?>
<?php endwhile; endif; // END the Wordpress Loop ?>
<?php wp_reset_query(); // Reset the Query Loop?>
</ul>
<div class="gallery_control">
<span class="icon-search"></span>View more
</div>
<?php
$taxonomy = 'filter';
$terms = get_terms( $taxonomy, '' );
if ($terms) {
foreach($terms as $term) {
echo '<p>' . '<a href="' . esc_attr(get_term_link($term, $taxonomy)) . '" title="' . sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a> has ' . $term->count . ' post(s). </p> ';
}
}
?>
Portfolio workings:
// function: post_type BEGIN
function post_type()
{
$labels = array(
'name' => __( 'Portfolio'),
'singular_name' => __('Portfolio'),
'rewrite' => array(
'slug' => __( 'portfolio' )
),
'add_new' => _x('Add Item', 'portfolio'),
'edit_item' => __('Edit Portfolio Item'),
'new_item' => __('New Portfolio Item'),
'view_item' => __('View Portfolio'),
'search_items' => __('Search Portfolio'),
'not_found' => __('No Portfolio Items Found'),
'not_found_in_trash' => __('No Portfolio Items Found In Trash'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => null,
'supports' => array(
'title',
'editor',
'thumbnail'
)
);
register_post_type(__( 'portfolio' ), $args);
} // function: post_type END
// function: portfolio_messages BEGIN
function portfolio_messages($messages)
{
$messages[__( 'portfolio' )] =
array(
0 => '',
1 => sprintf(('Portfolio Updated. View portfolio'), esc_url(get_permalink($post_ID))),
2 => __('Custom Field Updated.'),
3 => __('Custom Field Deleted.'),
4 => __('Portfolio Updated.'),
5 => isset($_GET['revision']) ? sprintf( __('Portfolio Restored To Revision From %s'), wp_post_revision_title((int)$_GET['revision'], false)) : false,
6 => sprintf(__('Portfolio Published. View Portfolio'), esc_url(get_permalink($post_ID))),
7 => __('Portfolio Saved.'),
8 => sprintf(__('Portfolio Submitted. <a target="_blank" href="%s">Preview Portfolio</a>'), esc_url( add_query_arg('preview', 'true', get_permalink($post_ID)))),
9 => sprintf(__('Portfolio Scheduled For: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Portfolio</a>'), date_i18n( __( 'M j, Y # G:i' ), strtotime($post->post_date)), esc_url(get_permalink($post_ID))),
10 => sprintf(__('Portfolio Draft Updated. <a target="_blank" href="%s">Preview Portfolio</a>'), esc_url( add_query_arg('preview', 'true', get_permalink($post_ID)))),
);
return $messages;
} // function: portfolio_messages END
// function: portfolio_filter BEGIN
function portfolio_filter()
{
register_taxonomy(
__( "filter" ),
array(__( "portfolio" )),
array(
"hierarchical" => true,
"label" => __( "Filter" ),
"singular_label" => __( "Filter" ),
"rewrite" => array(
'slug' => 'filter',
'hierarchical' => true
)
)
);
} // function: portfolio_filter END
add_action( 'init', 'post_type' );
add_action( 'init', 'portfolio_filter', 0 );
add_filter( 'post_updated_messages', 'portfolio_messages' );
I am not sure what you are doing here but change this
<?php
$large_image = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'fullsize', false, '' );
$large_image = $large_image[0];
?>
to this
<?php
$large_images[] = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'fullsize', false, '' );
$large_image = $large_images[0];
?>
I found a solution:
<?php
$args = array(
'post_type' => 'project',
'tax_query' => array(
array(
'taxonomy' => 'filter',
'field' => 'slug',
'terms' => 'featured'
)
)
);
$query = new WP_Query( $args );
?>
Only displays my filtered item with a name of featured.
This is the code I use to get full image and thumb of attached images:
$args = array(
'order' => 'ASC',
'post_mime_type' => 'image',
'post_parent' => $post->ID,
'post_status' => null,
'post_type' => 'attachment',
);
$upload_dir = wp_upload_dir();
$upload_url = $upload_dir['baseurl'];
// Get img data
$attachments = get_children( $args );
$images = array();
// Loop through attached images and get thumb + large img url
foreach($attachments as $attachment) {
$image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' );
$img['thumb'] = $image_attributes[0];
$image_attributes = wp_get_attachment_image_src( $attachment->ID, 'large' );
$img['large'] = $image_attributes[0];
array_push($images,$img);
}
// Get the image that you have set as the featured image in the post
$featured_img = wp_get_attachment_url(get_post_thumbnail_id($post->ID));
$featured_img_thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' );