WP custom_pre_get_posts 打破主题

Posted

技术标签:

【中文标题】WP custom_pre_get_posts 打破主题【英文标题】:WP custom_pre_get_posts breaks theme 【发布时间】:2014-07-20 09:56:22 【问题描述】:

我几周前添加了这段代码,但它昨晚突然停止工作,怎么可能?它在本地服务器上运行良好,但在共享主机上却不行。 Local 正在运行 php 5.5.3,host 正在运行 5.4,但我刚刚请求将该特定子域升级到 5.5,以防万一。

使用子主题。父主题创建了一个名为 Portfolio 的自定义帖子类型,其中所有帖子的 slug 为 /portfolio-item/。在我的子主题中,我添加了两件事: 1. 一个新的自定义帖子类型,称为隐藏页面,我使用了我在网上找到的删除 slug 的代码,所以它只是 domain.com/page-name。 2. 我添加了更多引用 Portfolio 类型的代码,这也删除了 slug。

一切都运行良好,但突然之间,所有标准页面 404(并且隐藏在后端,但不在数据库中,这不是数据库问题!),并且投资组合帖子神奇地移动到博客(常规标准帖子)。如果您注释掉 custom_pre_get_posts 行 (132),问题就解决了。但是客户需要在没有蛞蝓的情况下保持网址干净。所以我不想让它保持原样。

这是子主题的functions.php:

<?php

function evol_child_scripts() 
    wp_enqueue_style( 'style', get_stylesheet_directory_uri() . '/stylesheets/css/style.css' ); 


add_action( 'wp_enqueue_scripts', 'evol_child_scripts' );

/*function codex_custom_init() 
    $args = array(
      'public' => true,
      'label'  => 'Hidden Pages'
    );
    register_post_type( 'hidden', $args );

add_action( 'init', 'codex_custom_init' );
*/

/**
 * Register a custom post type but don't do anything fancy
 */
register_post_type( 'hidden', array( 'label' => 'Hidden Pages', 'public' => true, 'capability_type' => 'post',  'show_ui' => true, 'query_var' => true, 'supports' => array( 'title', 'editor', 'thumbnail' ) ) );
/**
 * Remove the slug from published post permalinks. Only affect our CPT though.
 */
function vipx_remove_cpt_slug( $post_link, $post, $leavename ) 

    if ( ! in_array( $post->post_type, array( 'hidden' ) ) 
        || 'publish' != $post->post_status )
        return $post_link;

    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );

    return $post_link;

add_filter( 'post_type_link', 'vipx_remove_cpt_slug', 10, 3 );

/**
 * Some hackery to have WordPress match postname to any of our public 
 * post types. All of our public post types can have /post-name/ as 
 * the slug, so they better be unique across all posts. Typically core 
 * only accounts for posts and pages where the slug is /post-name/
 */
function vipx_parse_request_tricksy( $query ) 

    // Only noop the main query
    if ( ! $query->is_main_query() )
        return;

    // Only noop our very specific rewrite rule match
    if ( 2 != count( $query->query )
        || ! isset( $query->query['page'] ) )
        return;

    // 'name' will be set if post permalinks are just post_name, 
    // otherwise the page rule will match
    if ( ! empty( $query->query['name'] ) )
        $query->set( 'post_type', array( 'post', 'hidden', 'page' ) );

add_action( 'pre_get_posts', 'vipx_parse_request_tricksy' );

function remove_search_filter () 
    remove_filter( 'pre_get_posts', 'tr_search_filter' );

add_action( 'init', 'remove_search_filter');

function remove_icons() 
    wp_dequeue_style( 'icons' );


add_action( 'wp_enqueue_scripts', 'remove_icons' );

function tr_widgets_init_2() 

    if ( ot_get_option( 'tr_sidebars' ) ) :
        $tr_sidebars = ot_get_option( 'tr_sidebars' );
        foreach ( $tr_sidebars as $tr_sidebar ) 
            register_sidebar( array(
                'id' => $tr_sidebar["id"],
                'name' => $tr_sidebar["title"],
                'before_widget' => '<div class="widget %2$s">',
                'after_widget' => '</div>',
                'before_title' => '<h6 class="widget-title">',
                'after_title' => '</h6>',
            ));
        
    endif;
