WordPress自定义文章类型,在管理列表页显示分类名

只需要在register_taxonomy函数的第三个参数中,添加show_admin_column=>true即可。代码如下:

<?php

/**
 * 为产品 post type 添加分类功能
 */
add_action('init', 'my_taxonomies_product', 0);
function my_taxonomies_product() {
    $labels = array(
        'name'              => _x('产品分类', 'taxonomy 名称'),
        'singular_name'     => _x('产品分类', 'taxonomy 单数名称'),
        'search_items'      => __('搜索产品分类'),
        'all_items'         => __('所有产品分类'),
        'parent_item'       => __('该产品分类的上级分类'),
        'parent_item_colon' => __('该产品分类的上级分类:'),
        'edit_item'         => __('编辑产品分类'),
        'update_item'       => __('更新产品分类'),
        'add_new_item'      => __('添加新的产品分类'),
        'new_item_name'     => __('新产品分类'),
        'menu_name'         => __('产品分类'),
    );
    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'show_admin_column' => true,
    );
    register_taxonomy('product_category', 'product', $args);
}

如果要在列表中添加自定义字段,即wp_postmeta表中的字段(通过meta_box添加的),可以使用下面的代码:

<?php

// 在列表中把加的字段显示出来
add_action("manage_posts_custom_column",  "product_custom_columns");
function product_custom_columns($column) {
    global $post;
    switch ($column) {
        case "product_director":
            echo get_post_meta($post->ID, '_product_director', true);
            break;
    }
}

add_filter("manage_edit-product_columns", "movie_edit_columns");
function movie_edit_columns($columns) {
    $columns['product_director'] = '产品分类';
    return $columns;
}

WordPress在single页面获取自定发布类型的分类

在详情页面,即single页面获取自定义发布类型的分类

<?php

/** 第一个参数表是当前文章的ID, 第二个参数表示所属的分类法,即taxonomy name。在single页面时可以直接使用 $post->ID **/
$terms = get_the_terms($post->ID, 'product_category');
if ($terms && !is_wp_error($terms)) :
    $terms_name_arr = array();
    foreach ($terms as $term) {
        $terms_name_arr[] = $term->name;
    }
    $terms_name_str = join(" ", $terms_name_arr);
endif;
echo $terms_name_str;

WordPress在archive.php页面获取文章列表

除了使用WP_Query函数之外,还可以使用query_posts函数来查询,如下:

<?php
query_posts(array(
    'post_type'   => 'case', // You can add a custom post type if you like
    'paged'     => get_query_var('paged', 1),
    'posts_per_page' => 1
));

while (have_posts()) :
    the_post();
?>
    <a href="<?php the_permalink() ?>" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 block-four-list">
        <div class="block-four-list-wrap">
            <img src="<?php echo catch_that_image(); ?>" alt="">
            <div class="infos-right-view2 about-a-infos">
                <h5>成功案例</h5>
                <h1><?php the_title() ?></h1>
                <span class="a-more-4">了解更多<i class="iconfont icon-youjiantou6"></i></span>
            </div>
        </div>
    </a>


<?php
endwhile;

?>

WordPress修改默认发布类型(post)的一些参数

<?php
add_action('init', 'cp_change_post_object');
// Change dashboard Posts to News
function cp_change_post_object() {
    $get_post_type = get_post_type_object('post');
    $labels = $get_post_type->labels;
    //$labels->name = 'News';
    $labels->singular_name = '新闻资讯';
    // $labels->add_new = 'Add News';
    // $labels->add_new_item = 'Add News';
    // $labels->edit_item = 'Edit News';
    // $labels->new_item = 'News';
    // $labels->view_item = 'View News';
    // $labels->search_items = 'Search News';
    // $labels->not_found = 'No News found';
    // $labels->not_found_in_trash = 'No News found in Trash';
    // $labels->all_items = 'All News';
    // $labels->menu_name = 'News';
    // $labels->name_admin_bar = 'News';
}

WordPress搜索功能的制作

首先要创建一个搜索表单,示例代码如下:

<form method="get" action="" onsubmit="return checkForm();">
    <input type="text" placeholder="搜索" name="s" value="<?php the_search_query(); ?>">
    <button type="submit">
        <i class="iconfont icon-sousuo"></i>
    </button>
</form>

表单要注意的是,搜索关键词输入框的name一定要为s,不然wordpress识别不了,也就进不了search.php模板页面。

这样,在点击搜索按钮后,wordpress就会自动跳转到search.php模板页面。

search.php主要代码参考:

