We're merging with GenerateBlocks! Learn more here.

[Support request] How to sort posts by Views Count Descending Order

Please login to receive premium support.

Support for the free plugin can be found here.

Home Forums Pro Support How to sort posts by Views Count Descending Order

Viewing 13 posts - 1 through 13 (of 13 total)
  • Author
    Posts
  • #36394
    Miguel
    Participant

    Hi WPSP Team,

    I’m showing my posts in the sidebar using the WP Show Posts shortcode in side Elements -> Element type -> Right Sidebar, and I need to display my Posts sorted by Views Count in descending order.

    I tried the code below that I found here in the forums, but that code throw this Error –> syntax error, unexpected token “=>”

    add_filter( ‘wp_show_posts_shortcode_args’, function( $args, $settings ) {
    if ( 123 === $settings[‘list_id’] ) {
    $args[‘meta_query’] => array(
    array(
    ‘key’ => ‘post_views_count’,
    ‘orderby’ => ‘meta_value_num’,
    ‘order’ => ‘DESC’,
    )
    );
    }

    return $args;
    } );

    #36396
    elvin
    Moderator

    Hi Miguel,

    There is indeed a syntax error on the site as it uses on some parts where it shouldn’t.

    Let me correct it a bit, try this:

    add_filter( 'wp_show_posts_shortcode_args', function( $args, $settings ) {
        if ( 123 === $settings['list_id'] ) {
            $args['meta_query'] = array(
                array(
                'key' => 'post_views_count',
                'orderby' => 'meta_value_num',
                'order' => 'DESC',
                )
            );
        }
        
        return $args;
    });

    And please don’t forget to change 123 to the WPSP list ID you’re trying to apply this on. 🙂

    • This reply was modified 1 year, 8 months ago by elvin.
    #36398
    Miguel
    Participant

    Hi Elvin, thanks for your kind help.

    Still there is some problem:

    Your PHP code changes were rolled back due to an error on line 138 of file wp-content/plugins/generatepress-custom-code/generatepress-custom-code.php. Please fix and try saving again.

    Uncaught ArgumentCountError: Too few arguments to function {closure}(), 1 passed in wp-includes/class-wp-hook.php on line 303 and exactly 2 expected in wp-content/plugins/generatepress-custom-code/generatepress-custom-code.php:138
    Stack trace:
    #0 wp-includes/class-wp-hook.php(303): {closure}()
    #1 wp-includes/plugin.php(189): WP_Hook->apply_filters()
    #2 wp-content/plugins/wp-show-posts/wp-show-posts.php(383): apply_filters()
    #3 wp-content/plugins/wp-show-posts/wp-show-posts.php(569): wpsp_display()
    #4 wp-includes/shortcodes.php(356): wpsp_shortcode_function()
    #5 [internal function]: do_shortcode_tag()
    #6 wp-includes/shortcodes.php(228): preg_replace_callback()
    #7 wp-content/plugins/gp-premium/elements/elements.php(199): do_shortcode()
    #8 wp-includes/class-wp-hook.php(303): generate_add_block_element_content_filters()
    #9 wp-includes/plugin.php(189): WP_Hook->apply_filters()
    #10 wp-content/plugins/gp-premium/elements/class-elements-helper.php(151): apply_filters()
    #11 wp-content/plugins/gp-premium/elements/class-block.php(404): GeneratePress_Elements_Helper::build_content()
    #12 wp-includes/class-wp-hook.php(303): GeneratePress_Block_Element->build_hook()
    #13 wp-includes/class-wp-hook.php(327): WP_Hook->apply_filters()
    #14 wp-includes/plugin.php(470): WP_Hook->do_action()
    #15 wp-content/themes/generatepress/sidebar.php(20): do_action()
    #16 wp-includes/template.php(770): require_once(‘/home/batidosf/…’)
    #17 wp-includes/template.php(716): load_template()
    #18 wp-includes/general-template.php(136): locate_template()
    #19 wp-content/themes/generatepress/inc/structure/sidebars.php(34): get_sidebar()
    #20 wp-content/themes/generatepress/index.php(80): generate_construct_sidebars()
    #21 wp-includes/template-loader.php(106): include(‘/home/batidosf/…’)
    #22 wp-blog-header.php(19): require_once(‘/home/batidosf/…’)
    #23 index.php(17): require(‘/home/batidosf/…’)
    #24 {main}
    thrown

    For adding the code I’m using the generatepress-custom-code.php file that was created by the plugin “Pluginception”

    Here the corrected code. I’m using the ID from my shortcode –> [wp_show_posts id=”9463″]

    138- add_filter( ‘wp_show_posts_shortcode_args’, function( $args, $settings ) {
    139- if ( 9463 === $settings[‘list_id’] ) {
    140- $args[‘meta_query’] = array(
    141- array(
    142- ‘key’ => ‘post_views_count’,
    143- ‘orderby’ => ‘meta_value_num’,
    144- ‘order’ => ‘DESC’,
    145- )
    146- );
    147- }
    148-
    149- return $args;
    150- });

    #36400
    elvin
    Moderator

    Ah I see,

    I assumed you did the necessary changes to the plugin’s code for this filter to work.

    The Uncaught ArgumentCountError: Too few arguments to function error is because the current official release takes only 1 arg for thewp_show_posts_shortcode_args filter.

    For it to take 2 arguments, you’ll have to do Tom’s instructions here – https://wpshowposts.com/support/topic/can-i-exclude-with-a-custom-meta-field-from-a-list/#post-13344

    #36403
    Miguel
    Participant

    Hi Elvin, I have just changed the line 383 from the wp-show-posts.php file as indicated by Tom in this link –> https://wpshowposts.com/support/topic/can-i-exclude-with-a-custom-meta-field-from-a-list/#post-13344

    But Still I don’t get my Posts sorted by the number of Posts Views. Let me explain:

    Just after that change in the wp-show-posts.php file, I still got this error –> Uncaught ArgumentCountError: Too few arguments to function {closure}(), 1 passed in wp-includes/class-wp-hook.php on line 303 and exactly 2 expected in wp-content/plugins/generatepress-custom-code/generatepress-custom-code.php:138

    But I was able to fix the “Uncaught ArgumentCountError:” error in this way –> I searched some examples in the forum and I found that you sometimes you add the number “10,2” at the end of the add_filter PHP snippet -> “},10,2);”

    So I added it to the PHP snippet you provided above and now I have this below and the “Uncaught ArgumentCountError: Too few arguments to function {closure}(),……” Error is gone.

    add_filter( ‘wp_show_posts_shortcode_args’, function( $args, $settings ) {
    if ( 9463 === $settings[‘list_id’] ) {
    $args[‘meta_query’] = array(
    array(
    ‘key’ => ‘post_views_count’,
    ‘orderby’ => ‘meta_value_num’,
    ‘order’ => ‘DESC’,
    )
    );
    }

    return $args;
    },10,2);

    Now, my issue is that in my Sidebar using the shortcode [wp_show_posts id=”9463″] I get this message –> Sorry, no posts were found.

    I’m Not a developer but I think that there is probably some other code that I have to add in the GeneratePress “functions.php” file or something like that. I don’t know.

    Would be awesome if you try to make this work on your own Testing website and let me know if you can get this working. Thank You in advance for your kind help. Hopefully we can get this working 🙂

    #36405
    elvin
    Moderator

    Is it solely for sorting the posts?

    If it’s solely for sorting the posts then I think what you need is $args[‘orderby’] and $args[‘order’].

    add_filter( ‘wp_show_posts_shortcode_args’, function( $args, $settings ) {
    if ( 9463 === $settings[‘list_id’] ) {
    $args[‘orderby’] = 'meta_value_num';
    $args['meta_key'] = 'post_views_count';
    $args['order'] = 'DESC';
    
    return $args;
    },10,2);

    Use this parameter as reference – https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters

    #36406
    Miguel
    Participant

    Hi Kevin, the new PHP code snippet does Not work. So, I prepared for you a super simple testing website with all the things needed so that you can easily check what is really happening:

    1- All the PHP code snippets are here –> Plugins -> Plugin Editor -> generatepress-custom-code.php

    2- The sidebar with “GP Elements” is there already created

    3- The WP Show Posts List is there already created

    (credentials removed for security purposes)

    Thanks in advance for your help 🙂

    • This reply was modified 1 year, 8 months ago by elvin.
    #36409
    elvin
    Moderator

    Ah I see why the code wasn’t working.

    This code assumes your posts already have a post_views_count meta on them. I’ve checked the site and the posts doesn’t have this meta.

    The post counting meta is something you’ll have to apply to the posts. It’s not something WP Show Posts automatically adds.

    You’ll either need a plugin for that or create the custom functionality for it.

    #36410
    Miguel
    Participant

    Thank Elvin. I will try some custom codes like these below to see if I can get this thing working:

    https://gretathemes.com/count-post-views/
    https://techsolutionshere.com/how-to-display-post-views-in-your-wordpress-post/
    https://instance-factory.com/?p=1598

    Would be awesome if some day Tom decides to add this simple option( in More settings -> Order by) to the WP Show Post Block when ported to GenerateBlocks. This will make your plugin more polyvalent and useful.

    All the Best.

    #36412
    elvin
    Moderator

    Would be awesome if some day Tom decides to add this simple option( in More settings -> Order by) to the WP Show Post Block when ported to GenerateBlocks. This will make your plugin more polyvalent and useful.

    Now may be a good time to suggest a feature since Tom’s in the process of merging WPSP and GB. Perhaps he can add things in while he’s at it.

    You can raise a feature request here –
    https://community.generateblocks.com/c/feature-requests/6

    And/or here-
    https://github.com/tomusborne/generateblocks

    although I suggest going through the community first so it gets more votes, so Tom finds it something to prioritize. 🙂

    #36413
    Miguel
    Participant

    Hey Elvin, me again. I searched a Lot and test several plugins and the only one that is working great with any cache plugin, thanks to its JavaScript and REST API counter modes is this -> https://wordpress.org/plugins/post-views-counter/

    But there is only one problem. This plugin does Not have a Gutenberg Block, it only has a Widget Block that only appears in the Widgets Area but Not in the Gutenberg Editor.

    Now my question: Have you any idea on how I can use a Widget Block inside the Gutenberg Editor so that I can use it in the “GP Elements -> Right Sidebar as a shortcode” ??

    • This reply was modified 1 year, 8 months ago by Miguel.
    #36419
    Miguel
    Participant

    Hey Elvin, I found the solution in order to use the Block-Based widget from https://wordpress.org/plugins/post-views-counter/ inside the GP Elements Block Editor following this instructions –> https://developer.wordpress.org/block-editor/how-to-guides/widgets/legacy-widget-block/#using-the-legacy-widget-block-in-other-block-editors-advanced

    All the Best.

    #36426
    elvin
    Moderator

    Thanks for letting us know. Glad you got it sorted. 😀

Viewing 13 posts - 1 through 13 (of 13 total)
  • You must be logged in to reply to this topic.