• Hi,

    Actually, related posts are based on post title (and post content eventually).
    I’d like to know if it’s possible to display related posts with another criteria.
    In my postmeta database table, i’ve got a meta_key name “_yoast_wpseo_focuskw” and i’d like to choose this criteria to find related posts (with same value in the meta_value field) .
    In the php code, this “_yoast_wpseo_focuskw” value has the id “snippet_title”.

    Is this possible to do what i want by changing your plugin php code ? And which file must be change ?
    Thanks for your help.

    https://wordpress.org/plugins/contextual-related-posts/

Viewing 15 replies - 1 through 15 (of 17 total)
  • Plugin Author WebberZone

    (@webberzone)

    Please see this gist for a code you could potentially add to your theme’s functions.php

    It’s for another plugin I author (Better Search) and uses a meta field and value.

    https://gist.github.com/ajaydsouza/767215093a24bafb903a

    You’ll need to test by changing bsearch_ to crp_ and use the appropriate fields for Yoast as you have above.

    Thread Starter guenfood

    (@guenfood)

    Hi,

    Thanks for your answer.
    When you say “use the appropriate fields for Yoast”, it’s on this line ?
    AND ( $wpdb->postmeta.meta_key = '_visibility' AND $wpdb->postmeta.meta_value = 'visible' )

    I have to change _visibility by _yoast_wpseo_focuskw but what i have to set instead of “visible” for meta_value ?

    I have for each post ID a _yoast_wpseo_focuskw meta_key but i can have the same meta_value for several post ID.
    I want to display on a post, all posts (in a specific category) with the same meta_value.

    Plugin Author WebberZone

    (@webberzone)

    Would it be: “snippet_title” for the value?

    e.g. in the above case, there were multiple meta_key entries for _visibility and I only wanted the ones which had the value visible.

    You’ll need to see which would be the case for the yoast focus keyword.

    Thread Starter guenfood

    (@guenfood)

    Value must be same values that the actually post.

    Example : on my post, i’ve got the yoast_wpseo_focuskw which is “toto”. I want as related posts all post ID in category “book” where yoast_wpseo_focuskw is “toto”.

    Plugin Author WebberZone

    (@webberzone)

    I don’t know how yoast works behind the scenes for the meta-tables when it comes to focus keywords. It’s something I’ll need to spend some time digging into.

    I’d expect this to be similar to yoast where you have the meta_key and meta_value

    For the same category, you might want to install the CRP Taxonomy addon

    Thread Starter guenfood

    (@guenfood)

    Ok.
    I know what i want to do but not how to do.

    Here AND ( $wpdb->postmeta.meta_key = '_yoast_wpseo_focuskw' AND $wpdb->postmeta.meta_value = 'visible' ) i have just to change “= visible” by = the post.ID postmeta.meta_value.
    Just don’t know how to write it.

    Plugin Author WebberZone

    (@webberzone)

    Can you get into the meta tables in there which has _yoast_wpseo_focuskw.

    You should find the meta_key and meta_value entries in there.

    The part of the code might be something like this:

    function crp_bsearch_posts_where( $where ) {
    	global $wpdb, $post;
    	$string = WPSEO_Meta::get_value( 'focuskw', $post->ID );
    
    	return $where . "
    		AND ( $wpdb->postmeta.meta_key = '_yoast_wpseo_focuskw' AND $wpdb->postmeta.meta_value = {$string} )
    	";
    }
    add_filter( 'crp_posts_where', 'filter_crp_posts_where' );
    Thread Starter guenfood

    (@guenfood)

    I tried but i’ve got php error messages.
    So, i’m going to try another thing.

    Is it possible to find related posts where post_title are exactly the same as the post display ?

    Example : I open a post in my browser where post_title is “Best wordpress theme” and i want to display only related posts with exactly the same post_title “Best wordpress theme”.

    I set 0 in the “Limit content to be compared” field, but it doesn’t work.
    Maybe a change in php file ?

    Plugin Author WebberZone

    (@webberzone)

    It would prioritise the three keywords, but it would never be able to return only those since it doesn’t match exactly but approximately.

    What PHP error did you get?

    Thread Starter guenfood

    (@guenfood)

    As you can see in this page, post title is “Quand les gens tombent”.

    Related posts are display in the sidebar under “LES CHRONIQUES”.
    And these posts aren’t in relation with post.
    http://www.livresque-du-noir.fr/quand-les-anges-tombent/

    Plugin Author WebberZone

    (@webberzone)

    I don’t know the language, but I can see the lack of relation. Are the posts better without the extra piece of code?

    Thread Starter guenfood

    (@guenfood)

    No. I had delete the extra piece of code.

    In my example, post-title “Quand les anges tombent” can be translate as “When angels fall”.
    And related posts found by the plugin are “I hear the noise of the wings which fall” and “Torn off wings of the angels

    Plugin Author WebberZone

    (@webberzone)

    I’m not sure as to what the solution would be. What was the error you got with the piece of code?

    Thread Starter guenfood

    (@guenfood)

    Here is a php code that a guy made which can only display related posts with same post title.
    It just display related posts but without links, thumbnails, author…
    Maybe it’s possible to use a part of this code with yours ?

    <?php
    /*
    Plugin Name: WPSE Get Duplicate Post Titles
    Plugin URI:  http://wordpress.stackexchange.com/q/220279/31545
    Description: Displays posts with the same title in the sidear
    Version:     1.0.0
    Author:      Pieter Goosen
    Author URI:  http://wordpress.stackexchange.com/users/31545/pieter-goosen
    License:     GPL2
    License URI: https://www.gnu.org/licenses/gpl-2.0.html
    */
    
    add_filter( 'posts_where', function ( $where, $q ) use ( &$wpdb )
    {
        // Get the value from our new wpse_title_match query var
        $title_match = $q->get( 'wpse_title_match' );
    
        // Make sure we have a value, if not, bail
        if ( !$title_match )
            return $where;
    
        /**
         * Lets alter the SQL WHERE clause
         *
         * Note, this will be an exact 1 to 1 match, adjust as necessary
         */
        $where .= $wpdb->prepare(
            " AND {$wpdb->posts}.post_title = %s ",
            $title_match
        );
    
        return $where;
    }, 10, 2 );
    
    class WPSE_Get_Duplicate_Post_titles extends WP_Widget
    {
    
        public function __construct()
        {
            parent::__construct(
                'widget_get_duplicate_post_titles',
                _x( 'Post Title duplicates', 'Post Title duplicates' ),
                [ 'description' => __( 'Displays posts which share the same post title.' ) ]
            );
            $this->alt_option_name = 'widget_get_duplicate_post_titles';
    
            add_action( 'save_post',    [$this, 'flush_widget_cache'] );
            add_action( 'deleted_post', [$this, 'flush_widget_cache'] );
            add_action( 'switch_theme', [$this, 'flush_widget_cache'] );
        }
    
        public function widget( $args, $instance )
        {
            $cache = [];
            if ( ! $this->is_preview() ) {
                $cache = wp_cache_get( 'widget_bpfi', 'widget' );
            }
    
            if ( ! is_array( $cache ) ) {
                $cache = [];
            }
    
            if ( ! isset( $args['widget_id'] ) ) {
                $args['widget_id'] = $this->id;
            }
    
            if ( isset( $cache[ $args['widget_id'] ] ) ) {
                echo $cache[ $args['widget_id'] ];
                return;
            }
    
            ob_start();
    
            $title          = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Post Title Duplicates' );
            /** This filter is documented in wp-includes/default-widgets.php */
            $title          = apply_filters( 'widget_title', $title, $instance, $this->id_base );
    
            // ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END
            // First make sure this a single post page
            if ( is_single() ) { // We are on a single page
                // Get the current post object
                $post_object = $GLOBALS['wp_the_query']->get_queried_object();
    
                // Run our query to get the posts with duplicate titles
                $args = [
                    'posts_per_page'   => -1, // Get all posts
                    'post_type'        => 'post',
                    'wpse_title_match' => $post_object->post_title,
                    'post__not_in'     => [$post_object->ID], // Exclude current post
                    'tax_query'        => [
                        [
                            'taxonomy' => 'category',
                            'field'    => 'slug',
                            'terms'    => 'chroniques'
                        ]
                    ],
                    // Any other arguments
                ];
                $loop = new WP_Query( $args );
    
                // Run the loop
                if ( $loop->have_posts() ) {
                    while ( $loop->have_posts() ) {
                        $loop->the_post();
    
                        // Display your posts
                        the_title() . "\n";
    
                    }
                    wp_reset_postdata();
                }
            }
    
            echo $args['after_widget']; 
    
            if ( ! $this->is_preview() ) {
                $cache[ $args['widget_id'] ] = ob_get_flush();
                wp_cache_set( 'widget_bpfi', $cache, 'widget' );
            } else {
                ob_end_flush();
            }
        }
    
        public function update( $new_instance, $old_instance )
        {
            $instance                   = $old_instance;
            $instance['title']          = strip_tags( $new_instance['title'] );
            $this->flush_widget_cache();
    
            $alloptions = wp_cache_get( 'alloptions', 'options' );
            if ( isset($alloptions['widget_get_duplicate_post_titles']) )
                delete_option('widget_get_duplicate_post_titles');
    
            return $instance;
        }
    
        public function flush_widget_cache()
        {
            wp_cache_delete('widget_bpfi', 'widget');
        }
    
        public function form( $instance )
        {
    
            $title      = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
            ?>
    
            <p>
                <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
                <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" />
            </p>
    
        <?php
        }
    
    }
    
    add_action( 'widgets_init', function ()
    {
        register_widget( 'WPSE_Get_Duplicate_Post_titles' );
    });
    
    add_filter( 'sidebars_widgets', function ( $sidebars_widgets )
    {
        // Return our filter when we are on admin screen
        if ( is_admin() )
            return $sidebars_widgets;
    
        // Make sure we are not on the blog page, if we are, bail
        if ( is_single() )
            return $sidebars_widgets;
    
        /**
         * Widget we need to target. This should be the name/id we used to register it
         *
         * EXAMPLE
         *   parent::__construct(
                'widget_get_duplicate_post_titles',
                _x( 'Blog Page Featured Image', 'Blog page featured image' ),
                [ 'description' => __( 'Displays the featured image for the pge set as blog page.' ) ]
            );
         *
         */
        $custom_widget  = 'widget_get_duplicate_post_titles';
    
        // See if our custom widget exists is any sidebar, if so, get the array index
        foreach ( $sidebars_widgets as $sidebars_key=>$sidebars_widget ) {
            // Skip the wp_inactive_widgets set, we do not need them
            if ( $sidebars_key == 'wp_inactive_widgets' )
            continue;
    
            // Only continue our operation if $sidebars_widget are not an empty array
            if ( $sidebars_widget ) {
                foreach ( $sidebars_widget as $k=>$v ) {
    
                    /**
                     * Look for our custom widget, if found, unset it from the $sidebars_widgets array
                     * @see stripos()
                     */
                    if ( stripos( $v, $custom_widget ) !== false )
                        unset( $sidebars_widgets[$sidebars_key][$k] );
                } // endforeach $sidebars_widget
            } // endif $sidebars_widget
        } // endforeach $sidebars_widgets
    
        return $sidebars_widgets;
    });
    Plugin Author WebberZone

    (@webberzone)

    Are you using this code to display your related posts and are looking to filter this further? Or are you using CRP as the base?

Viewing 15 replies - 1 through 15 (of 17 total)
  • The topic ‘Related posts based on other field’ is closed to new replies.