Cómo crear un shortcode con contenido HTML y PHP

23 may 2017, 00:44:29
Vistas: 15.6K
Votos: 0

Quiero crear un shortcode para uno de los contenidos de mi tema.

El contenido de mi plantilla:

<section id="standing"  style="background-image: url('<?php echo (get_option('pixieclash-standings-background') && get_option('pixieclash-standings-background') != null) ? esc_url(get_option('pixieclash-standings-background')) : get_stylesheet_directory_uri() . '/images/standings-bg.jpg' ?>');">

<div class="container">
    <?php
        $headTxt = get_option('pixieclash-standings-section-heading-top');
        $bottomText = get_option('pixieclash-standings-section-heading-bottom');
    ?>

    <?php if(!empty($headTxt) || !empty($bottomText)): ?>
    <article class="head">
        <?php if(!empty($headTxt)): ?>
            <h4><?php echo esc_attr($headTxt); ?></h4>
        <?php endif; ?>

        <?php if(!empty($bottomText)): ?>
            <h3><?php echo esc_attr($bottomText); ?></h3>
        <?php endif; ?>
    </article>
    <?php endif; ?>

    <?php
        $groups = pixieclash_standings_groups();

        if(!empty($groups)):
            $i = 1;
            $onlyOne = count($groups) > 1 ? '' : 'onlyOne';
            foreach($groups as $group):
                $competitors = pixieclash_standings($group['id']);
    ?>
    <article class="table <?php echo ($i % 2 != 0) ? 'first' : 'second' ?> <?php echo $onlyOne ?>">
        <h5 class="group-name"><?php esc_html_e('Grupo', 'pixieclash') ?> <?php echo esc_attr($group['name']) ?></h5>

        <table class="table-body">
            <thead>
            <tr>
                <th><?php esc_html_e('Competidor', 'pixieclash') ?></th>
                <th rel="match<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('M', 'pixieclash') ?></th>
                <th rel="win<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('G', 'pixieclash') ?></th>
                <th rel="till<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('E', 'pixieclash') ?></th>
                <th rel="loss<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('P', 'pixieclash') ?></th>
                <th rel="point<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('Pts', 'pixieclash') ?></th>
            </tr>
            </thead>
            <tbody>
            <?php if(!empty($competitors)): foreach($competitors as $competitor): ?>
            <tr>
                <td>
                    <figure>
                        <img src="<?php echo esc_url($competitor['logo']) ?>" alt="<?php echo esc_attr($competitor['name']) ?>" title="Logo de <?php echo esc_attr($competitor['name']) ?>">
                    </figure>
                    <?php echo esc_attr($competitor['name']) ?>
                </td>
                <td rel="match<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['played']) ?></td>
                <td rel="win<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['wins']) ?></td>
                <td rel="till<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['till']) ?></td>
                <td rel="loss<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['losses']) ?></td>
                <td rel="point<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['points']) ?></td>
            </tr>
            <?php endforeach; else: ?>
            <tr>
                <td colspan="6"><?php esc_html_e('No hay competidores', 'pixieclash') ?></td>
            </tr>
            <?php endif; ?>
            </tbody>
        </table>

    </article>

    <?php $i ++; endforeach; endif; ?>
</div>
</section>

Intenté crear el shortcode usando add_shortcode('table', 'nombre de esta función'); pero no funcionó para mí.

¿Cómo puedo hacer esto?

2
Comentarios

¿Qué parte estás intentando reemplazar con un Shortcode? Un Shortcode debe return una cadena que contenga todo el contenido que deseas reemplazar en el marcador de posición del Shortcode.

Milo Milo
23 may 2017 20:12:33

Quiero crear un shortcode para esta sección <section> ..... </section>

Nienormalny_ Nienormalny_
23 may 2017 22:39:34
Todas las respuestas a la pregunta 2
5

Para crear un shortcode a partir de tus funciones, necesitas usar el siguiente código:

