forked from ampproject/amp-wp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-amp-polldaddy-embed.php
101 lines (88 loc) · 2.34 KB
/
class-amp-polldaddy-embed.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
/**
* Class WPCOM_AMP_Polldaddy_Embed
*
* @package AMP
*/
/**
* Class WPCOM_AMP_Polldaddy_Embed
*/
class WPCOM_AMP_Polldaddy_Embed extends AMP_Base_Embed_Handler {
/**
* Register embed.
*/
public function register_embed() {
add_shortcode( 'polldaddy', array( $this, 'shortcode' ) );
add_filter( 'embed_oembed_html', array( $this, 'filter_embed_oembed_html' ), 10, 3 );
}
/**
* Unregister embed.
*/
public function unregister_embed() {
remove_shortcode( 'polldaddy' );
remove_filter( 'embed_oembed_html', array( $this, 'filter_embed_oembed_html' ), 10 );
}
/**
* Shortcode.
*
* @param array $attr Shortcode attributes.
* @return string Shortcode.
* @global WP_Embed $wp_embed
*/
public function shortcode( $attr ) {
global $wp_embed;
$output = '';
$url = 'https://polldaddy.com/';
if ( ! empty( $attr['poll'] ) ) {
$url .= 'poll/' . $attr['poll'] . '/';
} elseif ( ! empty( $attr['survey'] ) ) {
$url .= 's/' . $attr['survey'] . '/';
}
if ( ! empty( $attr['title'] ) ) {
$output = $this->render_link( $url, $attr['title'] );
} elseif ( $url ) {
$output = $wp_embed->shortcode( $attr, $url );
}
return $output;
}
/**
* Filter oEmbed HTML for PollDaddy to for AMP output.
*
* @param string $cache Cache for oEmbed.
* @param string $url Embed URL.
* @param array $attr Shortcode attributes.
* @return string Embed.
*/
public function filter_embed_oembed_html( $cache, $url, $attr ) {
$parsed_url = wp_parse_url( $url );
if ( false === strpos( $parsed_url['host'], 'polldaddy.com' ) ) {
return $cache;
}
$output = '';
// Poll oEmbed responses include noscript.
if ( preg_match( '#<noscript>(.+?)</noscript>#', $cache, $matches ) ) {
$output = $matches[1];
}
if ( empty( $output ) ) {
if ( ! empty( $attr['title'] ) ) {
$name = $attr['title'];
} elseif ( false !== strpos( $url, 'polldaddy.com/s' ) ) {
$name = __( 'View Survey', 'amp' );
} else {
$name = __( 'View Poll', 'amp' );
}
$output = $this->render_link( $url, $name );
}
return $output;
}
/**
* Render poll/survey link.
*
* @param string $url Link URL.
* @param string $title Link Text.
* @return string Link.
*/
private function render_link( $url, $title ) {
return sprintf( '<p><a href="' . esc_url( $url ) . '">' . esc_html( $title ) . '</a></p>' );
}
}