;
add_action( 'widgets_init', 'tr_widgets_init_2' );


 add_filter('post_type_link','custom_post_type_link', 10, 3); 
    function custom_post_type_link($permalink, $post, $leavename)  

        $url_components = parse_url($permalink); 
        $post_path = $url_components['path']; 
        $post_name = end((explode('/', trim($post_path, '/'))));

        if(!empty($post_name))  
            switch($post->post_type)  
                case 'portfolio': 
                    $permalink = str_replace($post_path, '/' . $post_name . '/', $permalink); 
                break; 
             
         
        return $permalink; 
     

    function custom_pre_get_posts($query)  
        global $wpdb; 

        if(!$query->is_main_query())  
            return; 
         

        $post_name = $query->get('name'); 
        $post_type = $wpdb->get_var( $wpdb->prepare( 'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1', $post_name ) ); 

        switch($post_type)  
            case 'portfolio': 
                $query->set('portfolio', $post_name); 
                $query->set('post_type', $post_type); 
                $query->is_single = true; 
                $query->is_page = false; 
            break; 
         

        return $query; 
      


     add_action('pre_get_posts','custom_pre_get_posts');

function fb_add_search_box ( $items, $args ) 

    // only on primary menu
    if( 'primary' === $args -> theme_location )
        $items .= '<li class="menu-item menu-item-search">' . get_search_form( FALSE ) . '</li>';

    return $items;

add_filter( 'wp_nav_menu_items', 'fb_add_search_box', 10, 2 );

// Callback function to insert 'styleselect' into the $buttons array
function my_mce_buttons_2( $buttons ) 
    array_unshift( $buttons, 'styleselect' );
    return $buttons;

// Register our callback to the appropriate filter
add_filter('mce_buttons_2', 'my_mce_buttons_2');

// Callback function to filter the MCE settings
function my_mce_before_init_insert_formats( $init_array )   
    // Define the style_formats array
    $style_formats = array(  
        // Each array child is a format with it's own settings
        array(  
            'title' => 'Image Text', 
            'block' => 'p',  
            'classes' => 'image-text',     
        ),  
        array(  
            'title' => 'Image Text no Overlay', 
            'block' => 'p',  
            'classes' => 'image-text-2',     
        ),  
        array(  
             'title' => 'w/ gray background', 
            'inline' => 'span',  
            'exact' => true,    
             'classes' => 'gray-background', 
        ),  
        array(  
             'title' => 'w/ white background', 
            'inline' => 'span',  
            'exact' => true,    
             'classes' => 'white-background', 
        ),  
        array(  
            'title' => 'Image Text no Indent', 
            'block' => 'p',  
            'classes' => 'image-text-3',     
        ), 
        array(  
             'title' => 'Button', 
            'inline' => 'a',  
            'exact' => true,    
             'classes' => 'button small', 
        ),  
        array(  
            'title' => 'Blog Image Caption', 
            'block' => 'p',  
            'classes' => 'caption',     
        ), 
        array(  
             'title' => 'Signature', 
            'inline' => 'span',  
            'exact' => true,    
             'classes' => 'sign', 
        ),
    );  
    // Insert the array, JSON ENCODED, into 'style_formats'
    $init_array['style_formats'] = json_encode( $style_formats );  

    return $init_array;  

 
// Attach callback to 'tiny_mce_before_init' 
add_filter( 'tiny_mce_before_init', 'my_mce_before_init_insert_formats' );

这是父函数.php:

<?php

/*----------------------------------------------------------------------------*/
/*  Sets up theme defaults and registers support for various WordPress features.
/*----------------------------------------------------------------------------*/

function tr_theme_setup() 
    load_theme_textdomain( 'themerain', get_template_directory() . '/languages' );
    add_theme_support( 'automatic-feed-links' );
    add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list' ) );
    register_nav_menu( 'primary', 'Navigation Menu' );
    add_theme_support( 'post-thumbnails' );
    add_image_size( 'portfolio', 740, 540, true );

add_action( 'after_setup_theme', 'tr_theme_setup' );

/*----------------------------------------------------------------------------*/
/*  Sets up the content width value based on the theme's design and stylesheet.
/*----------------------------------------------------------------------------*/

if ( ! isset( $content_width ) ) $content_width = 780;

/*----------------------------------------------------------------------------*/
/*  Load Theme Options
/*----------------------------------------------------------------------------*/

add_filter( 'ot_show_pages', '__return_false' );
add_filter( 'ot_show_new_layout', '__return_false' );
add_filter( 'ot_theme_mode', '__return_true' );
load_template( trailingslashit( get_template_directory() ) . 'option-tree/ot-loader.php' );
load_template( trailingslashit( get_template_directory() ) . 'includes/theme-options.php' );
load_template( trailingslashit( get_template_directory() ) . 'includes/meta-boxes.php' );
load_template( trailingslashit( get_template_directory() ) . 'includes/theme-functions.php' );

/*----------------------------------------------------------------------------*/
/*  Register Sidebars
/*----------------------------------------------------------------------------*/

