Algolia Wordpress Limit Search to Post Titles only - wordpress

Is there a way to limit the search only to post titles with Algolia on Wordpress?
I need this for the autocomplete feature.

You can definitely customize on what field the search will be based on.
First of all you have to let Algolia know that you only want to search on the post title field by changing the attributesToIndex setting:
/**
* #param array $settings
*
* #return array
*/
function custom_posts_index_settings( array $settings ) {
$settings['attributesToIndex'] = array( 'unordered(post_title)' );
return $settings;
}
add_filter('algolia_posts_index_settings', 'custom_posts_index_settings');
add_filter('algolia_searchable_posts_index_settings', 'custom_posts_index_settings');
Then you need to customize the suggestions templates of the autocomplete by first moving the autocomplete.php file to your theme's folder like explained in this guide: https://community.algolia.com/wordpress/customize-autocomplete.html
Basically you will remove the part which looks like this one:
<#
var attributes = ['content', 'title6', 'title5', 'title4', 'title3', 'title2', 'title1'];
var attribute_name;
var relevant_content = '';
for ( var index in attributes ) {
attribute_name = attributes[ index ];
if ( data._highlightResult[ attribute_name ].matchedWords.length > 0 ) {
relevant_content = data._snippetResult[ attribute_name ].value;
break;
} else if( data._snippetResult[ attribute_name ].value !== '' ) {
relevant_content = data._snippetResult[ attribute_name ].value;
}
}
#>

Related

How to make a check that my entity title field is written to needed database table and that no other field is written there?

I have an entity called Entity Product. And this entity has a form, if you change the Title field in this form, Drupal will automatically save the new value of this field in the appropriate table in the database, but in addition, I also save the change of the Title field in the form to another database table product_product by creating a _custom_product_save_title function. It is necessary. And this function is called in the hook_ENTITY_TYPE_update() which tracks changes in Entity Product.
I need to add a check to see if the title is saved and if other fields are not saved. Please tell me what such a check should look like and where exactly should it be in the code?
function _custom_product_save_title($custom_product_id, $entity_product_title) {
if (isset($fields['url']) && $fields['url'] == '') {
if (isset($fields['name'])) {
$fields['url'] = strtolower(str_replace(' ', '-', $fields['name']));
}
}
$id = $form_state->getValue('cid');
if (!empty($form_state->getValue('cid'))) {
$query = $this->connection->update($this->getTableName())
->condition('cid', $form_state->getValue('cid'));
}
else {
$query = $this->connection->insert($this->getTableName());
}
$result = $query
->fields($fields)
->execute();
if (!$id) {
$id = $result;
}
Cache::invalidateTags([
"product:" . $form_state->getValue('cid'),
]);
Cache::invalidateTags([
"product:$custom_product_id",
]);
if (!$custom_product_id) {
Cache::invalidateTags([
"product_list",
]);
}
}
/**
* Implements hook_ENTITY_TYPE_update().
*/
function product_admin_node_update(\Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->bundle() == 'product') {
$custom_product_id = $entity->get('field_product_cid')->value;
$entity_product_title = $entity->getTitle();
_custom_product_save_title($custom_product_id, $entity_product_title);
}
}
After debugging the code using xdebug, I see the following structure of what comes in the standard argument $entity of the hook:
$entity
fields
field_product_cid
field_second
.....
title
x-default
list
0
values
value = “My title”

WordPress - Gravity Forms: How to add a "confirm phone number" field

