has_shortcode() - WordPress 函数参考中文文档

返回介绍

has_shortcode()

发布于 2017-09-11 字数3200 浏览 1012 评论 0

has_shortcode( string $content,  string $tag )

Whether the passed content contains the specified shortcode


描述


参数

$content

(string)
(Required)
Content to search for shortcodes.

$tag

(string)
(Required)
Shortcode tag to check.


返回值

(bool) Whether the passed content contains the given shortcode.


源代码

File: wp-includes/shortcodes.php

function has_shortcode( $content, $tag ) {
	if ( false === strpos( $content, '[' ) ) {
		return false;
	}

	if ( shortcode_exists( $tag ) ) {
		preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER );
		if ( empty( $matches ) )
			return false;

		foreach ( $matches as $shortcode ) {
			if ( $tag === $shortcode[2] ) {
				return true;
			} elseif ( ! empty( $shortcode[5] ) && has_shortcode( $shortcode[5], $tag ) ) {
				return true;
			}
		}
	}
	return false;
}

更新日志

Version 描述
3.6.0 Introduced.

相关函数

Uses

  • wp-includes/shortcodes.php:
    shortcode_exists()
  • wp-includes/shortcodes.php:
    get_shortcode_regex()
  • wp-includes/shortcodes.php:
    has_shortcode()

Used By

  • wp-admin/includes/ajax-actions.php:
    wp_ajax_parse_embed()
  • wp-includes/shortcodes.php:
    has_shortcode()
  • wp-includes/media.php:
    get_post_galleries()

User Contributed Notes

  1. Skip to note content

    You must log in to vote on the helpfulness of this noteVote results for this note: 0You must log in to vote on the helpfulness of this note

    Contributed by Codex

    Simple Example
    Note: has_shortcode() can use a lot of re源代码s if scanning a lot of content.

    
    $content = 'This is some text, (perhaps pulled via $post->post_content). It has a  shortcode.';
    
    if ( has_shortcode( $content, 'gallery' ) ) {
    	// The content has a  short code, so this check returned true.
    }
    
  2. Enqueue some script when some post uses some shortcode.
    Note: has_shortcode() can use a lot of re源代码s if scanning a lot of content.

    
    /**
     * Enqueue the wpdocs-script if the wpdocs-shortcode is being used
     */
    function wpdocs_shortcode_scripts() {
    	global $post;
    	if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'wpdocs-shortcode') ) {
    		wp_enqueue_script( 'wpdocs-script');
    	}
    }
    add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts');
    

上一篇:has_post_thumbnail()

下一篇:has_site_icon()

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

目前还没有任何评论,快来抢沙发吧!