<div class="met-news-list" m-id="noset">
    <ul class="ulstyle met-pager-ajax imagesize" data-scale="400x400">
        <?php
        $paged = 1;
        if (get_query_var('page')) {
            $paged = get_query_var('page');
        }
        $s = get_search_query();
        $args = array(
            's' => $s,
            'paged' => $paged,
            'posts_per_page' => 20
        );

        // The Query
        $the_query = new WP_Query($args);
        if ($the_query->have_posts()) {
            while ($the_query->have_posts()) {
                $the_query->the_post();
        ?>
                <li>
                    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                </li>

                <li class="media media-lg border-bottom1">
                    <div class="media-left">
                        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
                            <img class="media-object" src="<?php echo catch_that_image(); ?>" alt="<?php the_title(); ?>" height="100" />
                        </a>
                    </div>
                    <div class="media-body">
                        <h4> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_self"><?php the_title(); ?></a> </h4>
                    </div>
                </li>

            <?php
            }
        } else {
            ?>
            <!--未找到任何搜索结果-->

        <?php }
        ?>
    </ul>
    <div class="m-t-20 text-xs-center hidden-sm-down" m-type="nosysdata">
        共<strong><?php echo $the_query->max_num_pages; ?></strong>页 <strong><?php echo $wp_query->found_posts; ?></strong>条
    </div>
    <?php bootstrap_pagination($the_query); ?>
</div>

WordPress获取文章内的第一张图片

<?php
// 获取文章第一张图片

function catch_that_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post->post_content, $matches);
    $first_img = $matches[1][0];
    if (empty($first_img)) {
        $first_img = "/path/to/default.png";
    }
    return $first_img;
}

改进版,增加了默认图片的显示,以及文章中没有图片时的判断:

<?php
// 获取文章第一张图片
function catch_that_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post->post_content, $matches);
    if ($output) {
        $first_img = $matches[1][0];
    }

    if (empty($first_img)) {
        $first_img = bloginfo('template_url') . "/assets/images/default_image.jpeg";
    }
    return $first_img;
}

默认图片:default_image.jpeg,需要自己找一张。

WordPress分页改不了分页URL的问题,并且分页 页面提示“找不到页面”

一个分页问题搞了一晚上和一上午,分页函数`paginate_links`生成的链接一直是`/page/2`这种,并且打不开,提示找不到页面。

google+baidu 几乎找遍了也没找到解决方案。最后在看`paginate_links`参数时,发现第一个参数`base`的意思是”Base of the paginated url”,翻译过来就是“分页URL的基础”,忽然意识到是不是这个参数的原因。

由于之前分页代码是在网上随便找的,`base`参数是

$big = 999999999;
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),

打印了一下它的值是https://notes.wujie.me/case/page/%#%,也就是说生成的分页链接就是/case/page/%#%这种格式的。

那么到此就可以确定是该参数的问题,解决办法就是不使用该参数,或者使用它的默认值%_%,即可把分页URL改成https://notes.wujie.me/case?page=2这种默认样式。

至于为什么只有默认URL样式才能访问,而page/2这样样式会找不到页面,就不得而知了。

最终改过之后的代码如下:

global $wp_query;
echo paginate_links( array(
     'base' => '%_%',
     'format' => '?page=%#%',
     'current' => max( 1, get_query_var('page') ),
     'total' => $wp_query->max_num_pages
 ) );

附一个兼容boostrap4的分页样式:

// 兼容bootstrap4的分页
function bootstrap_pagination(\WP_Query $wp_query = null, $echo = true) {
    if (null === $wp_query) {
        global $wp_query;
    }

    $pages = paginate_links(
        [
            //'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
            'format'       => '?page=%#%',
            'current'      => max(1, get_query_var('paged')),
            'total'        => $wp_query->max_num_pages,
            'type'         => 'array',
            'show_all'     => false,
            'end_size'     => 3,
            'mid_size'     => 1,
            'prev_next'    => true,
            'prev_text'    => __('« 上一页'),
            'next_text'    => __('下一页 »'),
            'add_args'     => false,
            'add_fragment' => ''
        ]
    );

    if (is_array($pages)) {
        //$paged = ( get_query_var( 'paged' ) == 0 ) ? 1 : get_query_var( 'paged' );
        $pagination = '<div class="pagination"><ul class="pagination">';
        foreach ($pages as $page) {
            $pagination .= '<li class="page-item' . (strpos($page, 'current') !== false ? ' active' : '') . '"> ' . str_replace('page-numbers', 'page-link', $page) . '</li>';
        }
        $pagination .= '</ul></div>';
        if ($echo) {
            echo $pagination;
        } else {
            return $pagination;
        }
    }
    return null;
}

经验教训:复制网上的代码时,要弄懂每一行在干什么,不要随意粘贴到自己的项目中。