function my_shortcode_function(){ 
    if (get_option('pixieclash-standings-background') && get_option('pixieclash-standings-background') != null) {
        $background = esc_url(get_option('pixieclash-standings-background')) 
    } else {
        $background = get_stylesheet_directory_uri() . '/images/standings-bg.jpg';
    }
    $headTxt = get_option('pixieclash-standings-section-heading-top');
    $bottomText = get_option('pixieclash-standings-section-heading-bottom'); 
    if(!empty($headTxt)){ 
        $text_header = '<h4>'. esc_attr($headTxt);.'</h4>';
    } else {
        $text_header = '';
    }
    if(!empty($bottomText)) { 
        $text_footer = '<h3>'.esc_attr($bottomText); .'</h3>';
    } else {
        $text_footer ='';
    }
    if(!empty($headTxt) || !empty($bottomText)){ 
        $container = '<article class="head">'. $text_header . $text_footer.'</article>';
    } 
    $groups = pixieclash_standings_groups();
    if(!empty($groups)) {
        $i = 1;
        $onlyOne = (count($groups) > 1 ) ? '' : 'onlyOne';
        $competitors ='';
        foreach($groups as $group){
            $competitors .= pixieclash_standings($group['id']);
        }
    }
    $data = '
        <section id="standing" style="background-image: url("'.$background.'");">
            <div class="container">'.$container.$competitors'</div>
        </section>';
    return $data;
}
add_action('my-table-shortcode','pixieclash_standings_two');

Asegúrate de elegir un nombre único para tu shortcode.

Ahora usa lo siguiente para mostrar tu shortcode:

[my-table-shortcode]

O usa do_shortcode() en un archivo PHP:

echo do_shortcode('[my-table-shortcode]');

Nota: Por favor ten en cuenta que, como no tengo acceso a tus funciones, no pude validar exactamente el código. Puedes revisar tu registro de errores si el código no funciona como se esperaba.

ACTUALIZACIÓN

Hay una solución muy sencilla que creo que funciona mejor en tu caso, y es usar ob_start(). Esto registrará toda la salida de tu contenido y la almacenará en un valor para devolverlo más tarde. Echa un vistazo a esto:

function my_content_shortcode(){ 
    ob_start();?>
    <section id="standing"  style="background-image: url('<?php echo (get_option('pixieclash-standings-background') && get_option('pixieclash-standings-background') != null) ? esc_url(get_option('pixieclash-standings-background')) : get_stylesheet_directory_uri() . '/images/standings-bg.jpg' ?>');">

    <div class="container">
        <?php
            $headTxt = get_option('pixieclash-standings-section-heading-top');
            $bottomText = get_option('pixieclash-standings-section-heading-bottom');
        ?>

        <?php if(!empty($headTxt) || !empty($bottomText)): ?>
        <article class="head">
            <?php if(!empty($headTxt)): ?>
                <h4><?php echo esc_attr($headTxt); ?></h4>
            <?php endif; ?>

            <?php if(!empty($bottomText)): ?>
                <h3><?php echo esc_attr($bottomText); ?></h3>
            <?php endif; ?>
        </article>
        <?php endif; ?>

        <?php
            $groups = pixieclash_standings_groups();

            if(!empty($groups)):
                $i = 1;
                $onlyOne = count($groups) > 1 ? '' : 'onlyOne';
                foreach($groups as $group):
                    $competitors = pixieclash_standings($group['id']);
        ?>
        <article class="table <?php echo ($i % 2 != 0) ? 'first' : 'second' ?> <?php echo $onlyOne ?>">
            <h5 class="group-name"><?php esc_html_e('Group', 'pixieclash') ?> <?php echo esc_attr($group['name']) ?></h5>

            <table class="table-body">
                <thead>
                <tr>
                    <th><?php esc_html_e('Competitor', 'pixieclash') ?></th>
                    <th rel="match<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('M', 'pixieclash') ?></th>
                    <th rel="win<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('W', 'pixieclash') ?></th>
                    <th rel="till<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('T', 'pixieclash') ?></th>
                    <th rel="loss<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('L', 'pixieclash') ?></th>
                    <th rel="point<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('P', 'pixieclash') ?></th>
                </tr>
                </thead>
                <tbody>
                <?php if(!empty($competitors)): foreach($competitors as $competitor): ?>
                <tr>
                    <td>
                        <figure>
                            <img src="<?php echo esc_url($competitor['logo']) ?>" alt="<?php echo esc_attr($competitor['name']) ?>">
                        </figure>
                        <?php echo esc_attr($competitor['name']) ?>
                    </td>
                    <td rel="match<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['played']) ?></td>
                    <td rel="win<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['wins']) ?></td>
                    <td rel="till<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['till']) ?></td>
                    <td rel="loss<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['losses']) ?></td>
                    <td rel="point<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['points']) ?></td>
                </tr>
                <?php endforeach; else: ?>
                <tr>
                    <td colspan="6"><?php esc_html_e('No competitors', 'pixieclash') ?></td>
                </tr>
                <?php endif; ?>
                </tbody>
            </table>

        </article>

        <?php $i ++; endforeach; endif; ?>
    </div>
    </section><?php
    $content = ob_get_contents();
    ob_end_clean();
    return $content;
}
add_action('my-table-shortcode','my_content_shortcode');

