php [algolia wp] algolia wordpress

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php [algolia wp] algolia wordpress相关的知识,希望对你有一定的参考价值。

<?php
/**------------------------------------------------------------------------------
	index settings: https://community.algolia.com/wordpress/indexing-settings.html
*/    
//custom metric named visits_count and you would like to add a custom ranking rule on
add_filter('algolia_posts_index_settings', 'algolia_posts_index_settings', 10, 2);
function algolia_posts_index_settings($settings, $post_type) {
  	if($post_type=='post') {
      $custom_ranking = $settings['customRanking'];
      array_unshift( $custom_ranking, 'desc(visits_count)' );
      $settings['customRanking'] = $custom_ranking;
      
      //register a custom attribute as a facet
      $settings['attributesForFaceting'][] = 'number_bedroom';
	}
	return $settings;
}

/**
	hook into the indexing decision
*/
/**
 * @param bool $should_index
 * @param WP_User $user
 *
 * @return bool
 */
function filter_user( $should_index, $user ) {
  	//if the decision has already been taken to not index the content.
    if ( false === $should_index ) {
        return false;
    }
	//User with ID 1 would never get indexed
    return $user->ID !== 1;
}

add_filter( 'algolia_should_index_user', 'filter_user', 10, 2 );

//### exclude posts from the searchable_posts index
function filter_post( $should_index, WP_Post $post )
{
    if ( false === $should_index ) {
        return false;
    }
	//ex1: yoast seo with noindex
    return get_post_meta($post->ID, '_yoast_wpseo_meta-robots-noindex', true) == 1 ? false : true;
  
  	//ex2: Add all post types you don't want to make searchable.
    $excluded_post_types = array( 'page' );
  	return ! in_array( $post->post_type, $excluded_post_types, true );
  
  	//ex3: skips the post with ID 18517
  	if ( 18517 === $post->ID ) {
        return false;
    }
}

// Hook into Algolia to manipulate the post that should be indexed.
add_filter( 'algolia_should_index_searchable_post', 'filter_post', 10, 2 );
add_filter( 'algolia_should_index_post', 'filter_post', 10, 2 );

/**
	Add post type:
	default: plugin will only index post types that are not flagged as excluded from search.
*/
//manually determine the post types you want to index
add_filter( 'algolia_searchable_post_types', function( $post_types ) {
    $post_types[] = 'custom_post_type';

    return $post_types;
} );

//don't want to expose some post type for indexing
function mb_blacklist_custom_post_type( array $blacklist ) {
    $blacklist[] = 'custom_post_type';

    return $blacklist;
}
add_filter( 'algolia_post_types_blacklist', 'mb_blacklist_custom_post_type' );

/**
	Queue processing
*/
//Every time a change of your content is detected, we synchronize the item.
add_filter( 'algolia_changes_watchers', function() {
  //disable automatic sychronization by removing all the watchers
    return array();
} );

/*------------------------------------------------------attributes
	custom attributes
*/
//### retrieve visits count for every post, let's add it to every Algolia post records
function vm_post_shared_attributes( array $shared_attributes, WP_Post $post) {
    $shared_attributes['visits_count'] = vm_get_post_visit_count( $post->ID );

    return $shared_attributes;
}
add_filter( 'algolia_post_shared_attributes', 'vm_post_shared_attributes', 10, 2 );

//so add custom ranking for visits_count & protect this data
function vm_posts_index_settings( array $settings ) {
    $custom_ranking = $settings['customRanking'];
    array_unshift( $custom_ranking, 'desc(visits_count)' );
    $settings['customRanking'] = $custom_ranking;
	
  	// Protect our sensitive data. ie: visits_count is sensitive data
  	//now safely stored in Algolia, used in the ranking formula but un-retrievable from the frontend!
    $protected_attributes = array();
    if ( isset( $settings['unretrievableAttributes'] ) ) {
        // Ensure we merge our values with the existing ones if available.
        $protected_attributes = $settings['unretrievableAttributes'];
    }
    $protected_attributes[] = 'visits_count';
    $settings['unretrievableAttributes'] = $protected_attributes;
  
    return $settings;
}