If you are familiar with WordPress Gravity Forms then you know that can add a "Phone" field from the advanced fields options. That's great but I am working on a site that offers a service to mobile users so I need make sure that the person filling out the form does so twice (in two fields) to ensure that there isn't a typo in their mobile number entered. I've been looking everywhere and can't figure out how to do this.
This code from http://gravitywiz.com/custom-field-confirmation/ worked perfectly for me. There are more detailed instructions on their site.
Paste this into your functions.php file and change register_confirmation_fields(8, array(1, 2)); to suit your form.
/**
* Double Confirmation Fields
* http://gravitywiz.com/2012/05/01/custom-field-confirmation/
*/
register_confirmation_fields(8, array(1, 2));
add_filter('gform_validation', 'gfcf_validation');
function gfcf_validation($validation_result) {
global $gfcf_fields;
$form = $validation_result['form'];
$confirm_error = false;
if(!isset($gfcf_fields[$form['id']]))
return $validation_result;
foreach($gfcf_fields[$form['id']] as $confirm_fields) {
$values = array();
// loop through form fields and gather all field values for current set of confirm fields
foreach($form['fields'] as $field) {
if(!in_array($field['id'], $confirm_fields))
continue;
$values[] = rgpost("input_{$field['id']}");
}
// filter out unique values, if greater than 1, a value was different
if(count(array_unique($values)) <= 1)
continue;
$confirm_error = true;
foreach($form['fields'] as &$field) {
if(!in_array($field['id'], $confirm_fields))
continue;
// fix to remove phone format instruction
if(RGFormsModel::get_input_type($field) == 'phone')
$field['phoneFormat'] = '';
$field['failed_validation'] = true;
$field['validation_message'] = 'Your values do not match.';
}
}
$validation_result['form'] = $form;
$validation_result['is_valid'] = !$validation_result['is_valid'] ? false : !$confirm_error;
return $validation_result;
}
function register_confirmation_fields($form_id, $fields) {
global $gfcf_fields;
if(!$gfcf_fields)
$gfcf_fields = array();
if(!isset($gfcf_fields[$form_id]))
$gfcf_fields[$form_id] = array();
$gfcf_fields[$form_id][] = $fields;
}
// register field IDs 1 and 2 on form ID 8
register_confirmation_fields(8, array(1, 2));

Get gravity forms fields

I am using the gravity form on my site. I am working on create the custom report for this I have need gravity form fields name and id based on specific form id.Please let me know how I can do it.
I am using the following function but it is showing all forms info based on it. it is looking very hard to parse it. Please let me know any function so I can get fields name easily.
$forms = RGFormsModel::get_forms_by_id(13);
try this
function get_all_form_fields($form_id){
$form = RGFormsModel::get_form_meta($form_id);
$fields = array();
if(is_array($form["fields"])){
foreach($form["fields"] as $field){
if(isset($field["inputs"]) && is_array($field["inputs"])){
foreach($field["inputs"] as $input)
$fields[] = array($input["id"], GFCommon::get_label($field, $input["id"]));
}
else if(!rgar($field, 'displayOnly')){
$fields[] = array($field["id"], GFCommon::get_label($field));
}
}
}
//echo "<pre>";
//print_r($fields);
//echo "</pre>";
return $fields;
}
It's not that hard to parse:
$fields=array();
foreach ( $forms['fields'] as $field ) {
$fields[]=array($field['id'] => $field['inputName']);
}
P.S. I'm assuming you use Gravity Forms < 1.7 as RGFormsModel::get_forms_by_id is a deprecated function since 1.7
// Get the Form fields
$form = RGFormsModel::get_form_meta($form_id);
// Run through the fields to grab an object of the desired field
$field = RGFormsModel::get_field( $form, $field_id );
I use the above to get a specific field I want to filter the value of. The $field contains an object with all the properties you want.
echo $field->label // Gets the label
echo $field->inputName // Gets the name
echo $field->type // Gets the type
echo $field->cssClass // Gets the CSS Classes as a string
You are able to get the entered value/content of a field by using rgpost() and by referencing the id ($field->id).
// Check the entered value of every field
foreach( $form['fields'] as &$field ) {
// Get the content for the specific field
$fieldContent = rgpost( "input_".$field->id );
// Check the content
if ( $fieldContent == ... ){}
}

Generate url aliasing based on taxonomy term