Ahora, usando [my-table-shortcode] en un widget de texto o contenido, se comportará exactamente como tu sección, igual que usar echo do_shortcode('[my-table-shortcode]'); en un archivo php.

23 may 2017 02:03:27
Comentarios

@Nienormalny_ He añadido otra solución fácil para ti. Simplemente copia la respuesta UPDATE en tu archivo functions.php y usa el shortcode. Y si funcionó, lo único que puedes hacer es aceptar y/o votar a favor de la respuesta a cambio :)

Johansson Johansson
24 may 2017 00:33:00

Así que cuando pongo este código dentro de functions.php me muestra una página en blanco. Cuando lo pongo debajo del código <section> original con <?php...?> entonces me muestra el nombre del shortcode con corchetes.

Nienormalny_ Nienormalny_
24 may 2017 09:52:51

@Nienormalny_ Podría haber un error de sintaxis o un problema con las etiquetas php <?php y ?>. Por favor, revisa tu registro de errores para obtener más información o activa WP_DEBUG en tu instalación.

Johansson Johansson
24 may 2017 21:12:07

ok, lo revisaré

Nienormalny_ Nienormalny_
25 may 2017 14:27:14

Lo probé pero el registro de depuración no muestra nada y no tiene errores. Sigue mostrándome el shortcode. Si quieres, puedo darte el enlace de codeanywhere pero solo por mensaje privado. Así podrás ver qué está pasando allí.

Nienormalny_ Nienormalny_
25 may 2017 19:43:05
0

// Shortcode para generar una barra lateral dinámica function sidebar_detail_payedpost( $shortcode_attr, $shortcode_content ) {

      // echo "sidebar";
         $current_cat_id = get_queried_object_id();
         $count_post=get_term($current_cat_id);
         $city = isset($_GET['locationID']) ? base64_decode($_GET['locationID']) : $_SESSION['prefer_city'];
         $args = array(
              'post_type' => 'classified',
              'tax_query' => array( 
                                 array(
                                    'taxonomy' => 'classified_location',
                                    'field'    => 'id',
                                    'terms'    => array($city),
                                    'operator' => 'IN',
                                  )
                 ),
              );
            $result = new WP_Query($args);
            // echo $result->found_posts;
           //  print_r($result);
          //   echo "</pre>";
         if ( $result-> have_posts() ){

         while ( $result->have_posts() ){
             $result->the_post();
            ?>
          <!-- <div class="container post_box"> -->
           <div class="container">

                <?php 
                    $data=get_the_post_thumbnail();
                 ?>
                 <div class="SidebarPost">
                <a href="<?php echo get_permalink();  ?>"  data-img='<?php echo ($data); ?>' class="postimage_sidebar" ><?php echo ($data); ?>
                </a> 
                 <h5><a href="<?php echo get_permalink();  ?>"><?php the_title(); ?></a></h5>
                </div>   
            </div>


        <?php    
         }
    } 

}
    add_shortcode('DisplayPayablePost', 'sidebar_detail_payedpost');

Este código muestra publicaciones pagadas en la barra lateral y funciona correctamente para mí. Puedes agregar HTML y PHP de esta manera.

Es un código completamente probado y correcto, solo espero que funcione para ti.

21 dic 2018 06:20:29