Creare uno shortcode per visualizzare i custom post types con una specifica tassonomia

21 lug 2016, 21:54:57
Visualizzazioni: 39.3K
Voti: 7

Ho creato un template di pagina per elencare tutti i prodotti di una specifica linea di prodotti. Ora voglio elencare tutti i post di questo custom post type (prodotti) basandomi sulla tassonomia descritta nello shortcode per ogni pagina.

Esempio:

Pagina "Elenco di tutti i prodotti Prime"

[products line="prime"]

Ho provato questo codice:

function shortcode_mostra_produtos ( $atts ) {
  $atts = shortcode_atts( array(
    'default' => ''
  ), $atts );
    $terms = get_terms('linhas');
    wp_reset_query();
    $args = array('post_type' => 'produtos',
      'tax_query' => array(
        array(
          'taxonomy' => 'linhas',
          'field' => 'slug',
          'terms' => $atts,
        ),
      ),
     );
     $loop = new WP_Query($args);
     if($loop->have_posts()) {
        while($loop->have_posts()) : $loop->the_post();
            echo ' "'.get_the_title().'" ';
        endwhile;
     }
}
add_shortcode( 'produtos','shortcode_mostra_produtos' );
3
Commenti

Hai provato a farlo o hai del codice da mostrare?

Howdy_McGee Howdy_McGee
21 lug 2016 22:07:55

Ho provato questo: https://gist.github.com/luanpiegas/51560598cbee58e6881531ee003feab0

Luan Luan
21 lug 2016 22:09:22

È un buon inizio - a volte le persone qui sono più propense a rispondere alle domande quando sanno che chi chiede ha tentato una soluzione (e non sta solo chiedendo codice). Potrebbe essere utile modificare la tua domanda e aggiungere quel frammento di codice :)

Howdy_McGee Howdy_McGee
21 lug 2016 22:18:02
Tutte le risposte alla domanda 3
0

Innanzitutto, è sempre meglio registrare gli shortcode durante init piuttosto che direttamente nel file functions.php. Almeno add_shortcode() dovrebbe essere in init. Comunque, iniziamo!

Quando usi add_shortcode(), il primo parametro sarà il nome dello shortcode e il secondo sarà la funzione di callback. Questo significa che:

[products line="prime"]

Dovrebbe essere invece:

[produtos line="prime"]

Finora abbiamo questo:

/**
 * Registra tutti gli shortcodes
 *
 * @return null
 */
function register_shortcodes() {
    add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );

/**
 * Callback dello Shortcode Prodotti
 * - [produtos]
 * 
 * @param Array $atts
 *
 * @return string
 */
function shortcode_mostra_produtos( $atts ) {
    /** Il nostro schema andrà qui
}

Diamo un'occhiata all'elaborazione degli attributi. Il modo in cui funziona shortcode_atts() è che cercherà di abbinare gli attributi passati allo shortcode con gli attributi nell'array passato, con il lato sinistro come chiave e il lato destro come valori predefiniti. Quindi dobbiamo cambiare defaults in line - se vogliamo impostare una categoria predefinita, questo sarebbe il posto:

$atts = shortcode_atts( array(
    'line' => ''
), $atts );

SE l'utente aggiunge un attributo allo shortcode line="test", allora il nostro indice dell'array line conterrà test:

echo $atts['line']; // Stampa 'test'

Tutti gli altri attributi verranno ignorati a meno che non li aggiungiamo all'array shortcode_atts(). Infine, è solo questione di WP_Query e stampare ciò che ti serve:

/**
 * Registra tutti gli shortcodes
 *
 * @return null
 */
function register_shortcodes() {
    add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );

/**
 * Callback dello Shortcode Prodotti
 * 
 * @param Array $atts
 *
 * @return string
 */
function shortcode_mostra_produtos( $atts ) {
    global $wp_query,
        $post;

    $atts = shortcode_atts( array(
        'line' => ''
    ), $atts );

    $loop = new WP_Query( array(
        'posts_per_page'    => 200,
        'post_type'         => 'produtos',
        'orderby'           => 'menu_order title',
        'order'             => 'ASC',
        'tax_query'         => array( array(
            'taxonomy'  => 'linhas',
            'field'     => 'slug',
            'terms'     => array( sanitize_title( $atts['line'] ) )
        ) )
    ) );

    if( ! $loop->have_posts() ) {
        return false;
    }

    while( $loop->have_posts() ) {
        $loop->the_post();
        echo the_title();
    }

    wp_reset_postdata();
}
21 lug 2016 22:51:50
0
    add_shortcode( 'product-list','bpo_product_list' );
function bpo_product_list ( $atts ) {
  $atts = shortcode_atts( array(
    'category' => ''
  ), $atts );
    $terms = get_terms('product_category');
    wp_reset_query();
    $args = array('post_type' => 'product',
      'tax_query' => array(
        array(
          'taxonomy' => 'product_category',
          'field' => 'slug',
          'terms' => $atts,
        ),
      ),
     );
     $loop = new WP_Query($args);
     if($loop->have_posts()) {
        while($loop->have_posts()) : $loop->the_post();
            echo ' "'.get_the_title().'" ';
        endwhile;
     }

     else {
            echo  'Spiacenti, nessun articolo trovato';
          }
}

Nel codice sopra, ho creato un CPT product e una tassonomia product_category per il CPT product.

[product-list category="shirts"]

Il codice sopra funziona perfettamente!

4 nov 2018 13:29:03
2
-1

**Prova questo**

function shortcode_bws_quiz_maker($id)
{
  if($id!='')
  {
    $post_id=$id[0];
    $html='';
    global $wpdb;
   $args=array('post_type'=>'post_type','p'=>$post_id);
   $wp_posts=new WP_Query($args);
   $posts=$wp_posts->posts;
  $html.="Scrivi qui quello che vuoi ottenere";
    return $html;

  }
  else
  {
    return 'Inserisci uno shortcode corretto';    
  }

}
add_shortcode('bws_quiz_maker','shortcode_bws_quiz_maker');
20 giu 2017 10:33:40
Commenti

Per favore [modifica] la tua risposta e aggiungi una spiegazione: perché questa soluzione potrebbe risolvere il problema?

fuxia fuxia
20 giu 2017 11:23:05

Questa risposta non risponde affatto alla domanda dell'OP - sembra completamente non correlata. Manca inoltre qualsiasi spiegazione su cosa dovrebbe fare o come usarla.

butlerblog butlerblog
11 nov 2018 01:54:46