I have a vocab category and four terms within it. what i want to do is if content is tagged with a termin in particular say "term1" to have the url generated as word1/[node:title] and for all the other tags just the standard url formatting.
If i wanted the term in the url obviously id use pattern replacement but i want another word to be used if a particular tag is used
I can't think of an easy plug-and-play way of achieving this. You may have to create your own token for the "Default path pattern" in Pathauto's URL alias settings:
/**
* Implementation of hook_token_info().
*/
function MODULE_token_info() {
$info['tokens']['node']['node-term-path'] = array(
'name' => t('Node path by term'),
'description' => t('The path to a node based on its taxonomy terms.'),
);
return $info;
}
/**
* Implementation of hook_tokens().
*/
function MODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
$replacements = array();
if ($type == 'node' && !empty($data['node'])) {
$node = $data['node'];
foreach ($tokens as $name => $original) {
switch ($name) {
case 'node-term-path':
$items = field_get_items('node', $node, 'TAXONOMY_FIELD_NAME');
foreach ($items as $item) {
$tids[] = $item['tid'];
}
if (in_array(TID_OF_TERM1, $tids)) {
// Path for nodes with term1
$replacements[$original] = 'word1/'. pathauto_cleanstring($node->title);
}
else {
// Path for other nodes
$replacements[$original] = 'content/'. pathauto_cleanstring($node->title);
}
break;
}
}
}
return $replacements;
}
Found a simple way actually to anyone who need a similar solution use the module Entity Reference.
http://drupal.org/project/entityreference
I just created a new field for the user account select entity reference then you can choose any entity within drupal to reference.
(ie so you can select a term/content/anything)

wordpress contact form 7 unique id

i am currently using contact form 7 for wordpress. i would like a unique id for every form filled in and sent.
i have had a look around the internet but cant find anything, although i did find the following:
http://contactform7.com/special-mail-tags/
would there be any easy way to make my own function to do something similar to the above tags? i would need it to be a function to go into my themes function file, so that plugin updates wont affect it.
Cheers Dan
[_serial_number] field is an auto-incremented form submission ID. You just have to have Flamingo plugin installed as well. See http://contactform7.com/special-mail-tags/
(It's the same link as in the question, I guess the field wasn't there when the question was asked).
To generate ID for the Contactform7 you need to hook the 'wpcf7_posted_data'.
However, to generate incremental ID you need to save the forms in database so you can retrieve which ID should be next on next Form submit. For this you will need CFDB plugin (https://cfdbplugin.com/).
If you dont want to put the code inside theme functions.php file, you can use this plugin instead: https://wordpress.org/plugins/add-actions-and-filters/
Example code:
function pk_generate_ID($formName, $fieldName) {
//Retrieve highest ID from all records for given form stored by CFDB, increment by 1 and return.
require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBFormIterator.php');
$start = '001';
$exp = new CFDBFormIterator();
$atts = array();
$atts['show'] = $fieldName;
$atts['filter'] = "$fieldName>=$start&&$fieldName<999999999999"; //is_numeric() is not permitted by default for CFDB filter
$atts['limit'] = '1';
$atts['orderby'] = "$fieldName DESC";
$atts['unbuffered'] = 'true';
$exp->export($formName, $atts);
$found = $start;
while ($row = $exp->nextRow()) {
$row2 = $row[$fieldName];
$row2 += 1;
$found = max($found,$row2);
}
return $found;
}
function pk_modify_data( $posted_data){
$formName = 'Form1'; // change this to your form's name
$fieldName = 'ID-1'; // change this to your field ID name
//Get title of the form from private property.
$cf_sub = (array) WPCF7_Submission::get_instance();
$cf = (array) $cf_sub["\0WPCF7_Submission\0contact_form"];
$title = (string) $cf["\0WPCF7_ContactForm\0title"];
if ( $posted_data && $title == $formName) ) { //formName match
$posted_data[$fieldName] = pk_generate_ID($formName, $fieldName);
}
return $posted_data;
}
add_filter('wpcf7_posted_data', 'pk_modify_data');

Resources