开发者 |
jeffparker
shareaholic |
---|---|
更新时间 | 2021年6月24日 03:29 |
捐献地址: | 去捐款 |
PHP版本: | 5.3 及以上 |
WordPress版本: | 5.7 |
版权: | GPLv2 or later |
Add New
YARPP
YARPP
pluginyarpp-templates
folder into your active theme folder.yet-another-related-posts-plugin
folder to the /wp-content/plugins/
directoryyarpp-templates
folder into your active theme folder.wp plugin install yet-another-related-posts-plugin --activate
yarpp-templates
folder into your active theme folder.yarpp-templates
directory which ships with YARPP into your active theme's main directory. Be sure to move the files (which must be named yarpp-template-
....php
) to your theme, not the entire directory. There is no limit restriction on custom templates.
After Activation
You should customize your Pool, Algorithm and Automatic Display Options settings from the YARPP settings page. YARPP supports a full range of placement options, including Automatic Display Options (pick where to show YARPP from the YARPP settings page), Block, Shortcode, Widget, YARPP functions() and REST API support. Details below.
Automatic Display Options
Configurable from the YARPP settings page, the Automatic Display Option automatically displays YARPP right below post content. You can configure which posts types to display YARPP on from the YARPP settings page.
If you do not want to show the Related Posts display in its default position (right below the post content), first go to YARPP options and turn off the "Automatic Display Options".
If you would like to instead display it in your sidebar and you have a widget-aware theme, YARPP provides a Related Posts widget which you can add under "Appearance" > "Widgets."
If you would like to add Related Posts elsewhere (such as inline related posts), edit your relevant theme file (most likely something like single.php
) and add the shortcode code [yarpp]
or PHP function yarpp_related();
within The Loop where you want to display the related posts. Make sure you don't add echo yarpp_related();
or you may end up with duplicates in your related posts section. The YARPP Block is also an option.
Automatic Display in Feed Options
Make sure the "display related posts in feeds" option is turned on if you would like to show related posts in your RSS and Atom feeds. The "display related posts in feeds" option can be used regardless of whether you auto display them on your website (and vice versa).
Block
YARPP ships with full support for Gutenberg Blocks. You can place YARPP's Block manually wherever you’d like in post content.
Shortcode
You can place YARPP's related posts manually wherever you’d like in post content or theme files.
To add to post content, use the shortcode:
[yarpp]
to show content related to the current post. You may use more than one YARPP shortcode in a given post or template.
If you know the reference Post ID that you want to show content related to, use:
[yarpp reference_id=123]
to show content related to post 123
To specify which YARPP template to use, use the "template" attribute like so:
[yarpp template="yarpp-template-photoblog"]
- where yarpp-template-photoblog.php
is the file name of the custom template
[yarpp template="list"]
- built-in "List" template
[yarpp template="thumbnails"]
- built-in "Thumbnails" template
To specify maximum number of posts to show, use the "limit" attribute like so:
[yarpp template="list" limit=3]
To add YARPP shortcode to your theme files (eg. single.php), use:
<?php echo do_shortcode('[yarpp]'); ?>
<?php echo do_shortcode('[yarpp reference_id=123]'); ?>
If you're adding the shortcode outside the loop, you must provide the reference_id.
Widget
Related posts can also be displayed as a widget. Go to the Appearance > Widgets options page and add the "Related Posts (YARPP)" widget. Choose to display content from YARPP Basic. The widget will only be displayed on single entry (permalink) pages.
The YARPP widget can be used even if the "auto display" option is turned off.
REST API
Add related posts to your JavaScript driven app!
YARPP adds a REST API endpoint for fetching related posts. The JSON results from the REST API query are the same as you would see if you were visiting a post on your website (the same quantity and order). It is possible to override the quantity at the time of making the REST API request.
[Documentation]
YARPP functions()
Developers can call YARPP's powerful relatedness algorithm from anywhere in their own code. Some examples and more details are in this WordCamp Birmingham talk.
You may use the functions defined in includes/related_functions.php
in your own code, notably:
yarpp_related()
- gets the HTML for related posts and displays ityarpp_related_exist()
- checks whether any related posts existsyarpp_get_related()
- returns the list of related posts (WP_Post
objects)<?php yarpp_related(); ?>
Each of these functions will default to using the settings set in your the YARPP settings page, but can be customized. For example:
yarpp_related(
array(
// Pool options: these determine the "pool" of entities which are considered
'post_type' => array('post', 'page', 'wc_product', ...), // post types to include in results
'show_pass_post' => false, // show password-protected posts
'past_only' => false, // show only posts which were published before the reference post
'exclude' => array(), // a list of term_taxonomy_ids. entities with any of these terms will be excluded from consideration.
'recent' => false, // to limit to entries published recently, set to like '15 day', '20 week', or '12 month' (https://www.mysqltutorial.org/mysql-interval/)
// Relatedness algorithm options: these determine how "relatedness" is computed
// Weights are used to construct the "match score" between candidates and the reference post
'weight' => array(
'body' => 1,
'title' => 2, // larger weights mean this criteria will be weighted more heavily
'tax' => array(
'post_tag' => 1,
... // put any taxonomies you want to consider here with their weights
)
),
// Specify taxonomies and a number here to require that a certain number be shared:
'require_tax' => array(
'post_tag' => 1 // for example, this requires all results to have at least one 'post_tag' in common
),
// The threshold which must be met by the "match score" to be considered related
'threshold' => 5,
// Display options:
'template' => 'thumbnails', // which theme/custom template to use. Built-in ones include "list" and "thumbnails", or the name of a YARPP template file in your active theme folder starting with "yarpp-template-". Example: yarpp-template-videos or yarpp-template-videos.php
'limit' => 5, // maximum number of results
'order' => 'score DESC', // column on "wp_posts" to order by, then a space, and whether to order in ascending ("ASC") or descending ("DESC") order
'promote_yarpp' => true, // boolean indicating whether to add 'Powered by YARPP' below related posts
),
$reference_ID, // second argument: (optional) the post ID. If not included, will use the current post.
true // third argument: (optional) true to echo the HTML block; false to return it
);
Options which are not specified will default to those specified on the YARPP settings page. Additionally, if you are using a builtin template rather than specifying a custom template file in template
, the following arguments can be used to override the various parts of the builtin template: before_title
, after_title
, before_post
, after_post
, before_related
, after_related
, no_results
, excerpt_length
.
If you need to implement related entries programmatically or to know whether they exist, you can use the functions:
yarpp_get_related( $args, $reference_ID )
Returns an array of post
objects, just like the WordPress function get_posts
.yarpp_related_exist( $args, $reference_ID )
Returns a boolean for whether any such related entries exist.$args
takes the same arguments as those detailed for yarpp_related()
above, except for the various display and template options.
Note that at this time custom YARPP queries using the functions mentioned here are not cached in the built-in YARPP caching system. Thus, if you notice any performance hits, you may need to write your own code to cache the results.
Example of how to use a custom YARPP query and cache the results for a day:
$result = get_transient('yarpp_custom_results_for_' . $post->ID);
if(! $result){
$result = yarpp_related(['post_type' => 'reply'],null,false);
set_transient('yarpp_custom_results_for_' . $post->ID, $result, DAY_IN_SECONDS);
}
echo $result;
Show at most 4 related WooCommerce products based on their title and especially on their categories, assuming custom YARPP template
yarpp-related-wc-products.php
has been added to the active theme folder:
yarpp_related(
array(
'limit' => 4,
'weight' => array(
'title' => 1,
'tax' => array(
'category' => 2
)
),
'post_type' => 'wc_product',
'template' => 'yarpp-related-wc-products.php'
)
);
Check for posts related to post with ID 123, and loop through them in order to do some more custom logic:
$related_posts = yarpp_get_related(array(), 123);
if(! $related_posts){
echo 'No related posts';
} else {
foreach($related_posts as $post){
// $post is a WP_Post object.
echo $post->post_title;
}
}
If your question isn't here, ask your own question at the WordPress.org forums. Most likely you have "no related posts" right now because the default "match threshold" is too high. Here's what we recommend to find an appropriate match threshold: lower your match threshold in the YARPP "Algorithm" options to something very low, like 1. (If you don't see the match threshold, you may need to display the "Algorithm" options via the "Screen Options" tab at the top.) Most likely the really low threshold will pull up many posts that aren't actually related (false positives), so look at some of your posts' related posts and their match scores. This will help you find an appropriate threshold. You want it lower than what you have now, but high enough so it doesn't have many false positives.
In Wordpress, go to "Settings" and "Related Posts (YARPP)" and make sure "The Pool" is checked in the "Screen Options" section at the top of the page. In "The Pool" section, check the box next to "Show only posts from the past X months."
In WordPress, go to "Settings" and "YARPP" and make sure "Algorithm" is checked in the "Screen Options" section at the top of the page. In the "Algorithm" section, configure the dropdown boxes next to "Titles," "Bodies," "Categories," and "Tags."
Sorry, but specifying related posts, displaying related posts from external WordPress sites, and pulling content from the Comments section are all outside the scope of YARPP at this time.
Some WordPress themes treat the home page as an archive or a "page." Go to "Settings" then "Related Posts (YARPP)" and view the "Automatic Display Options" section. Make sure "Pages" and "Also display in archives" are not checked.
Option 1:
On the edit post page, uncheck “Display Related Posts” in the YARPP box. Be sure to update or publish to save your changes.
Option 2:
Add <?noyarpp-->
to the HTML code of any post to prevent related posts from displaying.
Option 3:
Use the noyarpp
filter. For example:
// Disable YARPP Automatic Display in specific categories
function yarpp_disable_categories() {
// Examples of in_category usage: https://codex.wordpress.org/Function_Reference/in_category
if ( in_category( array( 'my_category_1_slug', 'my_category_2_slug' ) ) ) {
return true;
}
}
add_filter( 'noyarpp', 'yarpp_disable_categories' );
These solutions only work if you are using "Automatic Display" in the "Display Options" section. If you are programatically calling yarpp_related()
, the shortcode [yarpp]
from PHP code or the YARPP Block, you will need to do your own conditional checks.
If you're familiar with CSS, you can override any YARPP styles by editing your theme's style.css
file, or any other CSS file you may have created that loads after the YARPP one. To edit your theme's CSS file, go to "Appearance" then "Editor" and then click style.css
in the right sidebar. Add changes at the bottom of the file and click "Save." If you do edit this file, just make sure you add !important
after each style declaration, to make sure they'll override the YARPP rules.
Some common overrides that YARPP users have added are:
/ Reduces the title font size and displays more than two title lines /
.yarpp-thumbnail {height: 200px !important;}
.yarpp-thumbnail-title {font-size:0.8em !important; max-height: 4em !important}
/ Centers the thumbnail section /
.yarpp-related-widget {text-align:center !important;}
Once you save any CSS changes, empty your browser's cache and reload your page to see the effect.
As of YARPP v5.19.0, YARPP usually defaults to using WordPress' default thumbnail size. This can be changed to another thumbnail size using the YARPP setting "Thumbnail Size".
However, if you used YARPP before v5.19.0, or your theme defines a "yarpp-thumbnail" size, the default is the "yarpp-thumbnail". To change "yarpp-thumbnail" size, add the following to your theme's functions.php
file with appropriate width and height variables:
add_image_size('yarpp-thumbnail', $width, $height, true);
When you do this, make sure you also set the YARPP setting "Thumbnail Size" to "yarpp-thumbnail".
Each time you change YARPP's thumbnail dimensions like this, you will probably want to have WordPress regenerate appropriate sized thumbnails for all of your images. We highly recommend the Regenerate Thumbnails plugin for this purpose.
By default, if an appropriately sized thumbnail is not available in WordPress, a larger image will be served and will be made to fit in the thumbnail space via CSS. Sometimes this means images will be scaled down in a weird way, so it is not ideal. What you really want is for YARPP to serve appropriately-sized thumbnails. There are two options for doing so:
define('YARPP_GENERATE_THUMBNAILS', true);
to your theme's functions.php
file.YARPP's thumbnail view requires that a WordPress "featured image" be set for each post. If you have many posts that never had a featured image set, we recommend the plugin Auto Post Thumbnail, which will generate post thumbnails for you.
YARPP should work fine in a multisite environment, and many users are running it without any issues using WordPress Multisite. It will, however, only get results within each blog. It will not display related posts results from across your network.
The recommended solution in such cases is to use the Polylang plugin. Polylang has posted a tutorial for using YARPP with Polylang.
YARPP works fine with full-width (double-byte) characters, assuming your WordPress database is set up with Unicode support. 99% of the time, if you're able to write blog posts with full-width characters and they're displayed correctly, YARPP will work on your blog. However, YARPP does have difficulty with languages that don't place spaces between words (Chinese, Japanese, etc.). For these languages, the "consider body" and "consider titles" options in the "Algorithm options" may not be very helpful. Using only tags and categories may work better for these languages.
YARPP is a highly optimized plugin with an inbuilt cache that makes subsequent queries super efficient. This means that YARPP will not slow your site down. If you are running a large site and need to throttle YARPP's computation, try the official YARPP Experiments plugin which adds this throttling functionality.
Before upgrading to a new WordPress version, you should first deactivate all plugins, then upgrade your WordPress, and then reactivate your plugins. Even then, you may still find that something went wrong with your YARPP functionality. If so, try these steps:
Yes, there is a button to clear YARPP's cache table in YARPP's WP Admin options.
To make YARPP support your Custom Post Type (CPT), the attribute yarpp_support
must be set to true when the CPT is registered. The CPT will then be available in the YARPP settings page.
'yarpp_support' => true
For example:
function register_my_cpt() {
$args = array(
'public' => true,
'label' => 'Books',
'yarpp_support' => true,
);
register_post_type( 'book', $args );
}
add_action( 'init', 'register_my_cpt' );
If you do not have access to the code which is registering the CPT, maybe because it is a third-party plugin that is creating it, you can still add the yarpp_support
argument:
/*
* Filter the CPT to register more options
*
* @param $args array The original CPT args.
* @param $post_type string The CPT slug.
*
* @return array
/
function add_yarpp_support_to_post_types( $args, $post_type ) {
// If not our target CPT, exit.
if ( 'my_custom_post_type' !== $post_type ) {
return $args;
}
// Add additional YARPP support option.
$cpt_args = array(
'yarpp_support' => true
);
// Merge args together.
return array_merge( $args, $cpt_args );
}
add_filter( 'register_post_type_args', 'add_yarpp_support_to_post_types', 10, 2 );
You should replace my_custom_post_type
with the CPT that you need to add YARPP support to and add this code to the functions.php
of your theme.
If you would like to programmatically control which post types are considered in an automatically-displayed related posts display, use the yarpp_map_post_types
filter.
Yes. Any taxonomy, including custom taxonomies, may be specified in the weight
or require_tax
arguments in a custom display as above. term_taxonomy_id
specified in the exclude
argument may be of any taxonomy.
If you would like to choose custom taxonomies to choose in the YARPP settings UI, either to exclude certain terms or to consider them in the relatedness formula via the UI, the taxonomy must (a) have either the show_ui
or yarpp_support
attribute set to true and (b) must apply to either the post types post
or page
or both.
If you want to prevent the Review Notice from appearing you can use the function below:
/*
* Disable YARPP Review Notice
*
/
function yarpp_disable_review_notice() {
remove_action('admin_notices', array('YARPP_Admin', 'display_review_notice'));
}
add_action('admin_init', 'yarpp_disable_review_notice', 11);
Sure. Use the following code:
add_action(
'admin_init',
function(){
remove_all_filters('shareaholic_deactivate_feedback_form_plugins');
},
11
);
Beginning with version 4.0.7, YARPP includes clean uninstall functionality. If you no longer wish to use YARPP, first deactivate YARPP using the "Plugins" page in WordPress, then click the "Delete" link found on the same page. This process will automatically remove all YARPP-related files, including temp tables. If you manually try to remove YARPP files instead of going through WordPress, some files or temp tables could remain.
noyarpp
. For example: add_filter( 'noyarpp', 'custom_function' );
strpos()
instead of stristr()
[yarpp template="list" limit=3]
// maximum post limit set to 3wp_parse_list
exists for backwards compatibility to older versions of WordPressyarpp_related
. Resolves bug with yarpp_function
not fully accounting for all parameters passed to it.[yarpp template="yarpp-template-simple"]
// where yarpp-template-simple.php
is the file name of the custom YARPP template in your active theme folder[yarpp template="list"]
// built-in "List" template[yarpp template="thumbnails"]
// built-in "Thumbnails" templatediv
with classes yarpp
, yarpp-related
and yarpp-template-TEMPLATE-NAME
to facilitate easier CSS customizationsyarpp_meta
postmeta is protected to prevent themes from displaying itwp_get_additional_image_sizes
exists for backwards compatibility to older versions of WordPressjoin
warning (Part 2/2)add_filter( 'yarpp_enqueue_related_style', '_\_return_false' );
join
warning (Part 1/2)`$post_types
[yarpp template="yarpp-template-photoblog"]
related_posts()
, related_pages()
and related_entries() [use
yarpp_related() instead`]related_posts_exist()
, related_pages_exist()
and related_entries_exist()
[use yarpp_related_exist()
instead]YARPP::maybe_enqueue_thumbnails()
and YARPP::enqueue_thumbnails()
[yarpp]
shortcode from a theme file (like single.php) or post contentapply_filters('the_content'...)
gets called again, don't try to re-add YARPP's content to the post again.reference_id
parameter support for the YARPP shortcode. For example: [yarpp reference_id=123]
to show content related to Post ID 123 (can be used either inside or outside the loop from theme code)WPDB->prepare
everywhere possible and related improvements[yarpp]
(documentation)the_content
, the_content_feed
and the_excerpt_rss
, example: add_filter('yarpp_content_priority', 1);
mk_MK
) localization by WPdiscounts.<!--noyarpp-->
by request.yarpp_related_exist()
type functions were causing errors.yarpp-template-wpml.php
is now called yarpp-template-multilingual.php
, following discussion with the author of the Polylang plugin.est_EST
) by journal24.infogu_IN
) by Vikas Arora of wiznicworld.comyarpp_results
sl_SI
) localization by Silvo Katalenić$post
global after YARPP is now more robust. Fixes the display of incorrect metadata on some complex themes.Template Name
fields in their headers, instead using YARPP Template
. This is to avoid confusion with regular page templates.yarpp-thumbnail
styles-thumbnails.php
stylesyarpp-related-
with a stray hyphen was sometimes being produced. Now fixed so it produces yarpp-related
.term_relationships
table was being joined when unnecessaryyarpp_map_post_types
filter now also applies to feeds and takes an extra argument to know whether the context is website
or rss
.related_posts_exist()
and get_related()
without explicit reference ID parameter would incorrectly return no related posts.div
with class yarpp-related
, yarpp-related-widget
, or yarpp-related-rss
as appropriate (by request). If there are no results, a yarpp-related-none
class is added.YARPP Template
, Description
, Author
, Author URI
, in the same format as plugin and theme file headers. See bundled templates for examples.div
s rather than table
s!h3
instead of p
yarpp_map_post_types
filter to programmatically specify what post types should be looked at for automatic displayszh_TW
) localization by Pserichr
) localization by gocroatia.comstats
method to YARPP_Cache_*
objects.screen_option
hook. Improves performance on admin pages.false
and removed FAQ text, as it no longer improves performance much.delete_post
hook receives relevant post ID informationenforce
method which will activate if it's a new install, or else upgrade if necessary. (Part of the fix for the network activation above.)table
YARPP cache method and a persistent object caching system, like W3 Total Cache or memcachedget_post_types()
failed in ajax displaycs_CZ
) localization by Zdenek Hejlsr_RS
) by Zarko Zivkovicereg_replace
clear_pre
function which has been deprecated since WordPress 3.4.$yarpp->get_post_types()
to return array of names by defaultweight
, template
, recent
parameters in options and in optional argsterm_taxonomy_id
s instead of term_id
srelated_*()
and yarpp_related()
function signatures.protect
the sql
method as it shouldn't be public
wp_list_pluck()
YARPP_EXTRA_WEIGHT
to define the "extra weight." By default, it's 3.sk_SK
) localization by Forexro_RO
) localization by Uhren Shopit_IT
, ko_KR
, fr_FR
, sv_SE
, ja
localizationswp_posts
table.yarpp-template-random.php
example template fileset_charset
method.global $post
access to custom templatesjoin_filter
on bypass cachepost_type
argrelated_*
functionssv_SE
, ko_KR
, fr_FR
localizations$yarpp
of class YARPP
; references to the global $yarpp_cache
should now be to global $yarpp->cache
yarpp
option (except yarpp_version
)YARPP_Cache_Postmeta
YARPP_Cache
abstract classget_terms
to load termsyarpp_get_related()
function can be used similar to get_posts()
it_IT
localizationinit
action, for compatibility with WPMLglob
sblog_charset
sit_IT
)hu_HU
) by daSSadkk_KZ
) by DachaDecorgb_IR
) by Ray Grenrelated_*()
results across post typesde_DE
German localization filespt_PT
Portuguese localization fileses_ES
Spanish localization by Rene of WordPress Webshopge_KA
Georgian by Kasia Ciszewski of Find My Hostingcs_CZ
) overused words list by bernieczpost_status
transitions.yarpp_related_exists()
yarpp_upgrade_check()
callingyarpp_version_json()
, including caching and minor security fixpostmeta
table instead. To use postmeta
caching, add define('YARPP_CACHE_TYPE', 'postmeta');
to your wp-config.php
file.bg_BG
) by Flash Galleryfa_IR
) by Moshen Derakhshanid_ID
) by Hendry Lee of Kelayangnb_NO
) by Tom Arne Sundtjønnpt_PT
) by Stefan Muellerlt_LT
) by Mantas Malciusar
) by ledarray_key
.get_site_option
s to get_option
s, so that individual site options can be maintained.tr_TR
)strip_tags()
errors.ar_EG
)lv_LV
)related_posts_exist
was giving incorrect valuesinclude
and require
pathsyarpp_clear_cache
bug on empty inputyarpp_settings_link
dependency when disabled.compare_version
code.compare_version
in lieu of old hacky versioning.is_single
and other such flags are now set properly within the related posts Loop (as a result, now compatible with WP Greet Box)wp_html_excerpt
(for WP 2.5+)ru_RU
) localization by Marat Latypovwp_
prefix on tablesinclude
PHP error was displayed.related_*()
functions were missing the echo
parameterja
) by Michael Yoshitaka Erlewinembstring
title
attributes were not properly escapedzh_CN
) by Jor Wang (mail at jorwang dot com) of jorwang.comde_DE
) by Michael Kalina of 3th.ben
words of the excerpt, rather than the content (by request)echo
parameter to the related_*()
functions, with default value of true
. If false
, the function will simply return the output.&yarpp_debug=1
to your URL's and look at the HTML source.related_posts()
functions.related_*_exist()
functions produced invalid querieswp_posts
with non-MyISAM engines and semi-compatibility with non-MyISAM setups.wp_posts
)user_level
was being checked in a deprecated mannerapply_filters
to work with WP 2.6admin_menu
instead of admin_head
yet-another-related-posts-plugin
apply_filters
to apply whatever content text transformation you use (Wikipedia link, Markdown, etc.) before computing similarity.