Support » Plugins » Bild aus ID erzeugen (Shortcode)

  • Hallo in die Runde.

    Ich benutze dieses Plugin, um eigene Shortcodes zu benutzen:
    https://wordpress.org/plugins/minimal-shortcode-ui/

    Genauer gesagt bin ich auf der Suche nach einer Funktion im WYSIWYG Editor einfach ein Bild auszuwählen, eine Bildunterschrift anzugeben und am Ende soll mir die Funktion einen HTML Code ausspucken, in dem die Bild- & Unterschriftvariablen enthalten sind.

    Das Plugin funktioniert insgesamt auch gut, dies ist der Code der als Beispiel gegeben wird.

    <?php
    /**
     * Example of a custom shortcode, include this file
     * to see it in action.
     */
    
    if(!class_exists('\Sui\Shortcodes')) {
    	throw new Exception('');
    }
    
    use \Sui\Shortcodes as Shortcodes;
    use \Sui\Shortcode as Shortcode;
    
    // this will register the shortcode below into the factory
    $result = Shortcodes::register('ExampleShortcodeTest');
    
    if(!$result) {
    	throw new Exception('Failed to register this example shortcode somehow..');
    }
    
    /**
     * This is an example shortcode. The tag name of the shortcode
     * may be determined by the classname.
     *
     * For more information see the source code of \Sui\Shortcode
     * at /lib/abstract/shortcode.php
     */
    class ExampleShortcodeTest extends Shortcode {
    
    	/**
    	 * Will be prepended to the shortcode
    	 * its tag name followed by an underscore.
    	 *
    	 * @var string
    	 */
    	protected $_tagNamePrefix = 'sui';
    
    	/**
    	 * The shortcode's description.
    	 *
    	 * @var string
    	 */
    	protected $_description = 'Shortcode description';
    
    	/**
    	 * Indicates whether this is an enclosing shortcode.
    	 *
    	 * @var boolean
    	 */
    	protected $_enclosed = true;
    
    	/**
    	 * Defines the shortcode attributes and default values.
    	 *
    	 * @var array
    	 */
    	protected $_attributes = array(
    		'name' => '',
    		'image_id' => '',
    		'test' => false,
    		'choose' => ''
    	);
    
    	/**
    	 * Class constructor
    	 *
    	 * Define the schema for your shortcode attributes here.
    	 * Or set a translated description for your shortcode here.
    	 */
    	public function __construct() {
    		parent::__construct();
    
    		//$this->_description = __('translated...', '
    
    		$this->_setSchemaAttribute('name', '', 'text');
    		$this->_setSchemaAttribute('image_id', '', 'image');
    		$this->_setSchemaAttribute('test', '', 'checkbox');
    		$this->_setSchemaAttribute('choose', '', 'select', array(
    			'options' => array(
    				'' => 'Choose...',
    				'1' => 'Something',
    				'2' => 'Test'
    			)
    		));
    	}
    
    	/**
    	 * Renders this shortcode.
    	 *
    	 * @param array $atts
    	 * @param string|null $content
    	 * @return string
    	 */
    	public function render($atts, $content = null) {
    		$atts = shortcode_atts($this->_attributes, $atts);
    
    		if(!$content) {
    			$content = '';
    		}
    
    		?>
    		<div>
    			<h1><?php echo $atts['name'] ?></h1>
    
    			<?php if($atts['image_id']): ?>
    			<img src="<?php wp_get_attachment_image_src($atts['image_id'], 'full') ?>" alt="" />
    			<?php endif; ?>
    
    			<p><?php echo $atts['test'] ? 'enabled' : 'disabled' ?></p>
    		</div>
    		<?php
    
    		// if enclosement allow nested shortcodes
    		if($this->_enclosed) {
    			$content = do_shortcode($content);
    		}
    
    		return $content;
    	}
    
    }
    ?>

    Das einzige was nicht funktioniert, ist das Bild zu generieren.

    <?php if($atts['image_id']): ?>
    			<img src="<?php wp_get_attachment_image_src($atts['image_id'], 'full') ?>" alt="" />
    			<?php endif; ?>

    ..zeigt nichts an.

    <?php echo $atts['image_id'] ?>

    ..gibt mir allerdings die Image ID aus, also genau das was es soll. Allerdings eben nicht in Kombination mit wp_get_attachment_image_src. Gibt es eine andere Möglichkeit aus einer Bild ID die URL zu generieren? Oder kann jemand erkennen, warum es nicht funktioniert.

    Habe natürlich schon beim Plugin Autor nachgefragt, aber keine Antwort bekommen.

    Vielen Dank!

