行业资讯
要实现添加代码首先要认识wordpress添加事件的钩子函数add_action($event,$func)。字面意思添加一个操作,一个行动。
$event参数是钩子事件,一般是执行的时机。例如:after_setup_theme主题启动执行,publish_post发布文章执行。$func自定义的函数或者类的方法。
今天我们讲解wp_head加载前端页面头部时执行(或者说往头部添加内容,或者去除内容),wp_footer底部添加内容。
add_action( 'wp_head', [$this,'baiduseo_mainpage'],1 );
public function baiduseo_mainpage(){ $baiduseo_zz = get_option('baiduseo_zz'); if(isset($baiduseo_zz['toutiao_key']) && $baiduseo_zz['toutiao_key'] ){ echo ''; } if(is_home() || is_front_page()){ $seo = get_option('seo_init'); if($seo){ if(isset($seo['keywords']) && $seo['keywords']){ echo ''."\n\r"; } if(isset($seo['description']) && $seo['description']){ echo ''."\n\r"; } } }elseif(is_category()){ $cate = get_the_category(); if(isset($cate[0]->cat_ID)){ $seo = get_option('baiduseo_cate_'.$cate[0]->cat_ID); if(!empty($seo)){ if(isset($seo['keywords']) && $seo['keywords']){ echo sprintf(''."\n",esc_attr($seo['keywords'])); } if(isset($seo['description']) && $seo['description']){ echo sprintf(''."\n",esc_attr($seo['description'])); } } } }elseif(is_single()){ add_action( 'the_content', [$this,'BaiduSEO_addlink']); } }
上面的代码是在头部head标签中添加头条推送的js,设置页面的keywords、description,以及加载头部时,更改文章内页的内容。wp_footer钩子的用法与wp_head相似,不过是body标签的底部添加。