add_filter( 'algolia_posts_index_settings', 'vm_posts_index_settings' );

//filters: https://community.algolia.com/wordpress/filters.html| https://community.algolia.com/wordpress/actions.html
//### custom fields: add the `bio` attribute to both searchable_posts and posts indices.
add_filter( 'algolia_post_shared_attributes', 'my_post_attributes', 10, 2 );
add_filter( 'algolia_searchable_post_shared_attributes', 'my_post_attributes', 10, 2 );

function my_post_attributes( array $attributes, WP_Post $post ) {

    if ( 'speaker' !== $post->post_type ) {
        // We only want to add an attribute for the 'speaker' post type.
        // Here the post isn't a 'speaker', so we return the attributes unaltered.
        return $attributes;
    }

    // Get the field value with the 'get_field' method and assign it to the attributes array.
    // @see https://www.advancedcustomfields.com/resources/get_field/
    $attributes['bio'] = get_field( 'bio', $post->ID );

    // Always return the value we are filtering.
    return $attributes;
}

//Make custom fields searchable
//alter the settings of the `posts_speaker` index because in the `searchable_posts` index not all posts have the `bio` attribute
add_filter( 'algolia_posts_speaker_index_settings', 'my_posts_index_settings' );
function my_posts_index_settings( array $settings ) {

    // Make Algolia search into the 'bio' field when searching for results.
    // Using ordered instead of unordered would make words matching in the beginning of the attribute make the record score higher.
    $settings['attributesToIndex'][] = 'unordered(bio)';

    // Make Algolia return a pre-computed snippet of 50 chars as part of the result set.
    $settings['attributesToSnippet'][] = 'bio:50';

    return $settings;
}

/**----------------------------------------------------------------------
	Filters / actions
*/
//specify the thumbnail sizes you want to push
add_filter('algolia_post_images_sizes', function($sizes) {
    $sizes[] = 'medium';
	//or containing the width and height
  	$sizes[] = array(250, 300);
  
    return $sizes;
});

//filter wp content
add_filter('algolia_post_content', 'algolia_searchable_post_content');
add_filter('algolia_searchable_post_content', 'algolia_searchable_post_content');
function algolia_searchable_post_content($content) {
    global $post;

    if($post->post_type=='product') {
        $ms = get_field( 'ms', $post->ID );
        $name = get_field( 'name', $post->ID );

        if(strpos($content, "MS: $ms")===false) $content.= "<br>\nMS: $ms, Name: $name";
    }

    return $content;
}

/**
	support search infix/suffix matching
    By default: algolia match prefix of each words
*/
function algolia_infix_matching($str, $min=2, &$track=[]) {
    $words = preg_split('#[\s]+#', $str);
    $r=[];
    foreach($words as $w) {
        while (mb_strlen($w) > $min) {
            $w = substr($w, 1);$c=0;
            foreach($r as $r1) {
                if(startsWith($r1, $w)) {$c=1;break;}
            }
            if(!$c && !isset($track[$w])) $r[$w] = $w;
        }
    }
    $track = array_merge($track,$r);    //save
    return array_values($r);
}
add_filter( 'algolia_post_shared_attributes', 'my_post_attributes', 10, 2 );
function my_post_attributes( array $attributes, WP_Post $post ) {
  	if ( 'product' !== $post->post_type ) {
        return $attributes;
    }
  	$trackSuffix=[];
  
  	$attributes['post_title'] = array_merge([$attributes['post_title']], algolia_infix_matching($attributes['post_title'], 2, $trackSuffix));
  	return $attributes;
}

以上是关于php [algolia wp] algolia wordpress的主要内容,如果未能解决你的问题,请参考以下文章

php [algolia php] algolia搜索php

algolia facets 自动隐藏产品

VuePress - Algolia 增加结果

Hexo next主题安装algolia

使用 Algolia 的 Firestore 数据库

在产品视图中显示 Algolia 结果