function tr_widgets_init() 
    register_sidebar( array(
        'id' => 'sidebar',
        'name' => 'Default Sidebar',
        'before_widget' => '<div class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h6 class="widget-title">',
        'after_title' => '</h6>',
    ));

    register_sidebar( array(
        'id' => 'footer-sidebar',
        'name' => 'Footer Sidebar',
        'before_widget' => '<div class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h6 class="widget-title">',
        'after_title' => '</h6>',
    ));

    if ( ot_get_option( 'tr_sidebars' ) ) :
        $tr_sidebars = ot_get_option( 'tr_sidebars' );
        foreach ( $tr_sidebars as $tr_sidebar ) 
            register_sidebar( array(
                'id' => $tr_sidebar["id"],
                'name' => $tr_sidebar["title"],
                'before_widget' => '<div class="widget %2$s">',
                'after_widget' => '</div>',
                'before_title' => '<h6 class="widget-title">',
                'after_title' => '</h6>',
            ));
        
    endif;
;
add_action( 'widgets_init', 'tr_widgets_init' );

/*----------------------------------------------------------------------------*/
/*  Register and load CSS & jQuery
/*----------------------------------------------------------------------------*/

function tr_enqueue_scripts() 
    wp_enqueue_style( 'style', get_stylesheet_uri() );
    wp_enqueue_style( 'icons', get_template_directory_uri() . '/assets/css/icons.css' );
    wp_enqueue_style( 'magnific', get_template_directory_uri() . '/assets/css/magnific-popup.css' );
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'custom', get_template_directory_uri() . '/assets/js/jquery.custom.js', 'jquery' );
    wp_enqueue_script( 'flexslider', get_template_directory_uri() . '/assets/js/jquery.flexslider.min.js', 'jquery' );
    wp_enqueue_script( 'isotope', get_template_directory_uri() . '/assets/js/jquery.isotope.min.js', 'jquery' );
    wp_enqueue_script( 'magnific', get_template_directory_uri() . '/assets/js/jquery.magnific-popup.min.js', 'jquery' );
    wp_enqueue_script( 'validation', get_template_directory_uri() . '/assets/js/jquery.validate.min.js', 'jquery' );
    if ( is_singular() ) wp_enqueue_script( 'comment-reply' );

add_action( 'wp_enqueue_scripts', 'tr_enqueue_scripts' );

/*----------------------------------------------------------------------------*/
/*  Load Widgets
/*----------------------------------------------------------------------------*/

include( "includes/widget-recent-projects.php" );

/*----------------------------------------------------------------------------*/
/*  Configure Pagination
/*----------------------------------------------------------------------------*/

function tr_pagination() 
    global $wp_query, $wp_rewrite;
    $pages = '';
    $total = 1;
    $max = $wp_query->max_num_pages;
    if ( ! $current = get_query_var( 'paged' ) ) $current = 1;
    $args['base'] = str_replace( 999999999, '%#%', get_pagenum_link( 999999999 ) );
    $args['total'] = $max;
    $args['current'] = $current;
    $args['end_size'] = 1;
    $args['mid_size'] = 3;
    $args['prev_text'] = '<i class="fa-angle-left"></i> Previous';
    $args['next_text'] = 'Next <i class="fa-angle-right"></i>';
    $args['type'] = 'list';
    if ( $max > 1 ) echo '<div id="pagination">';
    if ( $total == 1 && $max > 1 );
    echo $pages . paginate_links( $args );
    if ( $max > 1 ) echo '</div>';


/*----------------------------------------------------------------------------*/
/*  Configure Excerpt
/*----------------------------------------------------------------------------*/

function new_excerpt_more( $more ) 
    return ' ...';

add_filter( 'excerpt_more', 'new_excerpt_more' );

/*-----------------------------------------------------------------------------------*/
/*  Configure Tag Cloud
/*-----------------------------------------------------------------------------------*/

function tag_cloud_filter($args = array()) 
   $args['smallest'] = 12;
   $args['largest'] = 12;
   $args['unit'] = 'px';
   return $args;

add_filter('widget_tag_cloud_args', 'tag_cloud_filter', 90);

/*----------------------------------------------------------------------------*/
/*  Exclude Pages from Search
/*----------------------------------------------------------------------------*/

function tr_search_filter( $filter ) 
    if ( $filter->is_search ) 
        $filter->set( 'post_type', 'post' );
    
    return $filter;

add_filter( 'pre_get_posts', 'tr_search_filter' );

/*----------------------------------------------------------------------------*/
/*  Add Portfolio Post Types
/*----------------------------------------------------------------------------*/

