Answer the question
In order to leave comments, you need to log in
Is there another way to write the code in the shortcode?
I created a shortcode on the site and added it via wpbackery page builder to the main page. The question is, is it possible to somehow more conveniently and correctly write HTML and PHP code in functions? I also heard that it is better to use return instead of echo in the shortcode, but then the shortcode is not displayed in this way at all, and because I'm not strong in php, can you tell me how to write it correctly?
function tags() {
$tags = get_field_object('метки_и_ссылки', get_queried_object());
echo "<div class='theme-container tag-container'><ul class='tag-links'>";
foreach( $tags['value'] as $tag['value'] ) {
echo "<a class='tag-link' href='";
echo $tag['value'] -> description;
echo "'>";
echo $tag['value'] -> name;
echo "</a>";
}
echo "</ul></div>";
}
add_shortcode('tagsAndLinks', 'tags');
Answer the question
In order to leave comments, you need to log in
Note that the function called by the shortcode should never produce an output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output will directly lead to unexpected results. This is similar to the way filter functions should behave, in that they should not produce unexpected side effects from the call since you cannot control when and where they are called from.
Made it neater and I will give some tips
<ul>
Only elements can be nested in a tag<li>
// Использование [tag-list field="метки_и_ссылки" class="tag-list"]
add_shortcode( 'tag-list', 'get_custom_tag_list' );
function get_custom_tag_list( $atts ) {
// белый список параметров и значения по умолчанию для шорткода
$atts = shortcode_atts( array(
'class' => 'list',
'field' => '',
'post_id' => 0
), $atts );
$output = '';
$post = get_post( $atts['post_id'] );
if ( isset( $post->ID ) && !empty($atts['field']) ) {
$tags = get_field_object( $atts['field'], $post->ID );
if ( $tags ) {
$output .= '<ul class="' . $atts['class'] . '">';
foreach ( $tags['value'] as $key => $value ) {
$output .= '<li class="' . $atts['class'] . '__item" >';
$output .= '<a class="' . $atts['class'] . '__link" href="' . $value->description . '" rel="tag">' . $value->name . '</a>';
$output .= '</li>';
}
$output .= '</ul>';
}
}
return apply_filters( 'get_custom_tag_list', $output );
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question