标签: WordPress函数

  • WordPress 判断在后台,不在ajax中

    WordPress 判断在后台,不在ajax中

    在日常WordPress插件开发中,我们会在内容中增加删除一些内容,但是有些修改可能会导致数据无法保存,一般会使用 is_admin() 判断 WordPress 条件判断标签及用法大全,但是保存时会有 /wp-json/wp/v2/posts 报错,所以我们这里记录一下方法

    // Is admin, but not doing ajax
    if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
        require_once('admin/functions_admin.php'); 
    }
    // Is doing AJAX 
    else if ( is_admin() && ( defined( 'DOING_AJAX' ) || DOING_AJAX ) ) {
        require_once('functions_ajax.php'); 
    }
    // Front-end functions
    else { 
        require_once('public.php'); 
    }
  • WordPress 插件开发 自定义文章类型 置顶

    WordPress 插件开发 自定义文章类型 置顶

    在WordPress中,原生是自带文章“在博客中置顶”这个功能选项的,但是我们在插件开发时如果自定义了文章的类型,那么这个按钮就无法显示,需要通过代码设置才能显示出来,下面我们记录一下具体的代码。

    当前所使用主题的 functions.php 文件中

    add_action( 'add_meta_boxes', 'jiloc_add_book_box' );
    function jiloc_add_book_box(){
    add_meta_box( 'jiloc_add_book_box', '自定义文章类型置顶', 'jiloc_sticky ', '自定义类型type', 'side', 'high' );
    }
    function jiloc_sticky (){ ?>
    <input id="super-sticky" name="sticky" type="checkbox" value="sticky" <?php checked( is_sticky() ); ?> /><label for="super-sticky" class="selectit">置顶本产品</label>
    <?php
    }

    效果如下

    主题中输出置顶文章代码

    $sticky = get_option( 'sticky_posts' );
    query_posts( array( 'post__in' => $sticky, 'ignore_sticky_posts' => 1 ) );

    主题中输出非置顶文章代码

    $sticky = get_option( 'sticky_posts' );
    query_posts(array('ignore_sticky_posts' => 1,'post__not_in' => $sticky) );

    不想把置顶文章和非置顶文章区分开来的话,直接把不输出置顶文章中的 ignore_sticky_posts 和 post__not_in 去掉即可正常输出,并且自动将置顶文章排在首位。

    如果是正常输出文章让置顶文章自动置顶,那么我们很有必要在置顶文章标题后面或前面添加【置顶】标识,以便用户知道这是一篇置顶文章。方法也很简单,只需要在循环语句中的标题后面添加以下代码即可:

    <?php if (is_sticky()) {?><span class="sticky-icon">置顶</span><?php } ?>
    

    意思就是判定当前文章是否为置顶文章,是的话就输出置顶标识。

  • WordPress 如何获取文章发表用户ID

    WordPress 如何获取文章发表用户ID

    WordPress插件/主题开发中,如何获取文章发表用户的ID ?

    LOOP循环中

    官方文档:

    get_the_author_meta( string $field = '', int|false $user_id = false )

    Retrieves the requested data of the author of the current post.

    Description 

    Valid values for the $field parameter include:

    • admin_color
    • aim
    • comment_shortcuts
    • description
    • display_name
    • first_name
    • ID
    • jabber
    • last_name
    • nickname
    • plugins_last_view
    • plugins_per_page
    • rich_editing
    • syntax_highlighting
    • user_activation_key
    • user_description
    • user_email
    • user_firstname
    • user_lastname
    • user_level
    • user_login
    • user_nicename
    • user_pass
    • user_registered
    • user_status
    • user_url
    • yim

    Parameters

    $field

    (string) (Optional) The user field to retrieve.

    Default value: ”$user_id

    (int|false) (Optional) User ID.

    Default value: false

    Return

    (string) The author’s field from the current author’s DB object, otherwise an empty string.

    在循环外面通过以下方法获取用户ID

    $author_id = get_post_field ('post_author', get_the_ID() );
  • WordPress 插件开发 激活插件时添加通知 代码实例

    WordPress 插件开发 激活插件时添加通知 代码实例

    最近我们在重构WordPress采集插件WP-JPost,这里记录一下当我们激活插件时在面板中添加通知的方法。

    使用场景

    我们插件使用register_post_type方法来构建了自定义文章(wordpress使用register_post_type 函数创建自定义文章类型)后出现了404的错误。这里我们使用添加通知的方法来告知用户必须设置一下【固定链接】(WordPress 固定链接设置)才能正常使用。下面我们记录一下具体的实现方法。

    添加通知方法

    可以通过admin_notices的add_action来实现。

    		add_action( 'admin_notices', array( $this, 'jpost_notice' ) );

    实现方法函数

    做好输出工作即可。

    	public function jpost_notice(){
    		if( get_post_type() == $this->post_type )
    			printf('<div class="jads"></div>');
    		/* Check transient, if available display notice */
    		if (! get_option('permalink_structure') ){
    			printf('<div class="updated notice notice-warning is-dismissible">');
    			printf('<p>%s</p>', __( 'WP-JPost need Navigate to [ <strong>Dashboard</strong> ] -> [ <strong>Settings</strong> ] -> [ <strong>Permalink</strong> ] page -> click [ <strong>Save</strong> ] button to flush rewrite rules. [ <a href="https://www.jiloc.com/44235.html">?</a> ]') );
    			printf('</div>');
    			/* Delete transient, only display this notice once. */
    			// delete_transient( 'jpost-notice' );
    		}
    	}

    激活插件事件

    当没有设置固定链接的时候输出 jpost-notice 的通知。

    	static function active() {
    		if (! get_option('permalink_structure') )
    			set_transient( 'jpost-notice', true );
    		flush_rewrite_rules();
    	}

    全部代码

    //register activation function
    register_activation_hook( __FILE__, array( 'WP_JPost', 'active') );
    //register deactivation function
    register_deactivation_hook( __FILE__ , array( 'WP_JPost', 'deactive') );
    class WP_JPost {
    	protected $jpost_readme = 'https://www.jiloc.com/wp-jpost';
    	protected $post_type = 'wp-jpost';
    	protected $rewrite_slug = 'jpost';
    	/**
    	 * Constructor.
    	 */
    	public function __construct() {
                    add_action( 'plugins_loaded', array( $this, 'load_textdomain' ) );
    		add_action( 'init', array( $this, 'register_post_type' ) );
    		// add_filter( 'post_type_link', array($this , 'custom_link' ), 1, 3);
    		add_filter( 'query_vars', array( $this, 'jpost_query_vars') );
    		add_filter( 'post_updated_messages', array( $this, 'updated_message' ) );
    		// add_action( 'admin_init',array($this,'register_setting_page'));
    		add_action( 'admin_menu', array( $this, 'add_meta_box' ) );
    		add_action( 'save_post', array( $this, 'meta_box_save' ), 1, 2 );
    		add_action( 'manage_wp-jpost_posts_custom_column', array( $this, 'columns_data' ) );
    		add_filter( 'manage_wp-jpost_posts_columns', array( $this, 'columns_filter' ) );
    		add_action( 'template_redirect', array( $this, 'jpost_grab' ) );
    		add_action( 'admin_notices', array( $this, 'jpost_notice' ) );
    	}
    	
    	public function custom_link( $permalink, $post ){
    		if ( $post->post_type == $this->post_type ){
    			return $permalink . ( strpos( $permalink ,'?' ) !== false ? '&' : '?') . 'jpage='.get_post_meta( get_the_ID(), '_jpost_task_list_max_page', true ) . '&debug=1';
    		} else {
    			return $permalink;
    		}
    	}
    	public function jpost_notice(){
    		if( get_post_type() == $this->post_type )
    			printf('<div class="jads"></div>');
    		/* Check transient, if available display notice */
    		if (! get_option('permalink_structure') ){
    			printf('<div class="updated notice notice-warning is-dismissible">');
    			printf('<p>%s</p>', __( 'WP-JPost need Navigate to [ <strong>Dashboard</strong> ] -> [ <strong>Settings</strong> ] -> [ <strong>Permalink</strong> ] page -> click [ <strong>Save</strong> ] button to flush rewrite rules. [ <a href="https://www.jiloc.com/44235.html">?</a> ]') );
    			printf('</div>');
    			/* Delete transient, only display this notice once. */
    			// delete_transient( 'jpost-notice' );
    		}
    	}
    	static function active() {
    		if (! get_option('permalink_structure') )
    			set_transient( 'jpost-notice', true );
    		flush_rewrite_rules();
    	}
    }
  • WordPress 插件开发 如何新建自定义页面?

    WordPress 插件开发 如何新建自定义页面?

    WordPress 插件开发中,我们需要自定义一些 option 操作选项。下面我们举例说明:在“设置”菜单下 — 添加一个名为“My Settings”的菜单,然后在页面中添加名为 ID Number 、Title 的2个填写框,我们这里尽量使用WordPress的原生代码,没有写很多不必要的HTML代码。

    PHP代码实例

    在 wp-content/plugins 目录下新建一个文件夹:wp-jpost 然后将以下文件命名为:plugin.php ,然后记得在插件列表中启用插件。

    <?php
    class MySettingsPage
    {
        /**
         * Holds the values to be used in the fields callbacks
         */
        private $options;
        /**
         * Start up
         */
        public function __construct()
        {
            add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
            add_action( 'admin_init', array( $this, 'page_init' ) );
        }
        /**
         * Add options page
         */
        public function add_plugin_page()
        {
            // This page will be under "Settings"
            add_options_page(
                'Settings Admin', 
                'My Settings', 
                'manage_options', 
                'my-setting-admin', 
                array( $this, 'create_admin_page' )
            );
        }
        /**
         * Options page callback
         */
        public function create_admin_page()
        {
            // Set class property
            $this->options = get_option( 'my_option_name' );
            ?>
            <div class="wrap">
                <h1>My Settings</h1>
                <form method="post" action="options.php">
                <?php
                    // This prints out all hidden setting fields
                    settings_fields( 'my_option_group' );
                    do_settings_sections( 'my-setting-admin' );
                    submit_button();
                ?>
                </form>
            </div>
            <?php
        }
        /**
         * Register and add settings
         */
        public function page_init()
        {        
            register_setting(
                'my_option_group', // Option group
                'my_option_name', // Option name
                array( $this, 'sanitize' ) // Sanitize
            );
            add_settings_section(
                'setting_section_id', // ID
                'My Custom Settings', // Title
                array( $this, 'print_section_info' ), // Callback
                'my-setting-admin' // Page
            );  
            add_settings_field(
                'id_number', // ID
                'ID Number', // Title 
                array( $this, 'id_number_callback' ), // Callback
                'my-setting-admin', // Page
                'setting_section_id' // Section           
            );      
            add_settings_field(
                'title', 
                'Title', 
                array( $this, 'title_callback' ), 
                'my-setting-admin', 
                'setting_section_id'
            );      
        }
        /**
         * Sanitize each setting field as needed
         *
         * @param array $input Contains all settings fields as array keys
         */
        public function sanitize( $input )
        {
            $new_input = array();
            if( isset( $input['id_number'] ) )
                $new_input['id_number'] = absint( $input['id_number'] );
            if( isset( $input['title'] ) )
                $new_input['title'] = sanitize_text_field( $input['title'] );
            return $new_input;
        }
        /** 
         * Print the Section text
         */
        public function print_section_info()
        {
            print 'Enter your settings below:';
        }
        /** 
         * Get the settings option array and print one of its values
         */
        public function id_number_callback()
        {
            printf(
                '<input type="text" id="id_number" name="my_option_name[id_number]" value="%s" />',
                isset( $this->options['id_number'] ) ? esc_attr( $this->options['id_number']) : ''
            );
        }
        /** 
         * Get the settings option array and print one of its values
         */
        public function title_callback()
        {
            printf(
                '<input type="text" id="title" name="my_option_name[title]" value="%s" />',
                isset( $this->options['title'] ) ? esc_attr( $this->options['title']) : ''
            );
        }
    }
    if( is_admin() )
        $my_settings_page = new MySettingsPage();

    实例来源WordPress官网:https://codex.wordpress.org/Creating_Options_Pages#Example_.232

  • WordPress 插件开发 自定义文章类型中 add_meta_box  如何使用原生的分类/标签显示并保存数据?

    WordPress 插件开发 自定义文章类型中 add_meta_box 如何使用原生的分类/标签显示并保存数据?

    近日我们在改版 WordPress 采集插件 wp-jpost , 将代码内容进行重构,我们尽量使用 WordPress 原生的代码来做。

    当我们在插件开发中使用 register_post_type 函数来自定义文章类型(wordpress使用register_post_type 函数创建自定义文章类型)时,可能需要 register_taxonomy 来注册一个对应的分类,但是我们这里想使用原生的 分类时,一开始我们使用了 add_meta_box (WordPress函数:add meta box(自定义添加Meta模块))的 post_categories_meta_box 来进行注册。

    但是后台可以正常显示,但是保存数据时并不能将分类数据保存下来,后来我们查阅相关文档之后发现必须使用 register_taxonomy_for_object_type 函数来调用。同样的标签类型也可以使用。

    <?php
    add_action( 'init', 'jiloc_add_page_cats' );
    function jiloc_add_page_cats(){
        $slug = "jiloc";
        register_taxonomy_for_object_type( 'category', $slug );
        register_taxonomy_for_object_type( 'post_tag', $slug );
    }
    

    WordPress函数:register post type (自定义文章类型)用法和范例 , 在这篇文章中我们进行了详细的记载。

WeChat
↑