function tr_portfolio() 
    $labels = array(
        'name' => 'Portfolio',
        'singular_name' => 'Portfolio Item',
        'add_new' => 'Add New',
        'add_new_item' => 'Add New Portfolio Item',
        'edit_item' => 'Edit Portfolio Item',
        'new_item' => 'New Portfolio Items',
        'view_item' => 'View Portfolio Item',
        'search_items' => 'Search Portfolio Items',
        'not_found' =>  'No Portfolio Items found',
        'not_found_in_trash' => 'No Portfolio Items found in Trash', 
        'parent_item_colon' => ''
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'exclude_from_search' => false,
        'publicly_queryable' => true,
        'show_ui' => true, 
        'query_var' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => 4,
        'rewrite' => array( 'slug' => 'portfolio-item' ),
        'supports' => array( 'title', 'editor', 'thumbnail' )
    );
    register_post_type( 'portfolio', $args );

    register_taxonomy(
        "portfolio-category", array( "portfolio" ), array(
            "hierarchical" => true,
            "label" => "Portfolio Categories",
            "singular_label" => "Portfolio Categories",
            "rewrite" => true,
            "query_var" => true
        )
    );

add_action( 'init', 'tr_portfolio' );

/*----------------------------------------------------------------------------*/
/*  Add Gallery Post Types
/*----------------------------------------------------------------------------*/

function tr_gallery() 
    $labels = array(
        'name' => 'Gallery',
        'singular_name' => 'Gallery Item',
        'add_new' => 'Add New',
        'add_new_item' => 'Add New Gallery Item',
        'edit_item' => 'Edit Gallery Item',
        'new_item' => 'New Gallery Items',
        'view_item' => 'View Gallery Item',
        'search_items' => 'Search Gallery Items',
        'not_found' =>  'No Gallery Items found',
        'not_found_in_trash' => 'No Gallery Items found in Trash', 
        'parent_item_colon' => ''
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'exclude_from_search' => true,
        'publicly_queryable' => true,
        'show_ui' => true, 
        'query_var' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => 4,
        'rewrite' => array( 'slug' => 'gallery-item' ),
        'supports' => array( 'title', 'thumbnail' )
    );
    register_post_type( 'gallery', $args );

    register_taxonomy(
        "gallery-category", array( "gallery" ), array(
            "hierarchical" => true,
            "label" => "Gallery Categories",
            "singular_label" => "Gallery Categories",
            "rewrite" => true,
            "query_var" => true
        )
    );

add_action( 'init', 'tr_gallery' );

/*----------------------------------------------------------------------------*/
/*  Add a Custom Taxonomy to the Post Class
/*----------------------------------------------------------------------------*/

function custom_portfolio_post_class( $classes, $class, $ID ) 
    $taxonomy = 'portfolio-category';
    $terms = get_the_terms( (int) $ID, $taxonomy );
    if ( ! empty( $terms ) ) 
        foreach ( (array) $terms as $order => $term ) 
            if ( ! in_array( $term->slug, $classes ) ) 
                $classes[] = $term->slug;
            
        
    
    return $classes;

add_filter( 'post_class', 'custom_portfolio_post_class', 10, 3 );

function custom_gallery_post_class( $classes, $class, $ID ) 
    $taxonomy = 'gallery-category';
    $terms = get_the_terms( (int) $ID, $taxonomy );
    if ( ! empty( $terms ) ) 
        foreach ( (array) $terms as $order => $term ) 
            if ( ! in_array( $term->slug, $classes ) ) 
                $classes[] = $term->slug;
            
        
    
    return $classes;

add_filter( 'post_class', 'custom_gallery_post_class', 10, 3 );

/*----------------------------------------------------------------------------*/
/*  Register the Required Plugins
/*----------------------------------------------------------------------------*/

require_once dirname( __FILE__ ) . '/includes/plugin-activation.php';