Ansicht von 7 Antworten - 1 bis 7 (von insgesamt 7)
  • Ich kenne das Plugin nicht und wenn es Dir um Support zu diesem Plugin geht, bist Du vermutlich beim Support auf der Plugin-Seite besser aufgehoben. Ich würde einen „Shortcode, der ein Bild und einen Begleittext ausgibt“ so umsetzen:

    <?php
    add_shortcode( 'bild_mit_text', 'bild_mit_text' );
    
    function bild_mit_text( $atts ) {
    	//Shortcode Attributes
    	$atts = shortcode_atts( array(
    		'ID'   => 0,
    		'size' => 'large',
    		'text' => 'Hello Dolly!'
    	), $atts );
    
    	//check whether a correct size was provided
    	$sizes = array( 'thumbnail', 'medium', 'large', 'full' );
    	if(!in_array( $atts[size], $sizes )) {
    		$atts[size] = 'large';
    	}
    
    	// Attributes for the image tag
    	$attr = array(
    		'class' => 'attachment-'.$atts[size],
    		);
    
    	//check whether an ID was provided
    	if(!empty($atts[ID])) {
                   //Output des Plugins
    		$out = '<div class="image_with_text">';
    		$out .= get_the_post_thumbnail( $atts[ID], $atts[size], $attr );
    		$out .= '<div class="caption">'. esc_html($atts[text]) . '</div>';
        $out .= '</div><!-- .image_with_text -->';
    	}	else {
    		$out = 'Bitte Bildnr. angeben.';
    	}
    
    	return $out;
    }

    Im Editor gibts Du dann den Shortcode ein, z.B.

    [bild_mit_text id="27" size="medium" text="Das hat mir gut gefallen"]

    Thread-Starter raoul_k

    (@raoul_k)

    Danke für den Code.

    Der Vorteil am Plugin ist, dass es direkt im WYSIWYG Editor einen einfach weg hinzufügt um die Image ID zu ermitteln. Da ich den Blog nicht alleine benutze, bietet dies für andere Autoren eine leichteren Weg.

    Mit folgender Codeänderung habe ich es geschafft, die Bilder per ID einzufügen

    if(!class_exists('\Sui\Shortcodes')) {
    	throw new Exception('');
    }
    
    use \Sui\Shortcodes as Shortcodes;
    use \Sui\Shortcode as Shortcode;
    
    // this will register the shortcode below into the factory
    $result = Shortcodes::register('HeroImage');
    
    if(!$result) {
    	throw new Exception('Failed to register this example shortcode somehow..');
    }
    
    /**
     * This is an example shortcode. The tag name of the shortcode
     * may be determined by the classname.
     *
     * For more information see the source code of \Sui\Shortcode
     * at /lib/abstract/shortcode.php
     */
    class HeroImage extends Shortcode {
    
    	/**
    	 * Will be prepended to the shortcode
    	 * its tag name followed by an underscore.
    	 *
    	 * @var string
    	 */
    	protected $_tagNamePrefix = 'img';
    
    	/**
    	 * The shortcode's description.
    	 *
    	 * @var string
    	 */
    	protected $_description = 'Dieses Bild wird über die gesamte Breite angezeigt. Wähle das Bild aus und gib eine optionale Bildunterschrift ein. Der Bereich Content muss frei bleiben.';
    
    	/**
    	 * Indicates whether this is an enclosing shortcode.
    	 *
    	 * @var boolean
    	 */
    	protected $_enclosed = true;
    
    	/**
    	 * Defines the shortcode attributes and default values.
    	 *
    	 * @var array
    	 */
    	protected $_attributes = array(
    		'image_id' => '',
    		'bildunterschrift' => '',
    	);
    
    	/**
    	 * Class constructor
    	 *
    	 * Define the schema for your shortcode attributes here.
    	 * Or set a translated description for your shortcode here.
    	 */
    	public function __construct() {
    		parent::__construct();
    
    		//$this->_description = __('translated...', '
    
    		$this->_setSchemaAttribute('image_id', '', 'image');
    		$this->_setSchemaAttribute('bildunterschrift', '', 'text');
    	}
    
    	/**
    	 * Renders this shortcode.
    	 *
    	 * @param array $atts
    	 * @param string|null $content
    	 * @return string
    	 */
    	public function render($atts, $content = null) {
    		$atts = shortcode_atts($this->_attributes, $atts);
    
    		if(!$content) {
    			$content = '';
    		}
    
    		?>
    
    		<?php
        $image_id = $atts['image_id']; // attachment ID
        $image_attributes = wp_get_attachment_image_src( $image_id, 'large'); // returns an array
    ?>
    
    		<div class="fullwidtharticleimg photoswipe_gallery gallery-columns-3 gallery-size-thumbnail photoswipe_showme" style="position: relative;" data-pswp-uid="1">
    			<figure class="msnry_item" style="position: absolute; left: 0px; top: 0px;">
    				<a href="<?php echo $image_attributes[0]; ?>" data-size="1280x853">
    					<img src="<?php echo $image_attributes[0]; ?>" alt="" />
    				</a>
    				<figcaption class="photoswipe-gallery-caption"><?php echo $atts['bildunterschrift'] ?></figcaption>
    			</figure>
    		</div>
    
    		<?php
    
    		// if enclosement allow nested shortcodes
    		if($this->_enclosed) {
    			$content = do_shortcode($content);
    		}
    
    		return $content;
    	}
    
    }

    Nun tritt allerdings ein neues Problem auf: Der ausgegebene Code erscheint nicht an der Stelle wo der Shortcode eingegeben wird, sondern immer direkt oben auf der Seite. Nach kurzem Googlen stellt sich heraus, dass dies kein seltener Fall bei Shortcode Funktionen ist. Das Problem scheint zu sein, dass ich in der functions.php per echo ausgebe und dies eher mit return tun sollte, soweit ich das verstanden habe. Ein Lösungsansatz sei dieser:

    ob_start();
    my_func_plugin();
    $output_string=ob_get_contents();;
    ob_end_clean();
    
    return $output_string;

    Ich kriege es leider partout nicht hin, dies in meinen Code einzuarbeiten… Wäre für Hilfe unglaublich dankbar.

    Heute Morgen schweißgebadet aufgewacht, wieso ich in der Funktion get_the_post_thumbnail() verwendet habe. Aber wie ich sehe, ist das eh unkritisch, weil Du dir anders weitergeholfen hast. Schön.

    Wird bei Verwendung eines Shortcodes der Text oberhalb des eigentlichen Inhalts ausgegeben, liegt das meistens daran, dass in der Funktion, die der Shortcode aufruft, Inhalte mit echo ausgegeben wurden, statt mit return.

    Thread-Starter raoul_k

    (@raoul_k)

    Haha 🙂 Oje, ich hoffe du hast dich erstmal von dem Schock erholt!

    Wenn ich alle echos durch return ersetze funktioniert es leider nicht, muss ich das noch anderweitig anpassen?

    Du gibst aber, wenn ich es recht verstehe, den Code

    <div class="fullwidtharticleimg photoswipe_gallery …

    direkt als HTML aus, statt ihn einer Variablen zuzuweisen und diese dann mit return zu übergeben.

    Thread-Starter raoul_k

    (@raoul_k)

    Ah, das war der entscheidende Hinweis. Vielen Dank!

    Habe es jetzt so zum Laufen gebracht:

    <?php
        $image_id = $atts['image_id']; // attachment ID
        $image_attributes = wp_get_attachment_image_src( $image_id, 'large'); // returns an array
        $out = '<div class="fullwidtharticleimg photoswipe_gallery gallery-columns-3 gallery-size-thumbnail photoswipe_showme" style="position: relative;" data-pswp-uid="1"><figure class="msnry_item" style="position: absolute; left: 0px; top: 0px;"><a href="';
    	$out .= $image_attributes[0];
    	$out .= '" data-size="1280x853"><img src="';
    	$out .= $image_attributes[0];
    	$out .= '" alt="" /></a><figcaption class="photoswipe-gallery-caption">';
    	$out .= $atts["bildunterschrift"];
    	$out .= '</figcaption></figure></div>';
    	return $out; ?>
    Thread-Starter raoul_k

    (@raoul_k)

    …zu früh gefreut.

    Wenn ich den Code einsetze, lädt WordPress die Seite nicht. Dies ist der komplette Code mit dem ich arbeite

    <?php
    /**
     * Shortcode for Big Hero Images
     *
     */
    if(!class_exists('\Sui\Shortcodes')) {
    	throw new Exception('');
    }
    
    use \Sui\Shortcodes as Shortcodes;
    use \Sui\Shortcode as Shortcode;
    
    // this will register the shortcode below into the factory
    $result = Shortcodes::register('HeroImage');
    
    if(!$result) {
    	throw new Exception('Failed to register this example shortcode somehow..');
    }
    
    /**
     * This is an example shortcode. The tag name of the shortcode
     * may be determined by the classname.
     *
     * For more information see the source code of \Sui\Shortcode
     * at /lib/abstract/shortcode.php
     */
    class HeroImage extends Shortcode {
    
    	/**
    	 * Will be prepended to the shortcode
    	 * its tag name followed by an underscore.
    	 *
    	 * @var string
    	 */
    	protected $_tagNamePrefix = 'img';
    
    	/**
    	 * The shortcode's description.
    	 *
    	 * @var string
    	 */
    	protected $_description = 'Dieses Bild wird über die gesamte Breite angezeigt. Wähle das Bild aus und gib eine optionale Bildunterschrift ein. Der Bereich Content muss frei bleiben.';
    
    	/**
    	 * Indicates whether this is an enclosing shortcode.
    	 *
    	 * @var boolean
    	 */
    	protected $_enclosed = true;
    
    	/**
    	 * Defines the shortcode attributes and default values.
    	 *
    	 * @var array
    	 */
    	protected $_attributes = array(
    		'image_id' => '',
    		'bildunterschrift' => '',
    	);
    
    	/**
    	 * Class constructor
    	 *
    	 * Define the schema for your shortcode attributes here.
    	 * Or set a translated description for your shortcode here.
    	 */
    	public function __construct() {
    		parent::__construct();
    
    		//$this->_description = __('translated...', '
    
    		$this->_setSchemaAttribute('image_id', '', 'image');
    		$this->_setSchemaAttribute('bildunterschrift', '', 'text');
    	}
    
    	/**
    	 * Renders this shortcode.
    	 *
    	 * @param array $atts
    	 * @param string|null $content
    	 * @return string
    	 */
    	public function render($atts, $content = null) {
    		$atts = shortcode_atts($this->_attributes, $atts);
    
    		if(!$content) {
    			$content = '';
    		}
    
    		?>
    
    		<?php
        $image_id = $atts['image_id']; // attachment ID
        $image_attributes = wp_get_attachment_image_src( $image_id, 'large'); // returns an array
        $out = '<div class="fullwidtharticleimg photoswipe_gallery gallery-columns-3 gallery-size-thumbnail photoswipe_showme" style="position: relative;" data-pswp-uid="1"><figure class="msnry_item" style="position: absolute; left: 0px; top: 0px; padding-bottom: 10px !important;"><a href="';
    	$out .= $image_attributes[0];
    	$out .= '" data-size="1280x853"><img src="';
    	$out .= $image_attributes[0];
    	$out .= '" alt="" /></a><figcaption style="display: none; height: 0;" class="photoswipe-gallery-caption">';
    	$out .= $atts["bildunterschrift"];
    	$out .= '</figcaption></figure></div><div style="color: #696f7a; font-size: 13px; padding-bottom: 50px !important;">';
    	$out .= $atts["bildunterschrift"];
    	$out .= '</div>';
    
    	return $out; ?>

    …ich kann keinen direkten Fehler finden. Allerdings bin ich mir auch nicht sicher, an welcher Stelle dieser Code am besten eingesetzt werden sollte… Er wird nur in Artikeln benutzt, daher single.php? Oder doch in der functions.php?

Ansicht von 7 Antworten - 1 bis 7 (von insgesamt 7)
  • Das Thema „Bild aus ID erzeugen (Shortcode)“ ist für neue Antworten geschlossen.