Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue-142: Add option to pull Trending posts #143

Merged
merged 22 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions blocks/query/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@
"OR"
],
"type": "string"
},
"trending": {
"default": false,
"type": "boolean"
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
22 changes: 16 additions & 6 deletions blocks/query/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
RangeControl,
SelectControl,
TextControl,
ToggleControl,
} from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import {
Expand All @@ -22,7 +23,6 @@ import {
import { __, sprintf } from '@wordpress/i18n';
import { addQueryArgs } from '@wordpress/url';

import type { WP_REST_API_Post, WP_REST_API_Posts } from 'wp-types';
import { Template } from '@wordpress/blocks';
import type {
EditProps,
Expand All @@ -44,6 +44,7 @@ interface Window {
wpCurateQueryBlock: {
allowedPostTypes: Array<string>;
allowedTaxonomies: Array<string>;
useParsely: string,
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
};
}

Expand All @@ -69,13 +70,15 @@ export default function Edit({
terms = {},
termRelations = {},
taxRelation = 'AND',
trending = false,
},
setAttributes,
}: EditProps) {
const {
wpCurateQueryBlock: {
allowedPostTypes = [],
allowedTaxonomies = [],
useParsely = 'false',
} = {},
} = (window as any as Window);

Expand Down Expand Up @@ -154,24 +157,22 @@ export default function Edit({
}
const fetchPosts = async () => {
let path = addQueryArgs(
'/wp/v2/posts',
'/wp-curate/v1/posts',
{
search: debouncedSearchTerm,
offset,
type: postTypeString,
status: 'publish',
per_page: 20,
trending,
},
);
path += `&${termQueryArgs}`;

apiFetch({
path,
}).then((response) => {
const postIds: number[] = (response as WP_REST_API_Posts).map(
(post: WP_REST_API_Post) => post.id,
);
setAttributes({ backfillPosts: postIds });
setAttributes({ backfillPosts: response as Array<number> });
});
};
fetchPosts();
Expand All @@ -181,6 +182,7 @@ export default function Edit({
offset,
postTypeString,
availableTaxonomies,
trending,
setAttributes,
]);

Expand Down Expand Up @@ -384,6 +386,14 @@ export default function Edit({
onChange={(next) => setAttributes({ searchTerm: next })}
value={searchTerm}
/>
{ useParsely === 'true' ? (
<ToggleControl
label={__('Show Trending Content from Parsely', 'wp-curate')}
help={__('If enabled, the block will show trending content from Parsely.', 'wp-curate')}
checked={trending}
onChange={(next) => setAttributes({ trending: next })}
/>
) : null }
</PanelBody>
</InspectorControls>

Expand Down
1 change: 1 addition & 0 deletions blocks/query/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ function wp_curate_query_block_init(): void {
[
'allowedPostTypes' => $allowed_post_types,
'allowedTaxonomies' => $allowed_taxonomies,
'useParsely' => apply_filters( 'wp_curate_use_parsely', false ) ? 'true' : 'false',
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
]
);
}
Expand Down
1 change: 1 addition & 0 deletions blocks/query/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ interface EditProps {
[key: string]: string;
};
taxRelation?: string;
trending?: boolean;
};
setAttributes: (attributes: any) => void;
}
Expand Down
2 changes: 1 addition & 1 deletion src/class-plugin-curated-posts.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function with_query_context( array $context, array $attributes, WP_Block_
'no_found_rows' => true,
'offset' => $attributes['offset'] ?? $block_type->attributes['offset']['default'],
'order' => 'DESC',
'orderby' => 'date',
'orderby' => isset( $attributes['trending'] ) ? 'trending' : 'date',
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
'posts_per_page' => $attributes['numberOfPosts'] ?? $block_type->attributes['numberOfPosts']['default'],
'post_status' => 'publish',
'post_type' => $attributes['postTypes'] ?? $block_type->attributes['postTypes']['default'],
Expand Down
54 changes: 54 additions & 0 deletions src/class-trending-post-queries.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php
/**
* Trending_Post_Queries class file
*
* @package wp-type-extensions
*/

namespace Alley\WP\WP_Curate;

use Alley\WP\Types\Post_Queries;
use Alley\WP\Types\Post_Query;
use Alley\WP\Post_Query\WP_Query_Envelope;
use Alley\WP\WP_Curate\Features\Parsely_Support;

/**
* Pull trending posts from Parsely.
*/
final class Trending_Post_Queries implements Post_Queries {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is specific to Parse.ly, then it should be named as such. If it's intended to be a generic trending posts class, then it should be structured so that it supports multiple providers, of which Parse.ly will be the first (and we could add other providers like GA4 later).

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kevinfodness supporting multiple providers was my plan... I kind of figured we would sort out how structure it when we added the second provider.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, we're using named arguments instead of positional ones, this works for me!

/**
* Set up.
*
* @param Post_Queries $origin Post_Queries object.
*/
public function __construct(
private readonly Post_Queries $origin,
) {}

/**
* Query for posts using literal arguments.
*
* @param array<string, mixed> $args The arguments to be used in the query.
* @return Post_Query
*/
public function query( array $args ): Post_Query {
if ( 'trending' === $args['orderby'] ) {
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
$parsely = new Parsely_Support();
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
$trending = $parsely->get_trending_posts( $args );
if ( ! empty( $trending ) ) {
return new WP_Query_Envelope(
new \WP_Query(
[
'post__in' => $trending,
'post_type' => 'any',
'ignore_sticky_posts' => true,
'orderby' => 'post__in',
]
)
);
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
}
}

return $this->origin->query( $args );
}
}
141 changes: 141 additions & 0 deletions src/features/class-parsely-support.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
<?php
/**
* Parsely_Support class file
*
* @package wp-curate
*/

namespace Alley\WP\WP_Curate\Features;

use Alley\WP\Types\Feature;
use Parsely\RemoteAPI\Analytics_Posts_API;

/**
* Add support for Parsely, if the plugin is installed.
*/
final class Parsely_Support implements Feature {
/**
* Set up.
*/
public function __construct() {}

/**
* Boot the feature.
*/
public function boot(): void {
if ( ! class_exists( 'Parsely\Parsely' ) ) {
return;
}
// Elsewhere in the plugin, we'll use $GLOBALS['parsely'], but it is not available here.
$parsely = new \Parsely\Parsely();
// If we don't have the API secret, we can't use the Parsely API.
if ( ! $parsely->api_secret_is_set() ) {
return;
}
add_filter( 'wp_curate_use_parsely', '__return_true' );
add_filter( 'wp_curate_trending_posts_query', [ $this, 'add_parsely_trending_posts_query' ], 10, 2 );
}

/**
* Gets the trending posts from Parsely.
*
* @param array<number> $posts The posts, which should be an empty array.
* @param array<string, mixed> $args The WP_Query args.
* @return array<number> Array of post IDs.
*/
public function add_parsely_trending_posts_query( array $posts, array $args ): array {
$parsely = $GLOBALS['parsely'];
if ( ! $parsely->api_secret_is_set() ) {
return $posts;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is going to be checked again here (which seems sensible), why worry about also checking it in boot()?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dlh01 I want to conditionally run

add_filter( 'wp_curate_use_parsely', '__return_true' );

only if the secret is set, which I'm doing in boot()

$trending_posts = $this->get_trending_posts( $args );
return $trending_posts;
}

/**
* Gets the trending posts from Parsely.
*
* @param array<string, mixed> $args The WP_Query args.
* @return array<number> An array of post IDs.
*/
public function get_trending_posts( array $args ): array {
// TODO: Add failover if we're not on production.
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
/**
* Filter the period start for the Parsely API.
*
* @param string $period_start The period start.
* @return string The period start.
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
*/
$period_start = apply_filters( 'wp_curate_parsely_period_start', '1d' );
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
$parsely_args = [
'limit' => $args['posts_per_page'],
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
'sort' => 'views',
'period_start' => $period_start,
'period_end' => 'now',
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
];
if ( isset( $args['tax_query'] ) && is_array( $args['tax_query'] ) ) {
foreach ( $args['tax_query'] as $tax_query ) {
if ( isset( $tax_query['taxonomy'] ) && 'category' === $tax_query['taxonomy'] ) {
$parsely_args['section'] = implode( ', ', $this->get_slugs_from_term_ids( $tax_query['terms'], $tax_query['taxonomy'] ) );
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
}
if ( isset( $tax_query['taxonomy'] ) && 'post_tag' === $tax_query['taxonomy'] ) {
$parsely_args['tag'] = implode( ', ', $this->get_slugs_from_term_ids( $tax_query['terms'], $tax_query['taxonomy'] ) );
}
}
}
$cache_key = 'parsely_trending_posts_' . md5( wp_json_encode( $parsely_args ) ); // @phpstan-ignore-line - wp_Json_encode not likely to return false.
$ids = wp_cache_get( $cache_key );
if ( false === $ids ) {
$api = new Analytics_Posts_API( $GLOBALS['parsely'] ); // @phpstan-ignore-line
$posts = $api->get_posts_analytics( $parsely_args ); // @phpstan-ignore-line
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
$ids = array_map(
function ( $post ) {
// Check if the metadata contains post_id, if not, use the URL to get the post ID.
$metadata = json_decode( $post['metadata'] ?? '', true );
if ( is_array( $metadata ) && ! empty( $metadata ) && isset( $metadata['post_id'] ) ) {
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
$post_id = intval( $metadata['post_id'] );
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
} elseif ( function_exists( 'wpcom_vip_url_to_postid' ) ) {
$post_id = wpcom_vip_url_to_postid( $post['url'] );
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
} else {
$post_id = url_to_postid( $post['url'] ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.url_to_postid_url_to_postid
}
/**
* Filters the post ID derived from Parsely post object.
*
* @param int $post_id The post ID.
* @param array $post The Parsely post object.
* @return int The post ID.
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
*/
return apply_filters( 'wp_curate_parsely_post_to_post_id', $post_id, $post );
},
$posts
);
wp_cache_set( $cache_key, $ids, '', 10 * MINUTE_IN_SECONDS );
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
}
$ids = array_map( 'intval', $ids ); // @phpstan-ignore-line
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved

return( $ids );
mogmarsh marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Get slugs from term IDs.
*
* @param array<int> $ids The list of term ids.
* @param string $taxonomy The taxonomy.
* @return array<string> The list of term slugs.
*/
private function get_slugs_from_term_ids( $ids, $taxonomy ) {
$terms = array_filter(
array_map(
function ( $id ) use ( $taxonomy ) {
$term = get_term( $id, $taxonomy );
if ( $term instanceof \WP_Term ) {
return $term->slug;
}
},
$ids
)
);
return $terms;
}
}
41 changes: 22 additions & 19 deletions src/features/class-query-block-context.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Alley\WP\Blocks\Parsed_Block;
use Alley\WP\Post_IDs\Used_Post_IDs;
use Alley\WP\Post_Queries\Exclude_Queries;
use Alley\WP\WP_Curate\Trending_Post_Queries;
use Alley\WP\Post_Queries\Variable_Post_Queries;
use Alley\WP\Types\Feature;
use Alley\WP\Types\Post_Queries;
Expand Down Expand Up @@ -73,31 +74,33 @@ public function filter_query_context( $context, $parsed_block, $parent_block ):
origin: new Must_Include_Curated_Posts(
qv: $this->stop_queries_var,
origin: new Plugin_Curated_Posts(
queries: new Variable_Post_Queries(
input: function () use ( $parsed_block ) {
$main_query = $this->main_query->query_object();
queries: new Trending_Post_Queries(
origin: new Variable_Post_Queries(
input: function () use ( $parsed_block ) {
$main_query = $this->main_query->query_object();

if ( isset( $parsed_block['attrs']['deduplication'] ) && 'never' === $parsed_block['attrs']['deduplication'] ) {
return false;
}
if ( isset( $parsed_block['attrs']['deduplication'] ) && 'never' === $parsed_block['attrs']['deduplication'] ) {
return false;
}

if ( true === $main_query->is_singular() || true === $main_query->is_posts_page ) {
$post_level_deduplication = get_post_meta( $main_query->get_queried_object_id(), 'wp_curate_deduplication', true );
if ( true === $main_query->is_singular() || true === $main_query->is_posts_page ) {
$post_level_deduplication = get_post_meta( $main_query->get_queried_object_id(), 'wp_curate_deduplication', true );

if ( true === (bool) $post_level_deduplication ) {
return true;
if ( true === (bool) $post_level_deduplication ) {
return true;
}
}
}

return false;
},
test: new Comparison( [ 'compared' => true ] ),
is_true: new Exclude_Queries(
$this->history,
$this->default_per_page,
$this->post_queries,
return false;
},
test: new Comparison( [ 'compared' => true ] ),
is_true: new Exclude_Queries(
$this->history,
$this->default_per_page,
$this->post_queries,
),
is_false: $this->post_queries,
),
is_false: $this->post_queries,
),
),
),
Expand Down
Loading