我将分享我如何使用Wordpress开箱即用功能和ACF
, 没有自定义PHP
有问题的脚本。
- Creating a custom post type
- Adding a custom field to the custom post type
- Creating the search form
- Outputting the search results
Custom Post Type:第一步相对容易,在
functions.php
文件或其他地方:
资源:
https://www.codexworld.com/wordpress-custom-post-types-without-plugin/
function product_init() {
$labels = array(
\'name\' => \'Products\',
\'singular_name\' => \'Product\',
\'add_new\' => \'Add New Product\',
\'add_new_item\' => \'Add New Product\',
\'edit_item\' => \'Edit Product\',
\'new_item\' => \'New Product\',
\'all_items\' => \'All Products\',
\'view_item\' => \'View Product\',
\'search_items\' => \'Search Products\',
\'not_found\' => \'No Products Found\',
\'not_found_in_trash\' => \'No Products found in Trash\',
\'parent_item_colon\' => \'\',
\'menu_name\' => \'Products\',
);
$args = array(
\'labels\' => $labels,
\'public\' => true,
\'has_archive\' => true,
\'show_ui\' => true,
\'capability_type\' => \'post\',
\'hierarchical\' => false,
\'rewrite\' => array(\'slug\' => \'product\'),
\'query_var\' => true,
\'menu_icon\' => \'dashicons-randomize\',
\'supports\' => array(
\'title\',
\'editor\',
\'excerpt\',
\'trackbacks\',
\'custom-fields\',
\'comments\',
\'revisions\',
\'thumbnail\',
\'author\',
\'page-attributes\'
)
);
register_post_type( \'product\', $args );
register_taxonomy(\'product_category\', \'product\', array(\'hierarchical\' => true, \'label\' => \'Category\', \'query_var\' => true, \'rewrite\' => array( \'slug\' => \'product-category\' )));
}
add_action( \'init\', \'product_init\' );
Custom fields:创建自定义字段时不使用
ACF
比我想象的要复杂,请改用高级自定义字段插件,并创建一个应用于
\'Type of Content\'
&燃气轮机;
\'Product\'
- 或者您的自定义帖子类型。创建“城市”等字段。
Search form:
创建一个名为searchform.php
在模板的文件夹中,它将包含<form>
:
<form id="searchform" method="get" action="<?php echo esc_url( home_url( \'/\' ) ); ?>">
<input type="text" class="search-field" name="s" placeholder="Search" value="<?php echo get_search_query(); ?>">
<input type="hidden" name="post_type[]" value="product" />
<input type="submit" value="Search">
</form>
资源:
https://wordpress.stackexchange.com/a/17119/219065https://artisansweb.net/create-custom-search-form-wordpress/
Results:
在search.php
文件,我执行以下代码:
$args = array(
\'post_type\' => \'product\',
\'meta_query\' => array(
array( \'key\' => \'city\', \'value\' => \'Moscow\', \'meta_compare\' => \'LIKE\' ),
array( \'key\' => \'city\', \'value\' => array(\'Edinburgh\', \'Moscow\'), \'meta_compare\' => \'IN\' ),
\'relation\' => \'OR\'
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) : $the_query->the_post();
echo get_the_title();
endwhile;
} else {
echo "No posts";
}
wp_reset_postdata();
资源:
https://www.smashingmagazine.com/2016/03/advanced-wordpress-search-with-wp_query/https://rudrastyh.com/wordpress/meta_query.htmlMeta_query compare operator explanation后记。您将不得不调整和调整大部分代码,因为它当然不准备处理您将要使用搜索功能的所有情况。我发现代码中的许多元素都是不必要和不完整的(查看参考资料了解更多信息),但它只是一个示例,希望对您有所帮助。