私は、私が望む拡張性で欲しいものを正確には見つけられなかったので、新しいプラグインを作成しようとしています。プラグインの目的は、簡単なショートコードを使用して、ブログの最新投稿を自動的に埋め込む画像スライダーを表示できるようにすることです。Wordpressプラグインでしたいことをエコーすることができません
私は基本的なプラグインファイルを用意して、ショートコードを実装してテストしました。私は昨日解決したsnafuを持っていましたが、解決策は新しい問題を強調しました。ここでは、コードです:
function slyd($category, $slydcount) {
global $post;
$tmp_post = $post; // Create $tmp_post to empty $post once Slyd is done with it
$args = array(
'category' => $category,
'numberposts' => $slydcount
);
$slydposts = get_posts($args);
foreach($slydposts as $post) : setup_postdata($post);
$post_title = get_the_title(); // Get the post's title
$post_content = get_the_content(); // Get the post's content - will write code to get excerpt later
$post_thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full'); // Get the post's featured image's src
$post_permalink = get_permalink(); // Get the post's permalink
echo '<h2><a href="' . $post_permalink . '">' . $post_title . '</a></h2>'
. '<p>' . $post_content . '</p>'
. '<p>' . $post_thumb . '</p>';
endforeach;
$post = $tmp_post; // Empty $post once Slyd is done with it
}
// Create the shortcode
function slyd_shortcode($atts) {
// $atts ::= array of attributes
// examples: [slyd]
// [slyd category='slide']
// [slyd slydcount='5']
// [slyd theme='default']
/* Retrieve attributes set by the shortcode and set defaults for
unregistered attributes. */
extract(shortcode_atts(array(
'category' => 'slyd', // Which category(s) to display posts from
'slydcount' => '5', // How many Slyds to display
'theme' => 'default' // Which Slyd theme to use
), $atts));
return "<p>category = {$category}, count = {$slydcount}</p>"
. slyd($category, $slydcount);
}
add_shortcode('slyd', 'slyd_shortcode');
問題がfunction slyd();
でforeach
ループです。私はもともとreturn
を使用していましたが、ここでecho
が結果を画面に表示します。それは最初の投稿を表示するために働いたが、もちろん、関数をエスケープするだろう。私はそれを繰り返してすべての投稿を表示する必要があります。
PHPのドキュメントを調べたところ、echo
またはの代わりにprint
を使用することができましたが、私にはecho
と同じ結果が得られました。何が起こっているのか、コードは2回実行されているようです。それは最初に必要な場所に配置され、ブラウザにエコーしてページのhead
のすぐ下に配置します。
return
,echo
、またはprint
の代替品が問題を解決するかどうかは私の疑問です。
ありがとうございます。
今、私はブログの最新の記事を取り込むためにプラグインを取得しようとしていますが、私はちょっとしたものにぶち当たっています。 The_title()とthe_permalink()を使用すると、コードの外に表示されます。さらに、The_content()はthe_permalink()とthe_title()で一度表示され、次にもう一度表示されます。
hereの動作を確認できます。
'echo'と' print'は同じ機能を持っていますが、 'return'は完全に異なっていますが、3つが交換可能だと聞いたことはありません...' return'を使うと、そこに戻って(何かまたは何もない)、そのルーチンから抜け出す。 'echo'や' print'を使うと処理を止めません。 –
本当にあなたの 'slyd'関数に' echo'が必要ですか?あなたがそれをコメントアウトするとどうなりますか? – seanbreeden
@DamienPirsy - 実際には 'return'はループを終了する点でのみ異なります。それ以外の場合は、3つすべてが値を返します。私はすでにそれを知っていて、私の機能が失敗している理由が「リターン」だったことを知っていました。私はそれを修正する方法を知りませんでした。 @seanbreeden - 'echo'(今は' return')は 'slyd'関数の中にある必要があります。それ以外の場合は、私が検索しようとしていた最新の投稿の代わりに、Wordpressのページの値を返します。 – trezy