function tr_register_required_plugins() 

    $plugins = array(
        array(
            'name'                  => 'Rain Shortcodes',
            'slug'                  => 'rain-shortcodes',
            'source'                => get_stylesheet_directory() . '/includes/plugins/rain-shortcodes.zip',
            'required'              => true,
            'version'               => '',
            'force_activation'      => false,
            'force_deactivation'    => false,
            'external_url'          => '',
        )
    );

    $theme_text_domain = 'tgmpa';

    $config = array(
        'domain'            => $theme_text_domain,
        'default_path'      => '',
        'parent_menu_slug'  => 'themes.php',
        'parent_url_slug'   => 'themes.php',
        'menu'              => 'install-required-plugins',
        'has_notices'       => true,
        'is_automatic'      => true,
        'message'           => '',
        'strings'           => array(
            'page_title'                                => __( 'Install Required Plugins', $theme_text_domain ),
            'menu_title'                                => __( 'Install Plugins', $theme_text_domain ),
            'installing'                                => __( 'Installing Plugin: %s', $theme_text_domain ), // %1$s = plugin name
            'oops'                                      => __( 'Something went wrong with the plugin API.', $theme_text_domain ),
            'notice_can_install_required'               => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.' ),
            'notice_can_install_recommended'            => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.' ),
            'notice_cannot_install'                     => _n_noop( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'Sorry, but you do not have the correct permissions to install the %s plugins. Contact the administrator of this site for help on getting the plugins installed.' ),
            'notice_can_activate_required'              => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.' ),
            'notice_can_activate_recommended'           => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.' ),
            'notice_cannot_activate'                    => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', 'Sorry, but you do not have the correct permissions to activate the %s plugins. Contact the administrator of this site for help on getting the plugins activated.' ),
            'notice_ask_to_update'                      => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.' ),
            'notice_cannot_update'                      => _n_noop( 'Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'Sorry, but you do not have the correct permissions to update the %s plugins. Contact the administrator of this site for help on getting the plugins updated.' ),
            'install_link'                              => _n_noop( 'Begin installing plugin', 'Begin installing plugins' ),
            'activate_link'                             => _n_noop( 'Activate installed plugin', 'Activate installed plugins' ),
            'return'                                    => __( 'Return to Required Plugins Installer', $theme_text_domain ),
            'plugin_activated'                          => __( 'Plugin activated successfully.', $theme_text_domain ),
            'complete'                                  => __( 'All plugins installed and activated successfully. %s', $theme_text_domain ),
            'nag_type'                                  => 'updated'
        )
    );
    tgmpa( $plugins, $config );


add_action( 'tgmpa_register', 'tr_register_required_plugins' );

?>

当 wp_debug 设置为 true 时,返回:

Strict Standards: Only variables should be passed by reference in    
[path redacted]/functions.php on line 97

这是指这一行:

$post_name = end(explode('/', trim($post_path, '/'))); 

这仍然在错误日志中,但是在更改后,它在管理端没有,这是否意味着它已修复?

儿童主题代码来自这里:https://gist.github.com/stefanbc/6620151 和 http://www.markwarddesign.com/2014/02/remove-custom-post-type-slug-permalink/

所以,如果有人知道如何修改此文件以使一切恢复正常工作,那就太好了。实际上,我们距离发布还有几天的时间。呃。谢谢!

【问题讨论】:

【参考方案1】:

问题不在于错误所述的 Wordpress,它都是纯 PHP。您应该对该行稍作改动(用括号括起来 explode()):

$post_name = end((explode('/', trim($post_path, '/')))); 

【讨论】:

嗨雷沃!非常感谢,这确实消除了错误,所以现在我们没有错误了。但不幸的是,它并没有解决问题。在仍然混乱的页面上仍然是 404ing。有什么后续步骤吗? (我应该更新上面的代码以反映这种变化,还是应该离开它?) @Alicia 同时设置WP_DEBUGWP_DEBUG_LOG。但是您已经启用了 WP_DEBUG,您需要在此之后添加此行:define('WP_DEBUG_LOG', true);。然后转到您的网站以创建要创建的日志并检查 /wp-content/ 目录中的 debug.log 日志文件。最好也为您的帖子添加更新。 好的,如果你的意思是error_log,这里是错误:PHP致命错误:无法在evol/functions.php中重新声明vipx_remove_cpt_slug()(之前在evol-child/functions.php:26中声明)在第 294 行,这是指我想我也必须将该部分添加到父主题的功能中。 @Alicia 所以就在那里!您已经在父模板中声明了该函数,无需重新声明。 好吧,问题是我只是看了看......它不存在。让我添加父functions.php。【参考方案2】:

鉴于我的 PHP 水平并且不想重写涉及父主题和子主题功能的代码,我无法找到解决此问题的方法。我最终删除了所有试图删除 slug 的代码。我交叉手指并安装了这个过时的插件,它工作。因此,对于任何人以供将来参考,我想您可以避免使用代码而直接使用它!

https://wordpress.org/plugins/remove-slug-from-custom-post-type/

【讨论】:

以上是关于WP custom_pre_get_posts 打破主题的主要内容,如果未能解决你的问题,请参考以下文章

CTF show xaiogaigai WP

Wechall 部分WP

[祥云杯2021] wp

bugkuCTFWEB部分WP

WP-2021西湖论剑

2021西湖论剑-wp