首页 视频课程 主题开发课程第04章、常用函数 WordPress主题插件开发中常用基本函数

WordPress主题插件开发中常用基本函数

2023-06-11 / 384阅

  1. wp_head()
    用于在网页头部调用样式表、脚本等内容。

示例代码:

<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><?php wp_title(); ?></title>
    <?php wp_head(); ?>
</head> 
  1. wp_footer()
    用于在网页底部调用需要的脚本等内容。

示例代码:

<body>
    <!-- 页面内容 -->
    <?php wp_footer(); ?>
</body> 
  1. get_template_directory_uri()
    获取主题的绝对路径。

示例代码:

<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/style.css"> 
  1. the_post_thumbnail()
    在文章中调用文章特色图像。

示例代码:

<?php if(has_post_thumbnail()): ?>
    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
        <?php the_post_thumbnail('large', array('class' => 'thumbnail')); ?>
    </a>
<?php endif; ?> 
  1. register_nav_menus()
    用于注册主题所支持的导航菜单。

示例代码:

function theme_nav_menus() {
    register_nav_menus( array(
        'primary' => __( 'Primary Menu', 'theme' ),
        'footer' => __( 'Footer Menu', 'theme' )
    ) );
}
add_action( 'after_setup_theme', 'theme_nav_menus' ); 
  1. dynamic_sidebar()
    在侧边栏中调用小工具。

示例代码:

<aside>
    <?php if( is_active_sidebar( 'sidebar' ) ) : ?>
        <?php dynamic_sidebar( 'sidebar' ); ?>
    <?php endif; ?>
</aside> 
  1. get_template_part()
    调用模板的部分文件。

示例代码:

<?php get_template_part( 'content', 'single' ); ?> 
  1. comments_template()
    调用文章评论模板。

示例代码:

<?php if ( comments_open() || get_comments_number() ) :
    comments_template();
endif; ?> 
  1. esc_attr__()
    用于转义输出内容,避免XSS攻击。

示例代码:

<div class="<?php echo esc_attr__( 'my-class' ); ?>">
    <!-- 内容 -->
</div> 
  1. wp_enqueue_script()
    加载自定义脚本文件。

示例代码:

function theme_scripts() {
    wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'theme_scripts' ); 

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录