Khan Bangladesch
Ich habe diesen Code, um alle Beiträge der Kategorie und Miniaturansicht für den ersten Beitrag von ihnen anzuzeigen.
<?php $recent = new WP_Query(); ?>
<?php $recent->query( 'cat=1&showposts=5' ); ?>
<?php $is_first_post = true; ?>
<?php while( $recent->have_posts() ) : $recent->the_post(); ?>
<ul>
<li>
<?php
if ( $is_first_post && has_post_thumbnail() ) {
the_post_thumbnail();
$is_first_post = false;
}
?>
<a href="<?php%20the_permalink();%20?>">
<?php the_title(); ?>
</a>
</li>
</ul>
<?php endwhile; ?>
Ich möchte diesen Code mit einem Shortcode ausführen, der Kategorie und Beitragsnummer verwendet.
Wie erstelle ich einen solchen Shortcode in WordPress?
Prashant Suthar
Fügen Sie diesen Code in function.php hinzu und das ist Ihr Shortcode “[my_form_shortcode cat=”1″ showposts=”5″]”.
function my_form_shortcode($atts) {
ob_start();
$atts = shortcode_atts(
array(
'cat' => '1',
'showposts' => '5',
), $atts, 'my_form_shortcode' );
//YOUR CODE START
$recent = new WP_Query();
$query = "cat=".$atts['cat']."&showposts=".$atts['showposts'];
$recent->query( $query );
$is_first_post = true;
while( $recent->have_posts() ) : $recent->the_post(); ?>
<ul>
<li>
<?php
if ( $is_first_post && has_post_thumbnail() ) {
the_post_thumbnail();
$is_first_post = false;
}
?>
<a href="https://stackoverflow.com/questions/41311453/<?php%20the_permalink();%20?>">
<?php the_title(); ?>
</a>
</li>
</ul>
<?php endwhile;
//YOUR CODE END
return ob_get_clean();
}
add_shortcode( 'my_form_shortcode', 'my_form_shortcode' );
Ein Shortcode ist eine PHP-Funktion. Sie brauchen eine Funktion, die alle Ihre Argumente akzeptiert. Zum Beispiel-
function get_posts($atts) {
extract( shortcode_atts( array(
'cat_id' => 'cat_id',
'num_posts' => 'num_posts'
), $atts ) );
$loop = array(
'cat' => $cat_id,
'posts_per_page' => $num_posts
);
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
// YOUR CODE HERE
endwhile;
endif;
}
add_shortcode( 'getposts', 'get_posts' );
Ihr Shortcode sieht so aus:
getposts[cat_id="1", num_posts="5"]
Dieser Code wurde nicht getestet, aber das ist ziemlich genau, wie Sie es tun
Zunächst einmal Sie gerade Ändern Sie Ihren Funktionsnamen.
In WordPress ist get_posts () eine Funktion, sodass Sie Ihre benutzerdefinierte Funktion nicht mit demselben Namen erstellt haben.
https://developer.wordpress.org/reference/functions/get_posts/
function ShowProduct()
{
$data = "Welcome to wordpress shortcode.";
return $data;
}
add_shortcode('products', 'ShowProduct');
http://www.codexwp.com/issues/how-to-create-shortcode-in-wordpress/
8770500cookie-checkWie erstelle ich einen WordPress-Shortcode aus vorhandenem Code?yes