qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
input
stringlengths
12
45k
output
stringlengths
2
31.8k
336,389
<p>I have a problem with a cron schedule function, it does not want to send an email with the <code>wp_mail()</code> function.</p> <p><strong>This is my code:</strong></p> <p>It is placed in the functions.php</p> <pre class="lang-php prettyprint-override"><code>&lt;?php add_filter('cron_schedules', 'add_review_invites_schedule'); function add_review_invites_schedule($schedules){ $schedules['send_review_invites_interval'] = array( 'interval' =&gt; 5*60, 'display' =&gt; __('Every Five Minutes'), ); return $schedules; } if (!wp_get_schedule('send_review_invites_event')) { wp_schedule_event( time(), 'send_review_invites_interval', 'send_review_invites_event'); } add_action( 'send_review_invites_event', 'send_review_invites' ); function send_review_invites(){ echo 'test'; wp_mail( '[email protected]', 'Automatic email', 'Automatic scheduled email from WordPress to test cron'); } ?&gt; </code></pre> <p>Some things you should know I have connected the wp-cron to my server cron so it runs this code on my website. I have also put <code>define('DISABLE_WP_CRON', false);</code> in the wp-config.php.</p> <p>The output I get in my mail when the server cron runs, echos <code>test</code>. This shows me that the function <code>send_review_invites()</code> is being run. Yet somehow I don't get another email on the email address given in the <code>wp_mail()</code> function.</p> <p>Thanks in advance for your help.</p>
[ { "answer_id": 336372, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I would like to be able to output this as a shortcode to add anywhere\n within the post</p>\n</blockquote>\n\n<p>So since you said, \"<em>I prefer a non-plugin solution</em>\", then you can use this (which you'd add to the theme <code>functions.php</code> file) to create the shortcode:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode( 'dansk_link', 'dansk_link_shortcode' );\nfunction dansk_link_shortcode() {\n ob_start();\n $url = get_post_meta( get_the_ID(), 'dansk_url', true );\n if ( $url ) : ?&gt;\n &lt;a href=\"&lt;?php echo esc_url( $url ); ?&gt;\"&gt;Dansk&lt;/a&gt;\n &lt;?php\n endif; // end $url\n return ob_get_clean();\n}\n</code></pre>\n\n<p>And in the post content, add <code>[dansk_link]</code> anywhere you like.</p>\n\n<p>The above PHP code is still considered a plugin, but it's basically \"your own\" plugin. :)</p>\n\n<p>PS: For the function reference, you can check <a href=\"https://developer.wordpress.org/reference/functions/add_shortcode/\" rel=\"nofollow noreferrer\"><code>add_shortcode()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta()</code></a>.</p>\n\n<h2>UPDATE</h2>\n\n<ol>\n<li><p>I changed the shortcode name to <code>dansk_link</code> because that seems better than <code>dansk_url</code> for what the shortcode is for (i.e. outputting a <em>link</em>).</p></li>\n<li><p>In my original answer, I used output buffering (i.e. those <code>ob_start()</code> and <code>ob_get_clean()</code>) so that's it's easier for <em>you</em> (the question author) to edit the HTML output.</p></li>\n</ol>\n\n<p>Having said the point #2 above, you could also use:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode( 'dansk_link', 'dansk_link_shortcode' );\nfunction dansk_link_shortcode() {\n if ( $url = get_post_meta( get_the_ID(), 'dansk_url', true ) ) {\n return '&lt;a href=\"' . esc_url( $url ) . '\"&gt;Dansk&lt;/a&gt;';\n }\n return '';\n}\n</code></pre>\n" }, { "answer_id": 336374, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 1, "selected": true, "text": "<p>Put this in <code>functions.php</code> of your theme.</p>\n\n<pre><code>add_shortcode( 'dansk_url', 'dansk_url' );\nfunction dansk_url() {\n $output='';\n $the_url= get_post_meta( get_the_ID(), 'dansk_url', true );\n\n if ( $the_url) $output .= '&lt;a href=\"' . esc_url( $the_url) . '\"&gt;Dansk&lt;/a&gt;';\n\n return $output;\n}\n</code></pre>\n\n<p>and use shortcode <code>[dansk_url]</code> in the post.</p>\n" } ]
2019/04/26
[ "https://wordpress.stackexchange.com/questions/336389", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165422/" ]
I have a problem with a cron schedule function, it does not want to send an email with the `wp_mail()` function. **This is my code:** It is placed in the functions.php ```php <?php add_filter('cron_schedules', 'add_review_invites_schedule'); function add_review_invites_schedule($schedules){ $schedules['send_review_invites_interval'] = array( 'interval' => 5*60, 'display' => __('Every Five Minutes'), ); return $schedules; } if (!wp_get_schedule('send_review_invites_event')) { wp_schedule_event( time(), 'send_review_invites_interval', 'send_review_invites_event'); } add_action( 'send_review_invites_event', 'send_review_invites' ); function send_review_invites(){ echo 'test'; wp_mail( '[email protected]', 'Automatic email', 'Automatic scheduled email from WordPress to test cron'); } ?> ``` Some things you should know I have connected the wp-cron to my server cron so it runs this code on my website. I have also put `define('DISABLE_WP_CRON', false);` in the wp-config.php. The output I get in my mail when the server cron runs, echos `test`. This shows me that the function `send_review_invites()` is being run. Yet somehow I don't get another email on the email address given in the `wp_mail()` function. Thanks in advance for your help.
Put this in `functions.php` of your theme. ``` add_shortcode( 'dansk_url', 'dansk_url' ); function dansk_url() { $output=''; $the_url= get_post_meta( get_the_ID(), 'dansk_url', true ); if ( $the_url) $output .= '<a href="' . esc_url( $the_url) . '">Dansk</a>'; return $output; } ``` and use shortcode `[dansk_url]` in the post.
336,433
<p>I'm currently getting the data from a custom taxonomy using this:</p> <pre><code>$terms = get_terms(array( 'taxonomy' =&gt; 'my_custom_taxonomy_name', 'hide_empty' =&gt; true )); </code></pre> <p>Now, this returns a lot of stuff in each <code>WP_Term</code> object; <code>term_id</code>, <code>name</code>, <code>slug</code>, <code>term_group</code>, <code>term_taxonomy_id</code>, <code>taxonomy</code>, <code>description</code>, <code>parent</code>, <code>count</code> and <code>filter</code>.</p> <p>I only need to get 2 of those: <code>name</code> and <code>slug</code>. How can I filter that query so it doesn't returns all that unused data?</p>
[ { "answer_id": 336372, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I would like to be able to output this as a shortcode to add anywhere\n within the post</p>\n</blockquote>\n\n<p>So since you said, \"<em>I prefer a non-plugin solution</em>\", then you can use this (which you'd add to the theme <code>functions.php</code> file) to create the shortcode:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode( 'dansk_link', 'dansk_link_shortcode' );\nfunction dansk_link_shortcode() {\n ob_start();\n $url = get_post_meta( get_the_ID(), 'dansk_url', true );\n if ( $url ) : ?&gt;\n &lt;a href=\"&lt;?php echo esc_url( $url ); ?&gt;\"&gt;Dansk&lt;/a&gt;\n &lt;?php\n endif; // end $url\n return ob_get_clean();\n}\n</code></pre>\n\n<p>And in the post content, add <code>[dansk_link]</code> anywhere you like.</p>\n\n<p>The above PHP code is still considered a plugin, but it's basically \"your own\" plugin. :)</p>\n\n<p>PS: For the function reference, you can check <a href=\"https://developer.wordpress.org/reference/functions/add_shortcode/\" rel=\"nofollow noreferrer\"><code>add_shortcode()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta()</code></a>.</p>\n\n<h2>UPDATE</h2>\n\n<ol>\n<li><p>I changed the shortcode name to <code>dansk_link</code> because that seems better than <code>dansk_url</code> for what the shortcode is for (i.e. outputting a <em>link</em>).</p></li>\n<li><p>In my original answer, I used output buffering (i.e. those <code>ob_start()</code> and <code>ob_get_clean()</code>) so that's it's easier for <em>you</em> (the question author) to edit the HTML output.</p></li>\n</ol>\n\n<p>Having said the point #2 above, you could also use:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode( 'dansk_link', 'dansk_link_shortcode' );\nfunction dansk_link_shortcode() {\n if ( $url = get_post_meta( get_the_ID(), 'dansk_url', true ) ) {\n return '&lt;a href=\"' . esc_url( $url ) . '\"&gt;Dansk&lt;/a&gt;';\n }\n return '';\n}\n</code></pre>\n" }, { "answer_id": 336374, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 1, "selected": true, "text": "<p>Put this in <code>functions.php</code> of your theme.</p>\n\n<pre><code>add_shortcode( 'dansk_url', 'dansk_url' );\nfunction dansk_url() {\n $output='';\n $the_url= get_post_meta( get_the_ID(), 'dansk_url', true );\n\n if ( $the_url) $output .= '&lt;a href=\"' . esc_url( $the_url) . '\"&gt;Dansk&lt;/a&gt;';\n\n return $output;\n}\n</code></pre>\n\n<p>and use shortcode <code>[dansk_url]</code> in the post.</p>\n" } ]
2019/04/26
[ "https://wordpress.stackexchange.com/questions/336433", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/166782/" ]
I'm currently getting the data from a custom taxonomy using this: ``` $terms = get_terms(array( 'taxonomy' => 'my_custom_taxonomy_name', 'hide_empty' => true )); ``` Now, this returns a lot of stuff in each `WP_Term` object; `term_id`, `name`, `slug`, `term_group`, `term_taxonomy_id`, `taxonomy`, `description`, `parent`, `count` and `filter`. I only need to get 2 of those: `name` and `slug`. How can I filter that query so it doesn't returns all that unused data?
Put this in `functions.php` of your theme. ``` add_shortcode( 'dansk_url', 'dansk_url' ); function dansk_url() { $output=''; $the_url= get_post_meta( get_the_ID(), 'dansk_url', true ); if ( $the_url) $output .= '<a href="' . esc_url( $the_url) . '">Dansk</a>'; return $output; } ``` and use shortcode `[dansk_url]` in the post.
336,572
<p>i'm using Advanced Custom Fields plugins and i want to display the fields on my posts. So i modified the single.php file of my theme like this:</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;?php the_field('name_of_placement'); ?&gt;&lt;/li&gt; &lt;li&gt;&lt;?php the_field('country'); ?&gt;&lt;/li&gt; &lt;li&gt;&lt;?php the_field('timeframe'); ?&gt;&lt;/li&gt; &lt;li&gt;&lt;?php the_field('types_of_healthcare_placement'); ?&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And this is my test post:</p> <p><a href="http://electives-abroad.org/custom-field-test/" rel="nofollow noreferrer">http://electives-abroad.org/custom-field-test/</a></p> <p>The only field that displays correctly is the "name of placement" field, the others display numbers, i don't know why.</p> <p><em>UPDATE</em></p> <p>The 'country' field is a taxonomy. According to this: advancedcustomfields.com/resources/taxonomy</p> <p>I put the following: </p> <pre><code>&lt;?php $term = get_field('country'); if( $term ): ?&gt; &lt;h2&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/h2&gt; &lt;p&gt;&lt;?php echo $term-&gt;description; ?&gt;&lt;/p&gt; &lt;p&gt;Color: &lt;?php the_field('country', $term); ?&gt;&lt;/p&gt; </code></pre> <p>But it doesn't show me anything –</p> <p>*SOLUTION PROPOSED BY Sally CJ</p> <pre><code> &lt;h2&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/h2&gt; &lt;p&gt;&lt;?php echo $term-&gt;description; ?&gt;&lt;/p&gt; &lt;p&gt;Color: &lt;?php the_field('country', $term); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;ul&gt; &lt;li&gt;&lt;?php the_field('name_of_placement'); ?&gt;&lt;/li&gt; &lt;li&gt;&lt;?php the_field('country'); ?&gt;&lt;/li&gt; &lt;li&gt;&lt;?php the_field('timeframe'); ?&gt;&lt;/li&gt; &lt;li&gt;&lt;?php the_field('types_of_healthcare_placement'); ?&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Now it shows me an "uncategorized".</p> <p><em>New update</em></p> <p>Now i tried this, to show 2 of my taxonomies: country and timeframe. </p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;?php the_field('name_of_placement'); ?&gt;&lt;/li&gt; &lt;li&gt;&lt;?php echo get_term_field( 'name', get_field('country') ); ?&gt;&lt;/li&gt; &lt;li&gt;&lt;?php echo get_term_field( 'name', get_field('timeframe') ); ?&gt;&lt;/li&gt; &lt;li&gt;&lt;?php the_field('types_of_healthcare_placement'); ?&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Both of them appear as "uncategorized".</p>
[ { "answer_id": 336546, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 1, "selected": false, "text": "<p>I think <em>\"how\"</em> depends mostly on the theme (or page builder plugin) you're using. </p>\n\n<p>If the posts section is hard-coded to a page or an archive template then you could <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/#adding-template-files\" rel=\"nofollow noreferrer\">copy the template to a child theme</a> and make the required changes to the copied file.</p>\n\n<p>If the post boxes are <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">template_parts</a> or they are made of multiple template_parts, then copy the correct file/s to your child theme and edit the copy/ied file/s.</p>\n\n<p>If there are <a href=\"https://codex.wordpress.org/Plugin_API#Hooks:_Actions_and_Filters\" rel=\"nofollow noreferrer\">actions or hooks</a> for editing the post boxes' layout/content available, you can use them.</p>\n\n<p>I guess you could also (ab)use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">wp_localize_script</a> to get the meta data to front-end, and then insert the data with necessary html to the correct post boxes with vanilla javascript or jquery.</p>\n\n<p>If the posts section is created with a (page builder) plugin, then refer to the plugin documentation or ask help from the plugin author. Perhaps you can extend the plugin with a custom addon that adds a posts section/grid that matches your needs. <a href=\"https://developers.elementor.com/creating-an-extension-for-elementor/\" rel=\"nofollow noreferrer\">Elementor docs for extending the plugin.</a></p>\n" }, { "answer_id": 365238, "author": "user186997", "author_id": 186997, "author_profile": "https://wordpress.stackexchange.com/users/186997", "pm_score": 0, "selected": false, "text": "<p>You need</p>\n\n<ol>\n<li>Advance custom field </li>\n<li>Taxonomy</li>\n<li>little bit PHP coding</li>\n</ol>\n\n<p>You should find \"blog template/ blog layout\" in your theme folder / look for the grip wrap, \nyour theme might have many layout to show the blogs and you need to find the GRID. </p>\n\n<p>make the \"field\", like : Holiday-option , Day duration in your advance field and fill it up in your Tour page. </p>\n\n<p>you may edit your \"blog template\" and call your input data </p>\n\n<p>e.g. </p>\n\n<pre><code>&lt;div class=\"tourprice\"&gt;&lt;?php echo 'Price: ' ; the_field( 'price' ) ?&gt;&lt;/div&gt;\n&lt;small&gt;&lt;?php the_taxonomies(); ?&gt;&lt;/small&gt;\n</code></pre>\n" } ]
2019/04/29
[ "https://wordpress.stackexchange.com/questions/336572", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/166978/" ]
i'm using Advanced Custom Fields plugins and i want to display the fields on my posts. So i modified the single.php file of my theme like this: ``` <ul> <li><?php the_field('name_of_placement'); ?></li> <li><?php the_field('country'); ?></li> <li><?php the_field('timeframe'); ?></li> <li><?php the_field('types_of_healthcare_placement'); ?></li> </ul> ``` And this is my test post: <http://electives-abroad.org/custom-field-test/> The only field that displays correctly is the "name of placement" field, the others display numbers, i don't know why. *UPDATE* The 'country' field is a taxonomy. According to this: advancedcustomfields.com/resources/taxonomy I put the following: ``` <?php $term = get_field('country'); if( $term ): ?> <h2><?php echo $term->name; ?></h2> <p><?php echo $term->description; ?></p> <p>Color: <?php the_field('country', $term); ?></p> ``` But it doesn't show me anything – \*SOLUTION PROPOSED BY Sally CJ ``` <h2><?php echo $term->name; ?></h2> <p><?php echo $term->description; ?></p> <p>Color: <?php the_field('country', $term); ?></p> <?php endif; ?> <ul> <li><?php the_field('name_of_placement'); ?></li> <li><?php the_field('country'); ?></li> <li><?php the_field('timeframe'); ?></li> <li><?php the_field('types_of_healthcare_placement'); ?></li> </ul> ``` Now it shows me an "uncategorized". *New update* Now i tried this, to show 2 of my taxonomies: country and timeframe. ``` <ul> <li><?php the_field('name_of_placement'); ?></li> <li><?php echo get_term_field( 'name', get_field('country') ); ?></li> <li><?php echo get_term_field( 'name', get_field('timeframe') ); ?></li> <li><?php the_field('types_of_healthcare_placement'); ?></li> </ul> ``` Both of them appear as "uncategorized".
I think *"how"* depends mostly on the theme (or page builder plugin) you're using. If the posts section is hard-coded to a page or an archive template then you could [copy the template to a child theme](https://developer.wordpress.org/themes/advanced-topics/child-themes/#adding-template-files) and make the required changes to the copied file. If the post boxes are [template\_parts](https://developer.wordpress.org/reference/functions/get_template_part/) or they are made of multiple template\_parts, then copy the correct file/s to your child theme and edit the copy/ied file/s. If there are [actions or hooks](https://codex.wordpress.org/Plugin_API#Hooks:_Actions_and_Filters) for editing the post boxes' layout/content available, you can use them. I guess you could also (ab)use [wp\_localize\_script](https://codex.wordpress.org/Function_Reference/wp_localize_script) to get the meta data to front-end, and then insert the data with necessary html to the correct post boxes with vanilla javascript or jquery. If the posts section is created with a (page builder) plugin, then refer to the plugin documentation or ask help from the plugin author. Perhaps you can extend the plugin with a custom addon that adds a posts section/grid that matches your needs. [Elementor docs for extending the plugin.](https://developers.elementor.com/creating-an-extension-for-elementor/)
336,574
<p>I am trying to get the terms from all the taxonomies in an array. but this throws an error like this ..not sure why. Is it the wrong method?:</p> <blockquote> <p>Fatal error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ',' or ')'</p> </blockquote> <pre><code>public function pggggo_list_of_terms(){ $terms = get_terms( 'taxonomy' =&gt; array( 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras') ); return $terms; } </code></pre>
[ { "answer_id": 336575, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>This is a PHP syntax error. You're attempting to pass an array to <code>get_terms()</code> but haven't used <code>array()</code> or <code>[]</code> to make it an array. This means that <code>=&gt;</code> is invalid here. The code should be:</p>\n\n<pre><code>public function pggggo_list_of_terms() {\n $terms = get_terms(\n [\n 'taxonomy' =&gt; [\n 'vehicle_safely_features',\n 'vehicle_exterior_features',\n 'vehicle_interior_features',\n 'vehicle_extras',\n ],\n ]\n );\n\n return $terms;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public function pggggo_list_of_terms() {\n $terms = get_terms(\n array(\n 'taxonomy' =&gt; array(\n 'vehicle_safely_features',\n 'vehicle_exterior_features',\n 'vehicle_interior_features',\n 'vehicle_extras',\n ),\n )\n );\n\n return $terms;\n}\n</code></pre>\n" }, { "answer_id": 336576, "author": "Nilambar Sharma", "author_id": 27998, "author_profile": "https://wordpress.stackexchange.com/users/27998", "pm_score": 0, "selected": false, "text": "<p>May be you are trying to do this. Passing arguments is wrong in your code.</p>\n\n<pre><code>public function pggggo_list_of_terms(){\n $terms = get_terms(\n 'taxonomy', array(\n 'vehicle_safely_features',\n 'vehicle_exterior_features',\n 'vehicle_interior_features',\n 'vehicle_extras')\n );\n return $terms;\n}\n</code></pre>\n" } ]
2019/04/29
[ "https://wordpress.stackexchange.com/questions/336574", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I am trying to get the terms from all the taxonomies in an array. but this throws an error like this ..not sure why. Is it the wrong method?: > > Fatal error: syntax error, unexpected '=>' (T\_DOUBLE\_ARROW), expecting > ',' or ')' > > > ``` public function pggggo_list_of_terms(){ $terms = get_terms( 'taxonomy' => array( 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras') ); return $terms; } ```
This is a PHP syntax error. You're attempting to pass an array to `get_terms()` but haven't used `array()` or `[]` to make it an array. This means that `=>` is invalid here. The code should be: ``` public function pggggo_list_of_terms() { $terms = get_terms( [ 'taxonomy' => [ 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras', ], ] ); return $terms; } ``` or ``` public function pggggo_list_of_terms() { $terms = get_terms( array( 'taxonomy' => array( 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras', ), ) ); return $terms; } ```
336,587
<p>I have the standard blog post format and gallery format. I have excluded all the gallery posts from the index.php page so only standard posts show up there. However, the gallery format posts are still being counted for pagination and there is just a blank space on the pagination pages where there would be a gallery post format. How can those be excluded from pagination?</p> <pre><code> &lt;?php echo paginate_links(); ?&gt; </code></pre> <p>I tried this but it didn't help:</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'post', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'post_format', 'field' =&gt; 'slug', 'terms' =&gt; array( 'post-format-gallery' ) , 'operator' =&gt; 'NOT IN', ) , ) ); ?&gt; &lt;?php echo paginate_links($args); ?&gt; </code></pre> <p>This is the query that displays the standard blog posts:</p> <pre><code> &lt;?php if (have_posts() ): ?&gt; &lt;?php while (have_posts() ): the_post(); ?&gt; &lt;?php $format = get_post_format( $post_id ); ?&gt; &lt;?php if($format != 'gallery'): ?&gt; &lt;div class="blog" style="width: 350px"&gt;&lt;a href="&lt;?php esc_url(the_permalink()); ?&gt;" class="w-inline-block"&gt;&lt;?php the_post_thumbnail(); ?&gt;&lt;/a&gt; &lt;div class="gallery-info"&gt;&lt;a href="&lt;?php esc_url(the_permalink()); ?&gt;" class="linkgallery"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;?php $the_category = get_the_category(); ?&gt; &lt;div class="gallery-info gallery-category"&gt;&lt;?php foreach($the_category as $category): ?&gt;&lt;?php echo $category-&gt;cat_name . ' '; ?&gt; &lt;?php endforeach; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; ?&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 336575, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>This is a PHP syntax error. You're attempting to pass an array to <code>get_terms()</code> but haven't used <code>array()</code> or <code>[]</code> to make it an array. This means that <code>=&gt;</code> is invalid here. The code should be:</p>\n\n<pre><code>public function pggggo_list_of_terms() {\n $terms = get_terms(\n [\n 'taxonomy' =&gt; [\n 'vehicle_safely_features',\n 'vehicle_exterior_features',\n 'vehicle_interior_features',\n 'vehicle_extras',\n ],\n ]\n );\n\n return $terms;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public function pggggo_list_of_terms() {\n $terms = get_terms(\n array(\n 'taxonomy' =&gt; array(\n 'vehicle_safely_features',\n 'vehicle_exterior_features',\n 'vehicle_interior_features',\n 'vehicle_extras',\n ),\n )\n );\n\n return $terms;\n}\n</code></pre>\n" }, { "answer_id": 336576, "author": "Nilambar Sharma", "author_id": 27998, "author_profile": "https://wordpress.stackexchange.com/users/27998", "pm_score": 0, "selected": false, "text": "<p>May be you are trying to do this. Passing arguments is wrong in your code.</p>\n\n<pre><code>public function pggggo_list_of_terms(){\n $terms = get_terms(\n 'taxonomy', array(\n 'vehicle_safely_features',\n 'vehicle_exterior_features',\n 'vehicle_interior_features',\n 'vehicle_extras')\n );\n return $terms;\n}\n</code></pre>\n" } ]
2019/04/29
[ "https://wordpress.stackexchange.com/questions/336587", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165412/" ]
I have the standard blog post format and gallery format. I have excluded all the gallery posts from the index.php page so only standard posts show up there. However, the gallery format posts are still being counted for pagination and there is just a blank space on the pagination pages where there would be a gallery post format. How can those be excluded from pagination? ``` <?php echo paginate_links(); ?> ``` I tried this but it didn't help: ``` <?php $args = array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => array( 'post-format-gallery' ) , 'operator' => 'NOT IN', ) , ) ); ?> <?php echo paginate_links($args); ?> ``` This is the query that displays the standard blog posts: ``` <?php if (have_posts() ): ?> <?php while (have_posts() ): the_post(); ?> <?php $format = get_post_format( $post_id ); ?> <?php if($format != 'gallery'): ?> <div class="blog" style="width: 350px"><a href="<?php esc_url(the_permalink()); ?>" class="w-inline-block"><?php the_post_thumbnail(); ?></a> <div class="gallery-info"><a href="<?php esc_url(the_permalink()); ?>" class="linkgallery"><?php the_title(); ?></a></div> <?php $the_category = get_the_category(); ?> <div class="gallery-info gallery-category"><?php foreach($the_category as $category): ?><?php echo $category->cat_name . ' '; ?> <?php endforeach; ?> </div> </div> <?php endif; ?> <?php endwhile; ?> <?php wp_reset_postdata(); ?> <?php endif; ?> ```
This is a PHP syntax error. You're attempting to pass an array to `get_terms()` but haven't used `array()` or `[]` to make it an array. This means that `=>` is invalid here. The code should be: ``` public function pggggo_list_of_terms() { $terms = get_terms( [ 'taxonomy' => [ 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras', ], ] ); return $terms; } ``` or ``` public function pggggo_list_of_terms() { $terms = get_terms( array( 'taxonomy' => array( 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras', ), ) ); return $terms; } ```
336,588
<p>I am trying &amp; learning to build custom block/template for Gutenberg and would like to "pre-set" CSS class for some specific block. Is it possible to add it like below?</p> <p>Refer: [Template and Block][1]</p> <p>For example, defined CSS class for one of the heading <code>blockHeadStyle</code>: </p> <pre><code>function myplugin_register_book_post_type() { $args = array( 'public' =&gt; true, 'label' =&gt; 'Books', 'show_in_rest' =&gt; true, 'template' =&gt; array( array( 'core/image', array( 'align' =&gt; 'left', ) ), array( 'core/heading', array( 'placeholder' =&gt; 'Add Author...', 'class' =&gt; 'blockHeadStyle' ) ), array( 'core/paragraph', array( 'placeholder' =&gt; 'Add Description...', )), ), ); register_post_type('book', $args); } add_action('init', 'myplugin_register_book_post_type'); </code></pre>
[ { "answer_id": 336630, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 2, "selected": false, "text": "<p>This can be done using the <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/\" rel=\"nofollow noreferrer\">block filters API</a>.</p>\n<p>Here is an example of adding a class to the block in the editor.</p>\n<pre><code>\nconst withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) =&gt; {\n return ( props ) =&gt; {\n const customClass = 'custom-classname' );\n return (\n &lt;BlockListBlock { ...props } className={ customClass }/&gt;\n );\n };\n}, 'withClientIdClassName' );\n\naddFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName );\n</code></pre>\n<p>The above code will add the <code>custom-classname</code> class to each block in the list of block in the editor.</p>\n<p>If you're looking to only affect a specific block, <code>props</code> has <code>name</code> property that can be checked:</p>\n<pre><code>\nconst withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) =&gt; {\n return ( props ) =&gt; {\n if( 'core/heading' === props.name ) {\n const customClass = 'custom-classname' );\n return (\n &lt;BlockListBlock { ...props } className={ customClass }/&gt;\n );\n } else {\n &lt;BlockListBlock { ...props }/&gt; \n }\n };\n}, 'withClientIdClassName' );\n\naddFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName );\n</code></pre>\n<p>Hope this helps!</p>\n" }, { "answer_id": 364114, "author": "mertbizk", "author_id": 186117, "author_profile": "https://wordpress.stackexchange.com/users/186117", "pm_score": 2, "selected": false, "text": "<p>In case anyone is looking for an answer to this that doesn't involve adding a filter and a bunch of extra code, you can add a className to the block directly in the template code. This is the same code that the OP used, with one small adjustment. \"class\" becomes \"className\":</p>\n\n<pre><code>function myplugin_register_book_post_type() {\n $args = array(\n 'public' =&gt; true,\n 'label' =&gt; 'Books',\n 'show_in_rest' =&gt; true,\n 'template' =&gt; array(\n array( 'core/image', array(\n 'align' =&gt; 'left',\n ) ),\n array( 'core/heading', array(\n 'placeholder' =&gt; 'Add Author...',\n 'className' =&gt; 'blockHeadStyle anotherClassName'\n ) ),\n array( 'core/paragraph', array(\n 'placeholder' =&gt; 'Add Description...',\n )),\n ),\n );\n register_post_type('book', $args);\n}\nadd_action('init', 'myplugin_register_book_post_type');\n</code></pre>\n\n<p>Here is a screenshot to show how this renders in dev tools:</p>\n\n<p><a href=\"https://i.stack.imgur.com/b6IYa.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b6IYa.jpg\" alt=\"Here is a screenshot to show how this renders in dev tools\"></a></p>\n\n<p>As you can see, I also added a second class to the h2 element, simply by adding a space between each class declared by \"className.\"</p>\n" } ]
2019/04/29
[ "https://wordpress.stackexchange.com/questions/336588", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/166651/" ]
I am trying & learning to build custom block/template for Gutenberg and would like to "pre-set" CSS class for some specific block. Is it possible to add it like below? Refer: [Template and Block][1] For example, defined CSS class for one of the heading `blockHeadStyle`: ``` function myplugin_register_book_post_type() { $args = array( 'public' => true, 'label' => 'Books', 'show_in_rest' => true, 'template' => array( array( 'core/image', array( 'align' => 'left', ) ), array( 'core/heading', array( 'placeholder' => 'Add Author...', 'class' => 'blockHeadStyle' ) ), array( 'core/paragraph', array( 'placeholder' => 'Add Description...', )), ), ); register_post_type('book', $args); } add_action('init', 'myplugin_register_book_post_type'); ```
This can be done using the [block filters API](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/). Here is an example of adding a class to the block in the editor. ``` const withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) => { return ( props ) => { const customClass = 'custom-classname' ); return ( <BlockListBlock { ...props } className={ customClass }/> ); }; }, 'withClientIdClassName' ); addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName ); ``` The above code will add the `custom-classname` class to each block in the list of block in the editor. If you're looking to only affect a specific block, `props` has `name` property that can be checked: ``` const withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) => { return ( props ) => { if( 'core/heading' === props.name ) { const customClass = 'custom-classname' ); return ( <BlockListBlock { ...props } className={ customClass }/> ); } else { <BlockListBlock { ...props }/> } }; }, 'withClientIdClassName' ); addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName ); ``` Hope this helps!
336,605
<p>1 - I have a CPT, with 10 posts.</p> <p>2 - I have 10 users</p> <hr> <p>Q : How can i assign a single post from my CPT, to an unique user ? -> Each user must see only it's assigned post</p> <p>(Each post will be assigned by the admin of the site)</p> <p>Thanks</p>
[ { "answer_id": 336630, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 2, "selected": false, "text": "<p>This can be done using the <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/\" rel=\"nofollow noreferrer\">block filters API</a>.</p>\n<p>Here is an example of adding a class to the block in the editor.</p>\n<pre><code>\nconst withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) =&gt; {\n return ( props ) =&gt; {\n const customClass = 'custom-classname' );\n return (\n &lt;BlockListBlock { ...props } className={ customClass }/&gt;\n );\n };\n}, 'withClientIdClassName' );\n\naddFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName );\n</code></pre>\n<p>The above code will add the <code>custom-classname</code> class to each block in the list of block in the editor.</p>\n<p>If you're looking to only affect a specific block, <code>props</code> has <code>name</code> property that can be checked:</p>\n<pre><code>\nconst withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) =&gt; {\n return ( props ) =&gt; {\n if( 'core/heading' === props.name ) {\n const customClass = 'custom-classname' );\n return (\n &lt;BlockListBlock { ...props } className={ customClass }/&gt;\n );\n } else {\n &lt;BlockListBlock { ...props }/&gt; \n }\n };\n}, 'withClientIdClassName' );\n\naddFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName );\n</code></pre>\n<p>Hope this helps!</p>\n" }, { "answer_id": 364114, "author": "mertbizk", "author_id": 186117, "author_profile": "https://wordpress.stackexchange.com/users/186117", "pm_score": 2, "selected": false, "text": "<p>In case anyone is looking for an answer to this that doesn't involve adding a filter and a bunch of extra code, you can add a className to the block directly in the template code. This is the same code that the OP used, with one small adjustment. \"class\" becomes \"className\":</p>\n\n<pre><code>function myplugin_register_book_post_type() {\n $args = array(\n 'public' =&gt; true,\n 'label' =&gt; 'Books',\n 'show_in_rest' =&gt; true,\n 'template' =&gt; array(\n array( 'core/image', array(\n 'align' =&gt; 'left',\n ) ),\n array( 'core/heading', array(\n 'placeholder' =&gt; 'Add Author...',\n 'className' =&gt; 'blockHeadStyle anotherClassName'\n ) ),\n array( 'core/paragraph', array(\n 'placeholder' =&gt; 'Add Description...',\n )),\n ),\n );\n register_post_type('book', $args);\n}\nadd_action('init', 'myplugin_register_book_post_type');\n</code></pre>\n\n<p>Here is a screenshot to show how this renders in dev tools:</p>\n\n<p><a href=\"https://i.stack.imgur.com/b6IYa.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b6IYa.jpg\" alt=\"Here is a screenshot to show how this renders in dev tools\"></a></p>\n\n<p>As you can see, I also added a second class to the h2 element, simply by adding a space between each class declared by \"className.\"</p>\n" } ]
2019/04/29
[ "https://wordpress.stackexchange.com/questions/336605", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/162471/" ]
1 - I have a CPT, with 10 posts. 2 - I have 10 users --- Q : How can i assign a single post from my CPT, to an unique user ? -> Each user must see only it's assigned post (Each post will be assigned by the admin of the site) Thanks
This can be done using the [block filters API](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/). Here is an example of adding a class to the block in the editor. ``` const withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) => { return ( props ) => { const customClass = 'custom-classname' ); return ( <BlockListBlock { ...props } className={ customClass }/> ); }; }, 'withClientIdClassName' ); addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName ); ``` The above code will add the `custom-classname` class to each block in the list of block in the editor. If you're looking to only affect a specific block, `props` has `name` property that can be checked: ``` const withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) => { return ( props ) => { if( 'core/heading' === props.name ) { const customClass = 'custom-classname' ); return ( <BlockListBlock { ...props } className={ customClass }/> ); } else { <BlockListBlock { ...props }/> } }; }, 'withClientIdClassName' ); addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName ); ``` Hope this helps!
336,647
<p>I deployed my wordpress site in Google Cloud Compute Engine. To enable SSL I followed the the steps outlined here <a href="https://www.onepagezen.com/free-ssl-certificate-wordpress-google-cloud-click-to-deploy" rel="nofollow noreferrer">https://www.onepagezen.com/free-ssl-certificate-wordpress-google-cloud-click-to-deploy</a></p> <ol> <li>Install Certbot Client</li> <li>Generate Certificates</li> <li>Configure the Certificates</li> <li>Enable HTTPS Redirect</li> <li>Restart Apache Server</li> <li>Update WordPress URLs</li> <li>Configure SSL Auto-Renewal</li> </ol> <p>Edit <code>/etc/apache2/sites-available/default-ssl.conf</code></p> <pre><code>&lt;IfModule mod_ssl.c&gt; &lt;VirtualHost _default_:443&gt; ServerAdmin webmaster@localhost DocumentRoot /var/www/html &lt;Directory /var/www/html&gt; Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny Allow from all Require all granted &lt;/Directory&gt; ... </code></pre> <p>and <code>/etc/apache2/sites-available/wordpress.conf</code></p> <pre><code>&lt;VirtualHost *:80&gt; ServerAdmin webmaster@localhost DocumentRoot /var/www/html ServerName mydomain.com ServerAlias mydomain.com Redirect permanent / https..mydomain.com &lt;Directory /&gt; Options FollowSymLinks AllowOverride None &lt;/Directory&gt; &lt;Directory /var/www/html/&gt; Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny Allow from all &lt;/Directory&gt; ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ &lt;Directory "/usr/lib/cgi-bin"&gt; AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; </code></pre> <p>After setting everything up, I run:</p> <pre><code>sudo a2ensite default-ssl sudo a2enmod ssl sudo service apache2 restart </code></pre> <p>SSL works fine for the backend and the landing page. However for all other pages I get a 404. When I switch form custom permalinks to simple permalinks the pages are accessible again. Any ideas what might be causing the problem?</p>
[ { "answer_id": 336630, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 2, "selected": false, "text": "<p>This can be done using the <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/\" rel=\"nofollow noreferrer\">block filters API</a>.</p>\n<p>Here is an example of adding a class to the block in the editor.</p>\n<pre><code>\nconst withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) =&gt; {\n return ( props ) =&gt; {\n const customClass = 'custom-classname' );\n return (\n &lt;BlockListBlock { ...props } className={ customClass }/&gt;\n );\n };\n}, 'withClientIdClassName' );\n\naddFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName );\n</code></pre>\n<p>The above code will add the <code>custom-classname</code> class to each block in the list of block in the editor.</p>\n<p>If you're looking to only affect a specific block, <code>props</code> has <code>name</code> property that can be checked:</p>\n<pre><code>\nconst withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) =&gt; {\n return ( props ) =&gt; {\n if( 'core/heading' === props.name ) {\n const customClass = 'custom-classname' );\n return (\n &lt;BlockListBlock { ...props } className={ customClass }/&gt;\n );\n } else {\n &lt;BlockListBlock { ...props }/&gt; \n }\n };\n}, 'withClientIdClassName' );\n\naddFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName );\n</code></pre>\n<p>Hope this helps!</p>\n" }, { "answer_id": 364114, "author": "mertbizk", "author_id": 186117, "author_profile": "https://wordpress.stackexchange.com/users/186117", "pm_score": 2, "selected": false, "text": "<p>In case anyone is looking for an answer to this that doesn't involve adding a filter and a bunch of extra code, you can add a className to the block directly in the template code. This is the same code that the OP used, with one small adjustment. \"class\" becomes \"className\":</p>\n\n<pre><code>function myplugin_register_book_post_type() {\n $args = array(\n 'public' =&gt; true,\n 'label' =&gt; 'Books',\n 'show_in_rest' =&gt; true,\n 'template' =&gt; array(\n array( 'core/image', array(\n 'align' =&gt; 'left',\n ) ),\n array( 'core/heading', array(\n 'placeholder' =&gt; 'Add Author...',\n 'className' =&gt; 'blockHeadStyle anotherClassName'\n ) ),\n array( 'core/paragraph', array(\n 'placeholder' =&gt; 'Add Description...',\n )),\n ),\n );\n register_post_type('book', $args);\n}\nadd_action('init', 'myplugin_register_book_post_type');\n</code></pre>\n\n<p>Here is a screenshot to show how this renders in dev tools:</p>\n\n<p><a href=\"https://i.stack.imgur.com/b6IYa.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b6IYa.jpg\" alt=\"Here is a screenshot to show how this renders in dev tools\"></a></p>\n\n<p>As you can see, I also added a second class to the h2 element, simply by adding a space between each class declared by \"className.\"</p>\n" } ]
2019/04/29
[ "https://wordpress.stackexchange.com/questions/336647", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167042/" ]
I deployed my wordpress site in Google Cloud Compute Engine. To enable SSL I followed the the steps outlined here <https://www.onepagezen.com/free-ssl-certificate-wordpress-google-cloud-click-to-deploy> 1. Install Certbot Client 2. Generate Certificates 3. Configure the Certificates 4. Enable HTTPS Redirect 5. Restart Apache Server 6. Update WordPress URLs 7. Configure SSL Auto-Renewal Edit `/etc/apache2/sites-available/default-ssl.conf` ``` <IfModule mod_ssl.c> <VirtualHost _default_:443> ServerAdmin webmaster@localhost DocumentRoot /var/www/html <Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny Allow from all Require all granted </Directory> ... ``` and `/etc/apache2/sites-available/wordpress.conf` ``` <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ServerName mydomain.com ServerAlias mydomain.com Redirect permanent / https..mydomain.com <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /var/www/html/> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny Allow from all </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> ``` After setting everything up, I run: ``` sudo a2ensite default-ssl sudo a2enmod ssl sudo service apache2 restart ``` SSL works fine for the backend and the landing page. However for all other pages I get a 404. When I switch form custom permalinks to simple permalinks the pages are accessible again. Any ideas what might be causing the problem?
This can be done using the [block filters API](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/). Here is an example of adding a class to the block in the editor. ``` const withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) => { return ( props ) => { const customClass = 'custom-classname' ); return ( <BlockListBlock { ...props } className={ customClass }/> ); }; }, 'withClientIdClassName' ); addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName ); ``` The above code will add the `custom-classname` class to each block in the list of block in the editor. If you're looking to only affect a specific block, `props` has `name` property that can be checked: ``` const withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) => { return ( props ) => { if( 'core/heading' === props.name ) { const customClass = 'custom-classname' ); return ( <BlockListBlock { ...props } className={ customClass }/> ); } else { <BlockListBlock { ...props }/> } }; }, 'withClientIdClassName' ); addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName ); ``` Hope this helps!
336,672
<p>We have a WordPress blog, google is indexing <code>http</code> as well as <code>https</code> urls. Now we are considering to either redirect <code>https</code> to <code>http</code>, or to use <code>https</code> and redirect all <code>http</code> traffic there. And how can we make all necessary changes to our WordPress installation?</p>
[ { "answer_id": 336741, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": 0, "selected": false, "text": "<p>You can paste this code in the <strong>wp-config.php</strong> file to define your new URL. </p>\n\n<pre><code>define('WP_HOME','http://yoursite.com'); //Enter your new URL\ndefine('WP_SITEURL','http://yoursite.com'); //Enter your new URL\n</code></pre>\n" }, { "answer_id": 338149, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>If available always use <code>https</code>, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. </p>\n\n<p><strong>1 Backup</strong></p>\n\n<p>Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database.</p>\n\n<p><strong>2 Set URL</strong></p>\n\n<p>Either under <em>Dashboard > Settings > General</em>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/688Qh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/688Qh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Or use constants in <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'WP_HOME','https://example.com' ); \ndefine( 'WP_SITEURL','https://example.com' ); \n</code></pre>\n\n<p><strong>3 Update database</strong> </p>\n\n<p>Either use the Search Replace DB tool: </p>\n\n<ul>\n<li><a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a> </li>\n<li><a href=\"https://github.com/interconnectit/Search-Replace-DB\" rel=\"nofollow noreferrer\">https://github.com/interconnectit/Search-Replace-DB</a> </li>\n</ul>\n\n<p>Or make use the WP-CLI command <code>search-replace</code>:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/search-replace/</a></li>\n</ul>\n\n<p>Example: <code>wp search-replace 'http://example.test' 'http://example.com'</code></p>\n\n<p>Both above options have an option to dry run, test, before making changes.</p>\n\n<p>Bonus, this plugin gets recommended a lot by people I generally trust:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-search-replace/</a> </li>\n</ul>\n\n<p>Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake.</p>\n\n<p><strong>4 Enforce redirecting to https</strong></p>\n\n<p>Either via adding the following lines to the <code>.htaccess</code>:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.</p>\n" } ]
2019/04/30
[ "https://wordpress.stackexchange.com/questions/336672", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/161485/" ]
We have a WordPress blog, google is indexing `http` as well as `https` urls. Now we are considering to either redirect `https` to `http`, or to use `https` and redirect all `http` traffic there. And how can we make all necessary changes to our WordPress installation?
If available always use `https`, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. **1 Backup** Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database. **2 Set URL** Either under *Dashboard > Settings > General*: [![enter image description here](https://i.stack.imgur.com/688Qh.png)](https://i.stack.imgur.com/688Qh.png) Or use constants in `wp-config.php`: ``` define( 'WP_HOME','https://example.com' ); define( 'WP_SITEURL','https://example.com' ); ``` **3 Update database** Either use the Search Replace DB tool: * <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/> * <https://github.com/interconnectit/Search-Replace-DB> Or make use the WP-CLI command `search-replace`: * <https://developer.wordpress.org/cli/commands/search-replace/> Example: `wp search-replace 'http://example.test' 'http://example.com'` Both above options have an option to dry run, test, before making changes. Bonus, this plugin gets recommended a lot by people I generally trust: * <https://wordpress.org/plugins/better-search-replace/> Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake. **4 Enforce redirecting to https** Either via adding the following lines to the `.htaccess`: ``` RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ``` Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.
336,674
<p>I'm working on a _products catalog` WP theme. I have a issue where my CTP has multiple subcategories, like for example:</p> <p><code>Vehicle -&gt; Vehicle type -&gt; Vehicle type -&gt; Vehicle year -&gt; Vehicle</code> or</p> <p><code>Car -&gt; SUV -&gt; VW -&gt; 2018 -&gt; T-Roc</code></p> <p>How can I create that structure? For now my <code>functions.php</code> looks like:</p> <pre><code>&lt;?php function custom_post_type() { $labels = array( 'name' =&gt; _x( 'Cars', 'Post Type General Name', 'twentythirteen' ), 'singular_name' =&gt; _x( 'Car', 'Post Type Singular Name', 'twentythirteen' ), 'menu_name' =&gt; __( 'Cars', 'twentythirteen' ), 'parent_item_colon' =&gt; __( 'Parent Car', 'twentythirteen' ), 'all_items' =&gt; __( 'All Cars', 'twentythirteen' ), 'view_item' =&gt; __( 'View Car', 'twentythirteen' ), 'add_new_item' =&gt; __( 'Add New Car', 'twentythirteen' ), 'add_new' =&gt; __( 'Add New', 'twentythirteen' ), 'edit_item' =&gt; __( 'Edit Car', 'twentythirteen' ), 'update_item' =&gt; __( 'Update Car', 'twentythirteen' ), 'search_items' =&gt; __( 'Search Car', 'twentythirteen' ), 'not_found' =&gt; __( 'Not Found', 'twentythirteen' ), 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'twentythirteen' ), ); $args = array( 'label' =&gt; __( 'cars', 'twentythirteen' ), 'description' =&gt; __( 'Cars news and reviews', 'twentythirteen' ), 'labels' =&gt; $labels, 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ), 'taxonomies' =&gt; array( 'category' ), 'hierarchical' =&gt; false, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_in_admin_bar' =&gt; true, 'menu_position' =&gt; 5, 'can_export' =&gt; true, 'has_archive' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'capability_type' =&gt; 'page', ); register_post_type( 'cars', $args ); } add_action( 'init', 'custom_post_type', 0 ); ?&gt; </code></pre>
[ { "answer_id": 336741, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": 0, "selected": false, "text": "<p>You can paste this code in the <strong>wp-config.php</strong> file to define your new URL. </p>\n\n<pre><code>define('WP_HOME','http://yoursite.com'); //Enter your new URL\ndefine('WP_SITEURL','http://yoursite.com'); //Enter your new URL\n</code></pre>\n" }, { "answer_id": 338149, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>If available always use <code>https</code>, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. </p>\n\n<p><strong>1 Backup</strong></p>\n\n<p>Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database.</p>\n\n<p><strong>2 Set URL</strong></p>\n\n<p>Either under <em>Dashboard > Settings > General</em>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/688Qh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/688Qh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Or use constants in <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'WP_HOME','https://example.com' ); \ndefine( 'WP_SITEURL','https://example.com' ); \n</code></pre>\n\n<p><strong>3 Update database</strong> </p>\n\n<p>Either use the Search Replace DB tool: </p>\n\n<ul>\n<li><a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a> </li>\n<li><a href=\"https://github.com/interconnectit/Search-Replace-DB\" rel=\"nofollow noreferrer\">https://github.com/interconnectit/Search-Replace-DB</a> </li>\n</ul>\n\n<p>Or make use the WP-CLI command <code>search-replace</code>:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/search-replace/</a></li>\n</ul>\n\n<p>Example: <code>wp search-replace 'http://example.test' 'http://example.com'</code></p>\n\n<p>Both above options have an option to dry run, test, before making changes.</p>\n\n<p>Bonus, this plugin gets recommended a lot by people I generally trust:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-search-replace/</a> </li>\n</ul>\n\n<p>Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake.</p>\n\n<p><strong>4 Enforce redirecting to https</strong></p>\n\n<p>Either via adding the following lines to the <code>.htaccess</code>:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.</p>\n" } ]
2019/04/30
[ "https://wordpress.stackexchange.com/questions/336674", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59688/" ]
I'm working on a \_products catalog` WP theme. I have a issue where my CTP has multiple subcategories, like for example: `Vehicle -> Vehicle type -> Vehicle type -> Vehicle year -> Vehicle` or `Car -> SUV -> VW -> 2018 -> T-Roc` How can I create that structure? For now my `functions.php` looks like: ``` <?php function custom_post_type() { $labels = array( 'name' => _x( 'Cars', 'Post Type General Name', 'twentythirteen' ), 'singular_name' => _x( 'Car', 'Post Type Singular Name', 'twentythirteen' ), 'menu_name' => __( 'Cars', 'twentythirteen' ), 'parent_item_colon' => __( 'Parent Car', 'twentythirteen' ), 'all_items' => __( 'All Cars', 'twentythirteen' ), 'view_item' => __( 'View Car', 'twentythirteen' ), 'add_new_item' => __( 'Add New Car', 'twentythirteen' ), 'add_new' => __( 'Add New', 'twentythirteen' ), 'edit_item' => __( 'Edit Car', 'twentythirteen' ), 'update_item' => __( 'Update Car', 'twentythirteen' ), 'search_items' => __( 'Search Car', 'twentythirteen' ), 'not_found' => __( 'Not Found', 'twentythirteen' ), 'not_found_in_trash' => __( 'Not found in Trash', 'twentythirteen' ), ); $args = array( 'label' => __( 'cars', 'twentythirteen' ), 'description' => __( 'Cars news and reviews', 'twentythirteen' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ), 'taxonomies' => array( 'category' ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'show_in_admin_bar' => true, 'menu_position' => 5, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'page', ); register_post_type( 'cars', $args ); } add_action( 'init', 'custom_post_type', 0 ); ?> ```
If available always use `https`, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. **1 Backup** Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database. **2 Set URL** Either under *Dashboard > Settings > General*: [![enter image description here](https://i.stack.imgur.com/688Qh.png)](https://i.stack.imgur.com/688Qh.png) Or use constants in `wp-config.php`: ``` define( 'WP_HOME','https://example.com' ); define( 'WP_SITEURL','https://example.com' ); ``` **3 Update database** Either use the Search Replace DB tool: * <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/> * <https://github.com/interconnectit/Search-Replace-DB> Or make use the WP-CLI command `search-replace`: * <https://developer.wordpress.org/cli/commands/search-replace/> Example: `wp search-replace 'http://example.test' 'http://example.com'` Both above options have an option to dry run, test, before making changes. Bonus, this plugin gets recommended a lot by people I generally trust: * <https://wordpress.org/plugins/better-search-replace/> Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake. **4 Enforce redirecting to https** Either via adding the following lines to the `.htaccess`: ``` RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ``` Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.
336,681
<p>I have the below code cobbled together. I've got it saved in a standalone PHP file so I can just run it on demand.</p> <p>It should be pretty clear what it's meant to do: loop over all posts of type 'product' and 'product-variation', then use preg_replace to remove all div and span tags.</p> <p>For some reason though, the below function doesn't seem to remove the tags:</p> <pre><code>&lt;?php require "wp-config.php"; // Post Types to include $args = array( 'posts_per_page' =&gt; '50', 'post_type' =&gt; array( 'product', 'product-variation' ) ); // The Query $query = new WP_Query( $args ); $posts = $query-&gt;posts; foreach($posts as $post) { $tags = array( 'div', 'span'); $content = $post-&gt;post_content; foreach ($tags as $tag) { $cleanedcontent = preg_replace('#&lt;\s*' . $tag . '[^&gt;]*&gt;.*?&lt;\s*/\s*'. $tag . '&gt;#msi', '', $content); } echo $cleanedcontent . '&lt;hr/&gt;'; // $cleaned_post = array( // 'ID' =&gt; $post-&gt;ID, // 'post_content' =&gt; $cleanedcontent // ); // wp_update_post( $cleaned_post ); } echo 'Done.' ?&gt; </code></pre> <p>Eventually I'll be using wp_update_post to save the "cleaned" content - that section is currently commented out.</p> <p>My code is partially based on this: <a href="https://wordpress.stackexchange.com/questions/248814/strip-only-specific-tags-like-p-but-keep-other-tags-like-br">strip only specific tags (like &lt;p&gt;), but keep other tags (like &lt;br/&gt;)</a></p> <p>Any ideas why my function isn't stripping out the div tags?</p>
[ { "answer_id": 336741, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": 0, "selected": false, "text": "<p>You can paste this code in the <strong>wp-config.php</strong> file to define your new URL. </p>\n\n<pre><code>define('WP_HOME','http://yoursite.com'); //Enter your new URL\ndefine('WP_SITEURL','http://yoursite.com'); //Enter your new URL\n</code></pre>\n" }, { "answer_id": 338149, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>If available always use <code>https</code>, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. </p>\n\n<p><strong>1 Backup</strong></p>\n\n<p>Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database.</p>\n\n<p><strong>2 Set URL</strong></p>\n\n<p>Either under <em>Dashboard > Settings > General</em>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/688Qh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/688Qh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Or use constants in <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'WP_HOME','https://example.com' ); \ndefine( 'WP_SITEURL','https://example.com' ); \n</code></pre>\n\n<p><strong>3 Update database</strong> </p>\n\n<p>Either use the Search Replace DB tool: </p>\n\n<ul>\n<li><a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a> </li>\n<li><a href=\"https://github.com/interconnectit/Search-Replace-DB\" rel=\"nofollow noreferrer\">https://github.com/interconnectit/Search-Replace-DB</a> </li>\n</ul>\n\n<p>Or make use the WP-CLI command <code>search-replace</code>:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/search-replace/</a></li>\n</ul>\n\n<p>Example: <code>wp search-replace 'http://example.test' 'http://example.com'</code></p>\n\n<p>Both above options have an option to dry run, test, before making changes.</p>\n\n<p>Bonus, this plugin gets recommended a lot by people I generally trust:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-search-replace/</a> </li>\n</ul>\n\n<p>Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake.</p>\n\n<p><strong>4 Enforce redirecting to https</strong></p>\n\n<p>Either via adding the following lines to the <code>.htaccess</code>:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.</p>\n" } ]
2019/04/30
[ "https://wordpress.stackexchange.com/questions/336681", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109355/" ]
I have the below code cobbled together. I've got it saved in a standalone PHP file so I can just run it on demand. It should be pretty clear what it's meant to do: loop over all posts of type 'product' and 'product-variation', then use preg\_replace to remove all div and span tags. For some reason though, the below function doesn't seem to remove the tags: ``` <?php require "wp-config.php"; // Post Types to include $args = array( 'posts_per_page' => '50', 'post_type' => array( 'product', 'product-variation' ) ); // The Query $query = new WP_Query( $args ); $posts = $query->posts; foreach($posts as $post) { $tags = array( 'div', 'span'); $content = $post->post_content; foreach ($tags as $tag) { $cleanedcontent = preg_replace('#<\s*' . $tag . '[^>]*>.*?<\s*/\s*'. $tag . '>#msi', '', $content); } echo $cleanedcontent . '<hr/>'; // $cleaned_post = array( // 'ID' => $post->ID, // 'post_content' => $cleanedcontent // ); // wp_update_post( $cleaned_post ); } echo 'Done.' ?> ``` Eventually I'll be using wp\_update\_post to save the "cleaned" content - that section is currently commented out. My code is partially based on this: [strip only specific tags (like <p>), but keep other tags (like <br/>)](https://wordpress.stackexchange.com/questions/248814/strip-only-specific-tags-like-p-but-keep-other-tags-like-br) Any ideas why my function isn't stripping out the div tags?
If available always use `https`, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. **1 Backup** Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database. **2 Set URL** Either under *Dashboard > Settings > General*: [![enter image description here](https://i.stack.imgur.com/688Qh.png)](https://i.stack.imgur.com/688Qh.png) Or use constants in `wp-config.php`: ``` define( 'WP_HOME','https://example.com' ); define( 'WP_SITEURL','https://example.com' ); ``` **3 Update database** Either use the Search Replace DB tool: * <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/> * <https://github.com/interconnectit/Search-Replace-DB> Or make use the WP-CLI command `search-replace`: * <https://developer.wordpress.org/cli/commands/search-replace/> Example: `wp search-replace 'http://example.test' 'http://example.com'` Both above options have an option to dry run, test, before making changes. Bonus, this plugin gets recommended a lot by people I generally trust: * <https://wordpress.org/plugins/better-search-replace/> Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake. **4 Enforce redirecting to https** Either via adding the following lines to the `.htaccess`: ``` RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ``` Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.
336,687
<p>I have a WordPress website with a custom post type called 'Courses'. </p> <p>On the WordPress dashboard page listing each course I've added a new column displaying a custom field, which is a date, called 'online start'. The online start date is a manually specified date that has no relation to the publish date of the post.</p> <p>I'd like to be able to sort the list of courses by the date now displayed in the 'online start' column.</p> <p>I have added the sort functionality, as included in the <code>add_sortable_date_column</code> function below, but the dates are not sorting in the correct order. I believe this is because I need to format the <code>$onlinestart</code> variable as a date, which I'm not quite sure how to do. </p> <p>Any help would be much appreciated.</p> <pre><code>//add custom field column to post list function add_admin_course_column_title( $columns ) { $columns['online_start'] = __( 'Online Start' ); return $columns; } add_filter( 'manage_courses_posts_columns', 'add_admin_course_column_title' ); function add_admin_course_column( $column, $post_id ) { if ( 'online_start' === $column ) { $onlinestart = get_post_meta( $post_id, 'online_start', true ); if ( ! $onlinestart ) { _e( 'n/a' ); } else { echo $onlinestart; } } } add_action( 'manage_courses_posts_custom_column', 'add_admin_course_column', 10, 2); function add_sortable_date_column( $columns ) { $columns['online_start'] = 'online_start'; return $columns; } add_filter( 'manage_edit-courses_sortable_columns', 'add_sortable_date_column'); </code></pre>
[ { "answer_id": 336741, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": 0, "selected": false, "text": "<p>You can paste this code in the <strong>wp-config.php</strong> file to define your new URL. </p>\n\n<pre><code>define('WP_HOME','http://yoursite.com'); //Enter your new URL\ndefine('WP_SITEURL','http://yoursite.com'); //Enter your new URL\n</code></pre>\n" }, { "answer_id": 338149, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>If available always use <code>https</code>, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. </p>\n\n<p><strong>1 Backup</strong></p>\n\n<p>Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database.</p>\n\n<p><strong>2 Set URL</strong></p>\n\n<p>Either under <em>Dashboard > Settings > General</em>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/688Qh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/688Qh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Or use constants in <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'WP_HOME','https://example.com' ); \ndefine( 'WP_SITEURL','https://example.com' ); \n</code></pre>\n\n<p><strong>3 Update database</strong> </p>\n\n<p>Either use the Search Replace DB tool: </p>\n\n<ul>\n<li><a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a> </li>\n<li><a href=\"https://github.com/interconnectit/Search-Replace-DB\" rel=\"nofollow noreferrer\">https://github.com/interconnectit/Search-Replace-DB</a> </li>\n</ul>\n\n<p>Or make use the WP-CLI command <code>search-replace</code>:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/search-replace/</a></li>\n</ul>\n\n<p>Example: <code>wp search-replace 'http://example.test' 'http://example.com'</code></p>\n\n<p>Both above options have an option to dry run, test, before making changes.</p>\n\n<p>Bonus, this plugin gets recommended a lot by people I generally trust:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-search-replace/</a> </li>\n</ul>\n\n<p>Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake.</p>\n\n<p><strong>4 Enforce redirecting to https</strong></p>\n\n<p>Either via adding the following lines to the <code>.htaccess</code>:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.</p>\n" } ]
2019/04/30
[ "https://wordpress.stackexchange.com/questions/336687", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78294/" ]
I have a WordPress website with a custom post type called 'Courses'. On the WordPress dashboard page listing each course I've added a new column displaying a custom field, which is a date, called 'online start'. The online start date is a manually specified date that has no relation to the publish date of the post. I'd like to be able to sort the list of courses by the date now displayed in the 'online start' column. I have added the sort functionality, as included in the `add_sortable_date_column` function below, but the dates are not sorting in the correct order. I believe this is because I need to format the `$onlinestart` variable as a date, which I'm not quite sure how to do. Any help would be much appreciated. ``` //add custom field column to post list function add_admin_course_column_title( $columns ) { $columns['online_start'] = __( 'Online Start' ); return $columns; } add_filter( 'manage_courses_posts_columns', 'add_admin_course_column_title' ); function add_admin_course_column( $column, $post_id ) { if ( 'online_start' === $column ) { $onlinestart = get_post_meta( $post_id, 'online_start', true ); if ( ! $onlinestart ) { _e( 'n/a' ); } else { echo $onlinestart; } } } add_action( 'manage_courses_posts_custom_column', 'add_admin_course_column', 10, 2); function add_sortable_date_column( $columns ) { $columns['online_start'] = 'online_start'; return $columns; } add_filter( 'manage_edit-courses_sortable_columns', 'add_sortable_date_column'); ```
If available always use `https`, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. **1 Backup** Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database. **2 Set URL** Either under *Dashboard > Settings > General*: [![enter image description here](https://i.stack.imgur.com/688Qh.png)](https://i.stack.imgur.com/688Qh.png) Or use constants in `wp-config.php`: ``` define( 'WP_HOME','https://example.com' ); define( 'WP_SITEURL','https://example.com' ); ``` **3 Update database** Either use the Search Replace DB tool: * <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/> * <https://github.com/interconnectit/Search-Replace-DB> Or make use the WP-CLI command `search-replace`: * <https://developer.wordpress.org/cli/commands/search-replace/> Example: `wp search-replace 'http://example.test' 'http://example.com'` Both above options have an option to dry run, test, before making changes. Bonus, this plugin gets recommended a lot by people I generally trust: * <https://wordpress.org/plugins/better-search-replace/> Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake. **4 Enforce redirecting to https** Either via adding the following lines to the `.htaccess`: ``` RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ``` Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.
336,708
<p>I'm running multisite. Looking to replace old URLs with new URLs for pulling a copy of the site form one environment to another environment. </p> <p><strong>Here is my command:</strong></p> <pre><code>wp search-replace --url=domain.com https://domain.com https://domain.test --all-tables --network --recurse-objects --skip-columns=guid --dry-run --allow-root --debug </code></pre> <p>WP-CLI is just taking my command and going to a new line, then returns nothing. </p> <p><strong>When I add <code>--debug</code> this is what I get back:</strong></p> <pre><code>Debug (bootstrap): No readable global config found (0.093s) Debug (bootstrap): Using project config: //wp-cli.yml (0.094s) Debug (bootstrap): argv: /usr/local/bin/wp search-replace --url=domain.com https://domain.com https://domain.test --all-tables --network --recurse-objects --skip-columns=guid --dry-run --allow-root --debug (0.094s) Debug (bootstrap): ABSPATH defined: /app/public/ (0.096s) Debug (bootstrap): Set URL: domain.com (0.097s) Debug (bootstrap): Begin WordPress load (0.102s) Debug (bootstrap): wp-config.php path: /app/public/wp-config.php (0.103s) </code></pre> <p>I run this very same command on another installation and it runs just fine. What could cause this to fail? Differences in <code>wp-config.php</code> by chance? Is there anything required in <code>wp-config.php</code> to run properly?</p>
[ { "answer_id": 336741, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": 0, "selected": false, "text": "<p>You can paste this code in the <strong>wp-config.php</strong> file to define your new URL. </p>\n\n<pre><code>define('WP_HOME','http://yoursite.com'); //Enter your new URL\ndefine('WP_SITEURL','http://yoursite.com'); //Enter your new URL\n</code></pre>\n" }, { "answer_id": 338149, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>If available always use <code>https</code>, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. </p>\n\n<p><strong>1 Backup</strong></p>\n\n<p>Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database.</p>\n\n<p><strong>2 Set URL</strong></p>\n\n<p>Either under <em>Dashboard > Settings > General</em>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/688Qh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/688Qh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Or use constants in <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'WP_HOME','https://example.com' ); \ndefine( 'WP_SITEURL','https://example.com' ); \n</code></pre>\n\n<p><strong>3 Update database</strong> </p>\n\n<p>Either use the Search Replace DB tool: </p>\n\n<ul>\n<li><a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a> </li>\n<li><a href=\"https://github.com/interconnectit/Search-Replace-DB\" rel=\"nofollow noreferrer\">https://github.com/interconnectit/Search-Replace-DB</a> </li>\n</ul>\n\n<p>Or make use the WP-CLI command <code>search-replace</code>:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/search-replace/</a></li>\n</ul>\n\n<p>Example: <code>wp search-replace 'http://example.test' 'http://example.com'</code></p>\n\n<p>Both above options have an option to dry run, test, before making changes.</p>\n\n<p>Bonus, this plugin gets recommended a lot by people I generally trust:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-search-replace/</a> </li>\n</ul>\n\n<p>Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake.</p>\n\n<p><strong>4 Enforce redirecting to https</strong></p>\n\n<p>Either via adding the following lines to the <code>.htaccess</code>:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.</p>\n" } ]
2019/04/30
[ "https://wordpress.stackexchange.com/questions/336708", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9579/" ]
I'm running multisite. Looking to replace old URLs with new URLs for pulling a copy of the site form one environment to another environment. **Here is my command:** ``` wp search-replace --url=domain.com https://domain.com https://domain.test --all-tables --network --recurse-objects --skip-columns=guid --dry-run --allow-root --debug ``` WP-CLI is just taking my command and going to a new line, then returns nothing. **When I add `--debug` this is what I get back:** ``` Debug (bootstrap): No readable global config found (0.093s) Debug (bootstrap): Using project config: //wp-cli.yml (0.094s) Debug (bootstrap): argv: /usr/local/bin/wp search-replace --url=domain.com https://domain.com https://domain.test --all-tables --network --recurse-objects --skip-columns=guid --dry-run --allow-root --debug (0.094s) Debug (bootstrap): ABSPATH defined: /app/public/ (0.096s) Debug (bootstrap): Set URL: domain.com (0.097s) Debug (bootstrap): Begin WordPress load (0.102s) Debug (bootstrap): wp-config.php path: /app/public/wp-config.php (0.103s) ``` I run this very same command on another installation and it runs just fine. What could cause this to fail? Differences in `wp-config.php` by chance? Is there anything required in `wp-config.php` to run properly?
If available always use `https`, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. **1 Backup** Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database. **2 Set URL** Either under *Dashboard > Settings > General*: [![enter image description here](https://i.stack.imgur.com/688Qh.png)](https://i.stack.imgur.com/688Qh.png) Or use constants in `wp-config.php`: ``` define( 'WP_HOME','https://example.com' ); define( 'WP_SITEURL','https://example.com' ); ``` **3 Update database** Either use the Search Replace DB tool: * <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/> * <https://github.com/interconnectit/Search-Replace-DB> Or make use the WP-CLI command `search-replace`: * <https://developer.wordpress.org/cli/commands/search-replace/> Example: `wp search-replace 'http://example.test' 'http://example.com'` Both above options have an option to dry run, test, before making changes. Bonus, this plugin gets recommended a lot by people I generally trust: * <https://wordpress.org/plugins/better-search-replace/> Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake. **4 Enforce redirecting to https** Either via adding the following lines to the `.htaccess`: ``` RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ``` Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.
336,709
<p>I'm building a custom shortcode in Wordpress. Essentially what I want this to do is the following:</p> <ol> <li>Dynamically pull values from a group of Advanced Custom Fields</li> <li>Output those values into a javascript array, comma-separated</li> </ol> <p>Where I'm getting stuck is that I can successfully run a loop over the group of fields and grab all the values and output them on a page. However, when I attempt to store them into a variable to be pulled into a javascript array (<code>$v</code> is stored in the <code>output</code> variable which is referenced in the <code>urls</code> array), it only returns one of those values.</p> <p>How can I get all the values from the <code>foreach ( $value as $v)</code> to list inside of the <code>urls</code> array, <em>with comma separation</em>? Any help would be appreciated :)</p> <pre><code>add_shortcode('training-player', 'training_player'); // Add shortcode for Diagnostic media playlist function training_player() { $author_id = get_the_author_meta('ID'); $fields = acf_get_fields(405); if( $fields ) { echo '&lt;div id="player"&gt;&lt;/div&gt;'; foreach( $fields as $field ) { $value = get_field( $field['name'], 'user_'. $author_id ); if(!empty($value)) { if ($value) { foreach ( $value as $v) { echo $v; } } } } echo " &lt;script src='https://luwes.github.io/vimeowrap.js/vimeowrap.js'&gt;&lt;/script&gt; &lt;script src='https://luwes.github.io/vimeowrap.js/vimeowrap.playlist.js'&gt;&lt;/script&gt; &lt;script&gt; var output = '$v'; console.log(output) vimeowrap('player').setup({ urls: [ output ], plugins: { 'playlist':{} } }); &lt;/script&gt; "; } } </code></pre>
[ { "answer_id": 336741, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": 0, "selected": false, "text": "<p>You can paste this code in the <strong>wp-config.php</strong> file to define your new URL. </p>\n\n<pre><code>define('WP_HOME','http://yoursite.com'); //Enter your new URL\ndefine('WP_SITEURL','http://yoursite.com'); //Enter your new URL\n</code></pre>\n" }, { "answer_id": 338149, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>If available always use <code>https</code>, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. </p>\n\n<p><strong>1 Backup</strong></p>\n\n<p>Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database.</p>\n\n<p><strong>2 Set URL</strong></p>\n\n<p>Either under <em>Dashboard > Settings > General</em>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/688Qh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/688Qh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Or use constants in <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'WP_HOME','https://example.com' ); \ndefine( 'WP_SITEURL','https://example.com' ); \n</code></pre>\n\n<p><strong>3 Update database</strong> </p>\n\n<p>Either use the Search Replace DB tool: </p>\n\n<ul>\n<li><a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a> </li>\n<li><a href=\"https://github.com/interconnectit/Search-Replace-DB\" rel=\"nofollow noreferrer\">https://github.com/interconnectit/Search-Replace-DB</a> </li>\n</ul>\n\n<p>Or make use the WP-CLI command <code>search-replace</code>:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/search-replace/</a></li>\n</ul>\n\n<p>Example: <code>wp search-replace 'http://example.test' 'http://example.com'</code></p>\n\n<p>Both above options have an option to dry run, test, before making changes.</p>\n\n<p>Bonus, this plugin gets recommended a lot by people I generally trust:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-search-replace/</a> </li>\n</ul>\n\n<p>Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake.</p>\n\n<p><strong>4 Enforce redirecting to https</strong></p>\n\n<p>Either via adding the following lines to the <code>.htaccess</code>:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.</p>\n" } ]
2019/04/30
[ "https://wordpress.stackexchange.com/questions/336709", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167100/" ]
I'm building a custom shortcode in Wordpress. Essentially what I want this to do is the following: 1. Dynamically pull values from a group of Advanced Custom Fields 2. Output those values into a javascript array, comma-separated Where I'm getting stuck is that I can successfully run a loop over the group of fields and grab all the values and output them on a page. However, when I attempt to store them into a variable to be pulled into a javascript array (`$v` is stored in the `output` variable which is referenced in the `urls` array), it only returns one of those values. How can I get all the values from the `foreach ( $value as $v)` to list inside of the `urls` array, *with comma separation*? Any help would be appreciated :) ``` add_shortcode('training-player', 'training_player'); // Add shortcode for Diagnostic media playlist function training_player() { $author_id = get_the_author_meta('ID'); $fields = acf_get_fields(405); if( $fields ) { echo '<div id="player"></div>'; foreach( $fields as $field ) { $value = get_field( $field['name'], 'user_'. $author_id ); if(!empty($value)) { if ($value) { foreach ( $value as $v) { echo $v; } } } } echo " <script src='https://luwes.github.io/vimeowrap.js/vimeowrap.js'></script> <script src='https://luwes.github.io/vimeowrap.js/vimeowrap.playlist.js'></script> <script> var output = '$v'; console.log(output) vimeowrap('player').setup({ urls: [ output ], plugins: { 'playlist':{} } }); </script> "; } } ```
If available always use `https`, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. **1 Backup** Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database. **2 Set URL** Either under *Dashboard > Settings > General*: [![enter image description here](https://i.stack.imgur.com/688Qh.png)](https://i.stack.imgur.com/688Qh.png) Or use constants in `wp-config.php`: ``` define( 'WP_HOME','https://example.com' ); define( 'WP_SITEURL','https://example.com' ); ``` **3 Update database** Either use the Search Replace DB tool: * <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/> * <https://github.com/interconnectit/Search-Replace-DB> Or make use the WP-CLI command `search-replace`: * <https://developer.wordpress.org/cli/commands/search-replace/> Example: `wp search-replace 'http://example.test' 'http://example.com'` Both above options have an option to dry run, test, before making changes. Bonus, this plugin gets recommended a lot by people I generally trust: * <https://wordpress.org/plugins/better-search-replace/> Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake. **4 Enforce redirecting to https** Either via adding the following lines to the `.htaccess`: ``` RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ``` Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.
336,710
<p>Is there a way to remove &amp; redirect any users of a site from accessing</p> <pre><code>https://www.example.com/wp-admin/ </code></pre> <p>Unless there id is one, i have seen some examples floating around the ask if admin-ajax is being used if so redirect. how ever this is not approach i wish to make as im using admin ajax on the front end for some admins. i just don't wish them to see anything to do with the backend of wordpress.</p> <p>Only userid 1 should have access to wp-admin.</p>
[ { "answer_id": 336741, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": 0, "selected": false, "text": "<p>You can paste this code in the <strong>wp-config.php</strong> file to define your new URL. </p>\n\n<pre><code>define('WP_HOME','http://yoursite.com'); //Enter your new URL\ndefine('WP_SITEURL','http://yoursite.com'); //Enter your new URL\n</code></pre>\n" }, { "answer_id": 338149, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>If available always use <code>https</code>, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. </p>\n\n<p><strong>1 Backup</strong></p>\n\n<p>Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database.</p>\n\n<p><strong>2 Set URL</strong></p>\n\n<p>Either under <em>Dashboard > Settings > General</em>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/688Qh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/688Qh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Or use constants in <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'WP_HOME','https://example.com' ); \ndefine( 'WP_SITEURL','https://example.com' ); \n</code></pre>\n\n<p><strong>3 Update database</strong> </p>\n\n<p>Either use the Search Replace DB tool: </p>\n\n<ul>\n<li><a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a> </li>\n<li><a href=\"https://github.com/interconnectit/Search-Replace-DB\" rel=\"nofollow noreferrer\">https://github.com/interconnectit/Search-Replace-DB</a> </li>\n</ul>\n\n<p>Or make use the WP-CLI command <code>search-replace</code>:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/search-replace/</a></li>\n</ul>\n\n<p>Example: <code>wp search-replace 'http://example.test' 'http://example.com'</code></p>\n\n<p>Both above options have an option to dry run, test, before making changes.</p>\n\n<p>Bonus, this plugin gets recommended a lot by people I generally trust:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-search-replace/</a> </li>\n</ul>\n\n<p>Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake.</p>\n\n<p><strong>4 Enforce redirecting to https</strong></p>\n\n<p>Either via adding the following lines to the <code>.htaccess</code>:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.</p>\n" } ]
2019/04/30
[ "https://wordpress.stackexchange.com/questions/336710", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167096/" ]
Is there a way to remove & redirect any users of a site from accessing ``` https://www.example.com/wp-admin/ ``` Unless there id is one, i have seen some examples floating around the ask if admin-ajax is being used if so redirect. how ever this is not approach i wish to make as im using admin ajax on the front end for some admins. i just don't wish them to see anything to do with the backend of wordpress. Only userid 1 should have access to wp-admin.
If available always use `https`, it is securer for obvious reasons, it is better received by search engines and browsers nowadays, it is just overall preferable. **1 Backup** Should go without saying, but backup your database. There is always a possibility that something goes wrong. Additionally, make sure you have access – ssh, ftp, etc – to your files, and you have a possibility to access – ssh (mysql, wp-cli), phpmyadmin, etc – the database. **2 Set URL** Either under *Dashboard > Settings > General*: [![enter image description here](https://i.stack.imgur.com/688Qh.png)](https://i.stack.imgur.com/688Qh.png) Or use constants in `wp-config.php`: ``` define( 'WP_HOME','https://example.com' ); define( 'WP_SITEURL','https://example.com' ); ``` **3 Update database** Either use the Search Replace DB tool: * <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/> * <https://github.com/interconnectit/Search-Replace-DB> Or make use the WP-CLI command `search-replace`: * <https://developer.wordpress.org/cli/commands/search-replace/> Example: `wp search-replace 'http://example.test' 'http://example.com'` Both above options have an option to dry run, test, before making changes. Bonus, this plugin gets recommended a lot by people I generally trust: * <https://wordpress.org/plugins/better-search-replace/> Note: I personally have no experience with the plugin; I'm adding it for completeness’ sake. **4 Enforce redirecting to https** Either via adding the following lines to the `.htaccess`: ``` RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ``` Or you can generally set this via your server administration gui, so plesk, cpanel, webmin or whatever your hosting provider is offering.
336,766
<p><a href="https://i.stack.imgur.com/huVKs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/huVKs.png" alt="enter image description here"></a></p> <p>The problem we are experiencing is very new to us. We did not experience this ever before with our website or with our web server (in last 8 years). Just recently for last 2 week we have this issue and it happened over 3 times.</p> <p><strong>Problem Description</strong></p> <p>Our site is experiencing "White Screen of Death". We do not see any error. Please see screenshot for better understanding. its just that. The site just tries to load but cannot.</p> <p><a href="https://i.stack.imgur.com/uFYj2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uFYj2.png" alt="enter image description here"></a></p> <p><strong>Findings : what we have done to fix this</strong></p> <p>We can fix it (temporarily) if we reboot the server (restarting the whole virtual machine).</p> <p>But this is not a viable solution . As we have other Wordpress and non-Wordpress websites in that server which does not have that issue. And rebooting the server means all sites in the server are down for 5-10 minutes. After rebooting the server site comes back and works fine as usual.</p> <p>But This problem occurred at least 3 times since last week. We cannot replicate the error by clicking on any page. There is no particular time of the day when this happens.</p> <p><strong>Further information</strong> </p> <p>The only significant change we can think of is upgrading the PHP version for the site from 5.3 to 7.2 in our web server. FYI we have upgraded the PHP version last month. And for approximately 3 weeks we have not seen this or any other issue. The wordpress version of the site is 4.9.1</p> <p>Webserver - Apache </p> <p>Database - My SQL 5.1.7</p> <p>We have plenty free disk space in the server</p> <p>We have tried to look in to the error log at the time of the problem . but we could not find any thing relevant. This is the error we could see on error log. Although I didn't think it was the issue but I have corrected the SQL query mentioned in the error log. But we have faced the same issue again today.</p> <p>I can see the following log files from my cpanel</p> <p>Webserver error log <a href="https://i.stack.imgur.com/ZTFln.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZTFln.png" alt="enter image description here"></a> Web server ssl error log <a href="https://i.stack.imgur.com/mNp6s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mNp6s.png" alt="enter image description here"></a></p> <p>web server transfer log <a href="https://i.stack.imgur.com/XqTIB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XqTIB.png" alt="enter image description here"></a></p> <p>webserver ssl transfer log <a href="https://i.stack.imgur.com/MzAPH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MzAPH.png" alt="enter image description here"></a></p> <pre><code>[Tue Apr 23 13:48:35 2019] [error] [client 101.180.145.79] FastCGI: server "/var/run/psychicf-remi-safe-php72.fcgi" stderr: PHP message: WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY number DESC' at line 1 for query SELECT * FROM view_site_numbers WHERE campaign_id = "7" AND `use` = "PPC" LIMIT 2 ORDER BY number DESC made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/psychicFuture/css/content-all-horoscopes.php'), get_header, locate_template, load_template, require_once('/themes/psychicFuture/header.php'), do_shortcode, preg_replace_callback, do_shortcode_tag, get_prs_number_register, referer: https://thehoroscopejunkie.ca/weekly_horoscopes.html </code></pre> <p>PHP Compatibility checker plugin showing the following error <a href="https://i.stack.imgur.com/F8Fao.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F8Fao.png" alt="enter image description here"></a> I do not know where to look at. Can you please advice ?</p>
[ { "answer_id": 336808, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>I'd recommend updating WP, and all themes and plugins to current versions. And you might check the version of PHP actually being used. (create a template and replace the 'loop' with a phpinfo() function, or look via your hosting cpanel).</p>\n\n<p>Perhaps the 'fastcgi' option is not good for your site, so try going back to 'regular' PHP 7.x.</p>\n\n<p>The error log should give you more info, but you mentioned already looking there. Your hosting support might be helpful. (If you have hosting for your site; although it appears you are self-hosted.)</p>\n" }, { "answer_id": 336810, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 1, "selected": false, "text": "<p>I don't think this can provide a solution but hopefully I can help you troubleshoot a little.</p>\n\n<p>Firstly, let's go over debugging:</p>\n\n<h3>Debugging</h3>\n\n<p>You're saying \"white screen of death\", but the screenshot you provided looks more like it's hanging while trying to load the page. Typically, the WSOD appears as exactly that - a completely blank page. Your screenshot shows the default \"New Tab\" view and a loading spinner, suggesting that the server is not responding. </p>\n\n<p>If you leave this page \"loading\" for a bit of time (several minutes at least), do you get any kind of error? Usually, Chrome will eventually kick in with a message like \"Too many redirects\" or something similar when it finally gives up <em>or</em> does it actually finally fail with a white screen?</p>\n\nwp-admin and White Screen\n\n<p>If it is a white screen, what do you get when trying to go to <code>/wp-admin/</code>? This is important, because WordPress will surface some debugging-related information if there is a problem in your installation's database setup when you access <code>/wp-admin/</code> that would otherwise not appear on the front-end.</p>\n\nWordPress debug log\n\n<p>WordPress also includes internal debugging that is disabled by default. In your question, you note that you checked the error logs, but didn't specify which ones. It could be helpful to do the following:</p>\n\n<ul>\n<li>Add these lines to <code>wp-config.php</code>:</li>\n</ul>\n\n<pre><code>define( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n\n<p>This will enable debug logging to the file <code>/wp-content/debug.log</code>. Try loading your site again and waiting until the load fails (server timeout, too many redirects, etc). Check the log to see if you find any errors</p>\n\n<h3>The SQL Error</h3>\n\n<p>While likely <em>not</em> the cause of your issues, the SQL error can be easily handled. Your custom query should have the <code>LIMIT</code> statement <em>after</em> the <code>ORDER BY</code> clause:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT * FROM view_site_numbers WHERE campaign_id = \"7\" AND `use` = \"PPC\" ORDER BY number DESC LIMIT 2\n</code></pre>\n\n<h3>Further investigation</h3>\n\n<p>As others have noted, it may be worth looking at stackoverflow.com for more help, as the issue definitely \"feels\" server-related. You said you recently upgraded your PHP version - it might not hurt to see if you can downgrade and see if the issue persists, however, I can't think of anything off the top of my head that might cause an issue like this (if it is infinite loading and not a direct white screen). </p>\n\n<p>Also, given that it only happens intermittently, makes me think it's less to do with the application code than something going on with the server itself. If you have access to access logs you could check for DDOS attempts. You should also check your processes to see if anything is leaking and eating more and more memory without being properly stopped, or just running forever and eating away at your CPU.</p>\n\n<p>Good luck!</p>\n" } ]
2019/05/01
[ "https://wordpress.stackexchange.com/questions/336766", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167148/" ]
[![enter image description here](https://i.stack.imgur.com/huVKs.png)](https://i.stack.imgur.com/huVKs.png) The problem we are experiencing is very new to us. We did not experience this ever before with our website or with our web server (in last 8 years). Just recently for last 2 week we have this issue and it happened over 3 times. **Problem Description** Our site is experiencing "White Screen of Death". We do not see any error. Please see screenshot for better understanding. its just that. The site just tries to load but cannot. [![enter image description here](https://i.stack.imgur.com/uFYj2.png)](https://i.stack.imgur.com/uFYj2.png) **Findings : what we have done to fix this** We can fix it (temporarily) if we reboot the server (restarting the whole virtual machine). But this is not a viable solution . As we have other Wordpress and non-Wordpress websites in that server which does not have that issue. And rebooting the server means all sites in the server are down for 5-10 minutes. After rebooting the server site comes back and works fine as usual. But This problem occurred at least 3 times since last week. We cannot replicate the error by clicking on any page. There is no particular time of the day when this happens. **Further information** The only significant change we can think of is upgrading the PHP version for the site from 5.3 to 7.2 in our web server. FYI we have upgraded the PHP version last month. And for approximately 3 weeks we have not seen this or any other issue. The wordpress version of the site is 4.9.1 Webserver - Apache Database - My SQL 5.1.7 We have plenty free disk space in the server We have tried to look in to the error log at the time of the problem . but we could not find any thing relevant. This is the error we could see on error log. Although I didn't think it was the issue but I have corrected the SQL query mentioned in the error log. But we have faced the same issue again today. I can see the following log files from my cpanel Webserver error log [![enter image description here](https://i.stack.imgur.com/ZTFln.png)](https://i.stack.imgur.com/ZTFln.png) Web server ssl error log [![enter image description here](https://i.stack.imgur.com/mNp6s.png)](https://i.stack.imgur.com/mNp6s.png) web server transfer log [![enter image description here](https://i.stack.imgur.com/XqTIB.png)](https://i.stack.imgur.com/XqTIB.png) webserver ssl transfer log [![enter image description here](https://i.stack.imgur.com/MzAPH.png)](https://i.stack.imgur.com/MzAPH.png) ``` [Tue Apr 23 13:48:35 2019] [error] [client 101.180.145.79] FastCGI: server "/var/run/psychicf-remi-safe-php72.fcgi" stderr: PHP message: WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY number DESC' at line 1 for query SELECT * FROM view_site_numbers WHERE campaign_id = "7" AND `use` = "PPC" LIMIT 2 ORDER BY number DESC made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/psychicFuture/css/content-all-horoscopes.php'), get_header, locate_template, load_template, require_once('/themes/psychicFuture/header.php'), do_shortcode, preg_replace_callback, do_shortcode_tag, get_prs_number_register, referer: https://thehoroscopejunkie.ca/weekly_horoscopes.html ``` PHP Compatibility checker plugin showing the following error [![enter image description here](https://i.stack.imgur.com/F8Fao.png)](https://i.stack.imgur.com/F8Fao.png) I do not know where to look at. Can you please advice ?
I don't think this can provide a solution but hopefully I can help you troubleshoot a little. Firstly, let's go over debugging: ### Debugging You're saying "white screen of death", but the screenshot you provided looks more like it's hanging while trying to load the page. Typically, the WSOD appears as exactly that - a completely blank page. Your screenshot shows the default "New Tab" view and a loading spinner, suggesting that the server is not responding. If you leave this page "loading" for a bit of time (several minutes at least), do you get any kind of error? Usually, Chrome will eventually kick in with a message like "Too many redirects" or something similar when it finally gives up *or* does it actually finally fail with a white screen? wp-admin and White Screen If it is a white screen, what do you get when trying to go to `/wp-admin/`? This is important, because WordPress will surface some debugging-related information if there is a problem in your installation's database setup when you access `/wp-admin/` that would otherwise not appear on the front-end. WordPress debug log WordPress also includes internal debugging that is disabled by default. In your question, you note that you checked the error logs, but didn't specify which ones. It could be helpful to do the following: * Add these lines to `wp-config.php`: ``` define( 'WP_DEBUG', true ); define( 'WP_DEBUG_LOG', true ); ``` This will enable debug logging to the file `/wp-content/debug.log`. Try loading your site again and waiting until the load fails (server timeout, too many redirects, etc). Check the log to see if you find any errors ### The SQL Error While likely *not* the cause of your issues, the SQL error can be easily handled. Your custom query should have the `LIMIT` statement *after* the `ORDER BY` clause: ```sql SELECT * FROM view_site_numbers WHERE campaign_id = "7" AND `use` = "PPC" ORDER BY number DESC LIMIT 2 ``` ### Further investigation As others have noted, it may be worth looking at stackoverflow.com for more help, as the issue definitely "feels" server-related. You said you recently upgraded your PHP version - it might not hurt to see if you can downgrade and see if the issue persists, however, I can't think of anything off the top of my head that might cause an issue like this (if it is infinite loading and not a direct white screen). Also, given that it only happens intermittently, makes me think it's less to do with the application code than something going on with the server itself. If you have access to access logs you could check for DDOS attempts. You should also check your processes to see if anything is leaking and eating more and more memory without being properly stopped, or just running forever and eating away at your CPU. Good luck!
336,780
<p>I have added a meta box in the page edit section:</p> <pre><code>add_meta_box('custom_section_box', 'Sections', array($this, 'section_box'), 'page','normal','high'); </code></pre> <p>Within the box, there is a wp_editor call:</p> <pre><code>$tinymce_options = array('plugins' =&gt; "table,lists,link,textcolor,hr", 'toolbar1'=&gt;"fontsizeselect,forecolor,backcolor,bold,italic,underline,strikethrough,alignleft,aligncenter,alignright,alignjustify",'toolbar2'=&gt;"blockquote,hr,table,bullist,numlist,undo,redo,link,unlink"); $editor_config= array('teeny'=&gt;true, 'textarea_rows'=&gt;10, 'editor_class'=&gt;'csec_text', 'textarea_name'=&gt;'csec_body', 'wpautop'=&gt;false, 'tinymce'=&gt;$tinymce_options); wp_editor(html_entity_decode(stripslashes($vals['content'])), 'csec_body', $editor_config); </code></pre> <p>Everything is working fine, but when I add a gallery through the media button, it displays the gallery shortcode only (like [gallery link="file" ids="759,760,761"]). There is no usual display of the gallery as in the normal page editor with edit/delete buttons.</p> <p>I had tried to add the <strong>do_shortcode</strong> to pass the value in wp_editor, but that displays the full html instead. Also other shortcodes are rendered as html.</p> <p>Can you please help?</p>
[ { "answer_id": 336786, "author": "anton", "author_id": 97934, "author_profile": "https://wordpress.stackexchange.com/users/97934", "pm_score": 1, "selected": false, "text": "<p>Make sure <code>tinymce</code> option has a valid value. <br/>\nRemove it or set it to true if you don't pass any parameters to tinymce <br/></p>\n\n<pre><code>$editor_config = array(\n 'teeny'=&gt;true,\n 'textarea_rows'=&gt;10, \n 'editor_class'=&gt;'csec_text', \n 'textarea_name'=&gt;'csec_body', \n 'wpautop'=&gt;false, \n 'tinymce'=&gt;$tinymce_options //THIS OPTION SHOULD BE VALID\n);\n</code></pre>\n\n<p><strong>Edit:</strong><br/><br/>\nMade a small research. Add <code>wpview</code> in plugins argument of tinymce options. <br/></p>\n\n<pre><code>$tinymce_options = array(\n 'plugins' =&gt; \"wpview,lists,link,textcolor,hr\",\n //all other options\n}\n</code></pre>\n\n<p><br/>Also, there is no tinymce <code>table</code> plugin.<br/>\nList of available plugins: <br/></p>\n\n<pre><code>'charmap',\n'colorpicker',\n'hr',\n'lists',\n'media',\n'paste',\n'tabfocus',\n'textcolor',\n'fullscreen',\n'wordpress',\n'wpautoresize',\n'wpeditimage',\n'wpemoji',\n'wpgallery',\n'wplink',\n'wpdialogs',\n'wptextpattern',\n'wpview',\n</code></pre>\n" }, { "answer_id": 336793, "author": "sariDon", "author_id": 92425, "author_profile": "https://wordpress.stackexchange.com/users/92425", "pm_score": 1, "selected": true, "text": "<p>This piece works perfectly:</p>\n\n<pre><code>$tinymce_options = array(\n'plugins' =&gt; \"paste,lists,link,textcolor,hr,media,wordpress,wpeditimage,wpgallery,wpdialogs,wplink,wpview\",\n'wordpress_adv_hidden'=&gt; false,\n'toolbar1'=&gt;\"formatselect,fontsizeselect,forecolor,backcolor,bold,italic,underline,strikethrough,alignleft,aligncenter,alignright,alignjustify,wp_adv\",\n'toolbar2'=&gt;\"blockquote,hr,table,bullist,numlist,outdent,indent,undo,redo,link,unlink,wp_fullscreen,wp_help\"\n);\n</code></pre>\n\n<p>Note I have added few wordpress related plugins in the tinymce options.</p>\n" } ]
2019/05/01
[ "https://wordpress.stackexchange.com/questions/336780", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92425/" ]
I have added a meta box in the page edit section: ``` add_meta_box('custom_section_box', 'Sections', array($this, 'section_box'), 'page','normal','high'); ``` Within the box, there is a wp\_editor call: ``` $tinymce_options = array('plugins' => "table,lists,link,textcolor,hr", 'toolbar1'=>"fontsizeselect,forecolor,backcolor,bold,italic,underline,strikethrough,alignleft,aligncenter,alignright,alignjustify",'toolbar2'=>"blockquote,hr,table,bullist,numlist,undo,redo,link,unlink"); $editor_config= array('teeny'=>true, 'textarea_rows'=>10, 'editor_class'=>'csec_text', 'textarea_name'=>'csec_body', 'wpautop'=>false, 'tinymce'=>$tinymce_options); wp_editor(html_entity_decode(stripslashes($vals['content'])), 'csec_body', $editor_config); ``` Everything is working fine, but when I add a gallery through the media button, it displays the gallery shortcode only (like [gallery link="file" ids="759,760,761"]). There is no usual display of the gallery as in the normal page editor with edit/delete buttons. I had tried to add the **do\_shortcode** to pass the value in wp\_editor, but that displays the full html instead. Also other shortcodes are rendered as html. Can you please help?
This piece works perfectly: ``` $tinymce_options = array( 'plugins' => "paste,lists,link,textcolor,hr,media,wordpress,wpeditimage,wpgallery,wpdialogs,wplink,wpview", 'wordpress_adv_hidden'=> false, 'toolbar1'=>"formatselect,fontsizeselect,forecolor,backcolor,bold,italic,underline,strikethrough,alignleft,aligncenter,alignright,alignjustify,wp_adv", 'toolbar2'=>"blockquote,hr,table,bullist,numlist,outdent,indent,undo,redo,link,unlink,wp_fullscreen,wp_help" ); ``` Note I have added few wordpress related plugins in the tinymce options.
336,787
<p>Below is my code:</p> <pre><code> wp_nav_menu( array( 'menu', _('My Custom Header Menu'), 'theme_location' =&gt; 'my_custom_location', ) ); </code></pre> <hr> <p>And as result, I obtain all Wordpress page's menu link instead of the menu of My Custom Header Menu.</p>
[ { "answer_id": 336788, "author": "Amine Faiz", "author_id": 66813, "author_profile": "https://wordpress.stackexchange.com/users/66813", "pm_score": 1, "selected": false, "text": "<p>First check if you have already registred a menu location with the same name : </p>\n\n<pre><code>register_nav_menus( array(\n 'my_custom_location' =&gt; 'My Custom location',\n) );\n</code></pre>\n\n<p>Secondly, i don't think you need this : 'menu', _('My Custom Header Menu'), and instead just keep your code as bellow : </p>\n\n<pre><code>wp_nav_menu( array(\n 'theme_location' =&gt; 'my_custom_location', \n) );\n</code></pre>\n" }, { "answer_id": 336789, "author": "anton", "author_id": 97934, "author_profile": "https://wordpress.stackexchange.com/users/97934", "pm_score": 3, "selected": true, "text": "<p><strong>Register your navigation menu</strong> <br/><br/>\nAdd this code to your functions.php file. </p>\n\n<pre><code>function my_custom_new_menu() {\n register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));\n}\nadd_action( 'init', 'my_custom_new_menu' );\n</code></pre>\n\n<p><strong>Create new menu</strong> <br/><br/>\nYou can now go to Appearance » Menus page in your WordPress admin and try to create or edit a new menu. You will see ‘My Custom Menu’ as theme location option. <br/><br/>\n<strong>Display new menu</strong> <br/><br/></p>\n\n<pre><code>wp_nav_menu( array( \n 'theme_location' =&gt; 'my-custom-menu') \n); \n</code></pre>\n" } ]
2019/05/01
[ "https://wordpress.stackexchange.com/questions/336787", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167169/" ]
Below is my code: ``` wp_nav_menu( array( 'menu', _('My Custom Header Menu'), 'theme_location' => 'my_custom_location', ) ); ``` --- And as result, I obtain all Wordpress page's menu link instead of the menu of My Custom Header Menu.
**Register your navigation menu** Add this code to your functions.php file. ``` function my_custom_new_menu() { register_nav_menu('my-custom-menu',__( 'My Custom Menu' )); } add_action( 'init', 'my_custom_new_menu' ); ``` **Create new menu** You can now go to Appearance » Menus page in your WordPress admin and try to create or edit a new menu. You will see ‘My Custom Menu’ as theme location option. **Display new menu** ``` wp_nav_menu( array( 'theme_location' => 'my-custom-menu') ); ```
336,801
<p>I have a WP installation that needs moving to a new site URL. </p> <p>I have tried the usual methods listed on <a href="https://codex.wordpress.org/Changing_The_Site_URL" rel="nofollow noreferrer">this codex</a>. All of them produce the same problem. When I hit a link like this on the site:</p> <p><code>&lt;a href="https://site.mydomain.com/path/to/post"&gt;</code></p> <p>The web server receives says:</p> <p><code>The requested URL /path/to/post/ was not found on this server.</code></p> <p>This is even if I paste the URL into the browser.</p> <p>Note that some URLs DO work, for example to this CSS file:</p> <p><code>http://site.mydomain.com/wp-includes/css/dist/block-library/style.min.css?ver=5.1.1</code></p> <p>But NOT to blog posts.</p> <p><strong>EDIT with more info</strong></p> <p>When I view the source of the pages, I see that all hrefs are in fact correct. However, when clicked on, the links to the posts (but not to CSS files) are missing the "http://" prefix and are instead rendered as server-root relative URLs.</p> <p>So my change to the siteurl option <strong>is</strong> being made, but something about the site in question is breaking some (but not all) URLs. </p> <p>I have since tried a vanilla fresh install of WP and changed the siteurl for that at it does <strong>NOT</strong> exhibit this problem so I assume it's something in the WP install for this site.</p> <p><strong>Further forensics</strong></p> <p>The problem persists even when I try the following:</p> <ul> <li>Removing all .htaccess files</li> <li>Deactivating all plugins</li> <li>Viewed using incognito mode.</li> <li>Using another web browser to load the site (had been using Chrome, installed and used a fresh installation of Firefox)</li> <li>Switching to a different theme (twentynineteen)</li> <li>Putting one of the broken URLs into a plain .html test file</li> </ul>
[ { "answer_id": 336788, "author": "Amine Faiz", "author_id": 66813, "author_profile": "https://wordpress.stackexchange.com/users/66813", "pm_score": 1, "selected": false, "text": "<p>First check if you have already registred a menu location with the same name : </p>\n\n<pre><code>register_nav_menus( array(\n 'my_custom_location' =&gt; 'My Custom location',\n) );\n</code></pre>\n\n<p>Secondly, i don't think you need this : 'menu', _('My Custom Header Menu'), and instead just keep your code as bellow : </p>\n\n<pre><code>wp_nav_menu( array(\n 'theme_location' =&gt; 'my_custom_location', \n) );\n</code></pre>\n" }, { "answer_id": 336789, "author": "anton", "author_id": 97934, "author_profile": "https://wordpress.stackexchange.com/users/97934", "pm_score": 3, "selected": true, "text": "<p><strong>Register your navigation menu</strong> <br/><br/>\nAdd this code to your functions.php file. </p>\n\n<pre><code>function my_custom_new_menu() {\n register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));\n}\nadd_action( 'init', 'my_custom_new_menu' );\n</code></pre>\n\n<p><strong>Create new menu</strong> <br/><br/>\nYou can now go to Appearance » Menus page in your WordPress admin and try to create or edit a new menu. You will see ‘My Custom Menu’ as theme location option. <br/><br/>\n<strong>Display new menu</strong> <br/><br/></p>\n\n<pre><code>wp_nav_menu( array( \n 'theme_location' =&gt; 'my-custom-menu') \n); \n</code></pre>\n" } ]
2019/05/01
[ "https://wordpress.stackexchange.com/questions/336801", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167177/" ]
I have a WP installation that needs moving to a new site URL. I have tried the usual methods listed on [this codex](https://codex.wordpress.org/Changing_The_Site_URL). All of them produce the same problem. When I hit a link like this on the site: `<a href="https://site.mydomain.com/path/to/post">` The web server receives says: `The requested URL /path/to/post/ was not found on this server.` This is even if I paste the URL into the browser. Note that some URLs DO work, for example to this CSS file: `http://site.mydomain.com/wp-includes/css/dist/block-library/style.min.css?ver=5.1.1` But NOT to blog posts. **EDIT with more info** When I view the source of the pages, I see that all hrefs are in fact correct. However, when clicked on, the links to the posts (but not to CSS files) are missing the "http://" prefix and are instead rendered as server-root relative URLs. So my change to the siteurl option **is** being made, but something about the site in question is breaking some (but not all) URLs. I have since tried a vanilla fresh install of WP and changed the siteurl for that at it does **NOT** exhibit this problem so I assume it's something in the WP install for this site. **Further forensics** The problem persists even when I try the following: * Removing all .htaccess files * Deactivating all plugins * Viewed using incognito mode. * Using another web browser to load the site (had been using Chrome, installed and used a fresh installation of Firefox) * Switching to a different theme (twentynineteen) * Putting one of the broken URLs into a plain .html test file
**Register your navigation menu** Add this code to your functions.php file. ``` function my_custom_new_menu() { register_nav_menu('my-custom-menu',__( 'My Custom Menu' )); } add_action( 'init', 'my_custom_new_menu' ); ``` **Create new menu** You can now go to Appearance » Menus page in your WordPress admin and try to create or edit a new menu. You will see ‘My Custom Menu’ as theme location option. **Display new menu** ``` wp_nav_menu( array( 'theme_location' => 'my-custom-menu') ); ```
336,802
<p>I'm using the example from <a href="https://developer.wordpress.org/reference/functions/add_image_size/" rel="nofollow noreferrer">add_image_size() | WordPress Developer Resources</a> to try to add custom image sizes to the admin media selector.</p> <pre><code>add_filter( 'image_size_names_choose', 'my_custom_sizes' ); function my_custom_sizes( $sizes ) { return array_merge( $sizes, array( 'your-custom-size' =&gt; __( 'Your Custom Size Name' ), ) ); } </code></pre> <p>But I'm getting a PHP Warning:</p> <blockquote> <p>call_user_func_array() expects parameter 1 to be a valid callback, function 'my_custom_sizes' not found or invalid function name</p> </blockquote> <p>and the media size selector is empty:</p> <p><a href="https://i.stack.imgur.com/EIB9T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EIB9T.png" alt="media size selector"></a></p> <p>The answers to <a href="https://wordpress.stackexchange.com/questions/200108/adding-custom-image-size-to-the-media-image-editor/226881#226881">Adding custom image size to the media image editor</a> and <a href="https://wordpress.stackexchange.com/questions/103995/add-image-size-and-add-filterimage-size-names-choose-my-custom-image-sizes">add_image_size and add_filter(&#39;image_size_names_choose&#39;, &#39;my_custom_image_sizes&#39;) not working with wordpress 3.5.2</a> don't work.</p> <p>I'm using the filter and <code>add_image_size</code> inside <code>after_setup_theme</code>; see below. I've tried it outside with no luck. Thumbnails are being generated, and regenerating thumbs works, too.</p> <p>What is breaking?</p> <pre><code>function setup() { // other code add_image_size( 'banner-ad', 655, 100, true ); add_image_size( 'banner-rectangle', 655, 250, true ); add_filter( 'image_size_names_choose', 'my_custom_sizes' ); function my_custom_sizes( $sizes ) { return array_merge( $sizes, array( 'banner-ad' =&gt; __( 'Banner Ad' ), 'banner-rectangle' =&gt; __( 'Banner Rectangle' ), ) ); } // other code } add_action('after_setup_theme', __NAMESPACE__ . '\\setup'); </code></pre>
[ { "answer_id": 336803, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 1, "selected": false, "text": "<p>Try defining the <code>my_custom_sizes()</code> function outside of the <code>setup()</code> function.</p>\n\n<p>I'm pretty sure that the <code>my_custom_sizes()</code> function is only available in the scope of the <code>setup()</code> function - which has already been called before the <code>image_size_names_choose</code> filter is fired and so it's not available to it.</p>\n" }, { "answer_id": 336804, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 1, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>function my_custom_sizes( $sizes ) {\n return array_merge( $sizes, array(\n 'banner-ad' =&gt; __( 'Banner Ad' ),\n 'banner-rectangle' =&gt; __( 'Banner Rectangle' ),\n ) );\n}\nadd_filter( 'image_size_names_choose', 'my_custom_sizes' );\n\n\nfunction setup()\n{\n\n// other code\n\n\nadd_image_size( 'banner-ad', 655, 100, true );\nadd_image_size( 'banner-rectangle', 655, 250, true );\n\n\n\n// other code\n}\nadd_action('after_setup_theme', __NAMESPACE__ . '\\\\setup');\n</code></pre>\n" }, { "answer_id": 336805, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You can't define a hook callback function inside another function. </p>\n\n<p>You've defined <code>my_custom_sizes()</code> inside <code>setup()</code>, which means that <code>my_custom_sizes()</code> cannot be called outside of the scope of <code>setup()</code>. This is a problem because the hook, <code>image_size_names_choose</code>, is not run inside your <code>setup()</code> function. You need to define your callback in the global scope:</p>\n\n<pre><code>function setup()\n{\n add_image_size( 'banner-ad', 655, 100, true );\n add_image_size( 'banner-rectangle', 655, 250, true );\n\n}\nadd_action('after_setup_theme', __NAMESPACE__ . '\\\\setup');\n\nfunction my_custom_sizes( $sizes )\n{\n return array_merge( $sizes, array(\n 'banner-ad' =&gt; __( 'Banner Ad' ),\n 'banner-rectangle' =&gt; __( 'Banner Rectangle' ),\n ) );\n}\nadd_filter( 'image_size_names_choose', __NAMESPACE__ . '\\\\my_custom_sizes' );\n</code></pre>\n" } ]
2019/05/01
[ "https://wordpress.stackexchange.com/questions/336802", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101490/" ]
I'm using the example from [add\_image\_size() | WordPress Developer Resources](https://developer.wordpress.org/reference/functions/add_image_size/) to try to add custom image sizes to the admin media selector. ``` add_filter( 'image_size_names_choose', 'my_custom_sizes' ); function my_custom_sizes( $sizes ) { return array_merge( $sizes, array( 'your-custom-size' => __( 'Your Custom Size Name' ), ) ); } ``` But I'm getting a PHP Warning: > > call\_user\_func\_array() expects parameter 1 to be a valid callback, > function 'my\_custom\_sizes' not found or invalid function name > > > and the media size selector is empty: [![media size selector](https://i.stack.imgur.com/EIB9T.png)](https://i.stack.imgur.com/EIB9T.png) The answers to [Adding custom image size to the media image editor](https://wordpress.stackexchange.com/questions/200108/adding-custom-image-size-to-the-media-image-editor/226881#226881) and [add\_image\_size and add\_filter('image\_size\_names\_choose', 'my\_custom\_image\_sizes') not working with wordpress 3.5.2](https://wordpress.stackexchange.com/questions/103995/add-image-size-and-add-filterimage-size-names-choose-my-custom-image-sizes) don't work. I'm using the filter and `add_image_size` inside `after_setup_theme`; see below. I've tried it outside with no luck. Thumbnails are being generated, and regenerating thumbs works, too. What is breaking? ``` function setup() { // other code add_image_size( 'banner-ad', 655, 100, true ); add_image_size( 'banner-rectangle', 655, 250, true ); add_filter( 'image_size_names_choose', 'my_custom_sizes' ); function my_custom_sizes( $sizes ) { return array_merge( $sizes, array( 'banner-ad' => __( 'Banner Ad' ), 'banner-rectangle' => __( 'Banner Rectangle' ), ) ); } // other code } add_action('after_setup_theme', __NAMESPACE__ . '\\setup'); ```
You can't define a hook callback function inside another function. You've defined `my_custom_sizes()` inside `setup()`, which means that `my_custom_sizes()` cannot be called outside of the scope of `setup()`. This is a problem because the hook, `image_size_names_choose`, is not run inside your `setup()` function. You need to define your callback in the global scope: ``` function setup() { add_image_size( 'banner-ad', 655, 100, true ); add_image_size( 'banner-rectangle', 655, 250, true ); } add_action('after_setup_theme', __NAMESPACE__ . '\\setup'); function my_custom_sizes( $sizes ) { return array_merge( $sizes, array( 'banner-ad' => __( 'Banner Ad' ), 'banner-rectangle' => __( 'Banner Rectangle' ), ) ); } add_filter( 'image_size_names_choose', __NAMESPACE__ . '\\my_custom_sizes' ); ```
336,807
<p>I have this function </p> <pre><code>$tags = get_tags( array('exclude' =&gt; 11, 12) ) </code></pre> <p>Which excludes specific tags 11 and 12. But without manually having to add each tag <strong>ID</strong> I don't want shown, how do I exclude the category that these tags are coming from?</p>
[ { "answer_id": 336803, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 1, "selected": false, "text": "<p>Try defining the <code>my_custom_sizes()</code> function outside of the <code>setup()</code> function.</p>\n\n<p>I'm pretty sure that the <code>my_custom_sizes()</code> function is only available in the scope of the <code>setup()</code> function - which has already been called before the <code>image_size_names_choose</code> filter is fired and so it's not available to it.</p>\n" }, { "answer_id": 336804, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 1, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>function my_custom_sizes( $sizes ) {\n return array_merge( $sizes, array(\n 'banner-ad' =&gt; __( 'Banner Ad' ),\n 'banner-rectangle' =&gt; __( 'Banner Rectangle' ),\n ) );\n}\nadd_filter( 'image_size_names_choose', 'my_custom_sizes' );\n\n\nfunction setup()\n{\n\n// other code\n\n\nadd_image_size( 'banner-ad', 655, 100, true );\nadd_image_size( 'banner-rectangle', 655, 250, true );\n\n\n\n// other code\n}\nadd_action('after_setup_theme', __NAMESPACE__ . '\\\\setup');\n</code></pre>\n" }, { "answer_id": 336805, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You can't define a hook callback function inside another function. </p>\n\n<p>You've defined <code>my_custom_sizes()</code> inside <code>setup()</code>, which means that <code>my_custom_sizes()</code> cannot be called outside of the scope of <code>setup()</code>. This is a problem because the hook, <code>image_size_names_choose</code>, is not run inside your <code>setup()</code> function. You need to define your callback in the global scope:</p>\n\n<pre><code>function setup()\n{\n add_image_size( 'banner-ad', 655, 100, true );\n add_image_size( 'banner-rectangle', 655, 250, true );\n\n}\nadd_action('after_setup_theme', __NAMESPACE__ . '\\\\setup');\n\nfunction my_custom_sizes( $sizes )\n{\n return array_merge( $sizes, array(\n 'banner-ad' =&gt; __( 'Banner Ad' ),\n 'banner-rectangle' =&gt; __( 'Banner Rectangle' ),\n ) );\n}\nadd_filter( 'image_size_names_choose', __NAMESPACE__ . '\\\\my_custom_sizes' );\n</code></pre>\n" } ]
2019/05/01
[ "https://wordpress.stackexchange.com/questions/336807", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132008/" ]
I have this function ``` $tags = get_tags( array('exclude' => 11, 12) ) ``` Which excludes specific tags 11 and 12. But without manually having to add each tag **ID** I don't want shown, how do I exclude the category that these tags are coming from?
You can't define a hook callback function inside another function. You've defined `my_custom_sizes()` inside `setup()`, which means that `my_custom_sizes()` cannot be called outside of the scope of `setup()`. This is a problem because the hook, `image_size_names_choose`, is not run inside your `setup()` function. You need to define your callback in the global scope: ``` function setup() { add_image_size( 'banner-ad', 655, 100, true ); add_image_size( 'banner-rectangle', 655, 250, true ); } add_action('after_setup_theme', __NAMESPACE__ . '\\setup'); function my_custom_sizes( $sizes ) { return array_merge( $sizes, array( 'banner-ad' => __( 'Banner Ad' ), 'banner-rectangle' => __( 'Banner Rectangle' ), ) ); } add_filter( 'image_size_names_choose', __NAMESPACE__ . '\\my_custom_sizes' ); ```
336,821
<p>Ultimately I'm wanting to add some custom widget fields to the existing default image widget, and define it as a new custom widget.</p> <p>I'm trying to create my own by extending the <code>WP_Widget_Media_Image</code> class, like this:</p> <pre><code>class Theme_Image_Widget extends WP_Widget_Media_Image { /** * Widget identifier. */ const WIDGET_SLUG = 'theme_image_widget'; /** * Widget friendly name. */ const WIDGET_NAME = 'Theme Image Widget'; /** * Widget description. */ const WIDGET_DESCRIPTION = 'foo'; public function __construct() { WP_Widget_Media::__construct( self::WIDGET_SLUG, self::WIDGET_NAME, array( 'classname' =&gt; self::WIDGET_SLUG, 'description' =&gt; self::WIDGET_DESCRIPTION ) ); } </code></pre> <p>This code gets the new widget to appear in the widgets area, but it doesn't contain the normal UI that the default image widget has. I'm essentially looking to get the same UI over into this widget, and then add some additional fields to it.</p> <p>Is there anyway to do this without having to re-write the JS UI code for the image widget?</p>
[ { "answer_id": 336803, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 1, "selected": false, "text": "<p>Try defining the <code>my_custom_sizes()</code> function outside of the <code>setup()</code> function.</p>\n\n<p>I'm pretty sure that the <code>my_custom_sizes()</code> function is only available in the scope of the <code>setup()</code> function - which has already been called before the <code>image_size_names_choose</code> filter is fired and so it's not available to it.</p>\n" }, { "answer_id": 336804, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 1, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>function my_custom_sizes( $sizes ) {\n return array_merge( $sizes, array(\n 'banner-ad' =&gt; __( 'Banner Ad' ),\n 'banner-rectangle' =&gt; __( 'Banner Rectangle' ),\n ) );\n}\nadd_filter( 'image_size_names_choose', 'my_custom_sizes' );\n\n\nfunction setup()\n{\n\n// other code\n\n\nadd_image_size( 'banner-ad', 655, 100, true );\nadd_image_size( 'banner-rectangle', 655, 250, true );\n\n\n\n// other code\n}\nadd_action('after_setup_theme', __NAMESPACE__ . '\\\\setup');\n</code></pre>\n" }, { "answer_id": 336805, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You can't define a hook callback function inside another function. </p>\n\n<p>You've defined <code>my_custom_sizes()</code> inside <code>setup()</code>, which means that <code>my_custom_sizes()</code> cannot be called outside of the scope of <code>setup()</code>. This is a problem because the hook, <code>image_size_names_choose</code>, is not run inside your <code>setup()</code> function. You need to define your callback in the global scope:</p>\n\n<pre><code>function setup()\n{\n add_image_size( 'banner-ad', 655, 100, true );\n add_image_size( 'banner-rectangle', 655, 250, true );\n\n}\nadd_action('after_setup_theme', __NAMESPACE__ . '\\\\setup');\n\nfunction my_custom_sizes( $sizes )\n{\n return array_merge( $sizes, array(\n 'banner-ad' =&gt; __( 'Banner Ad' ),\n 'banner-rectangle' =&gt; __( 'Banner Rectangle' ),\n ) );\n}\nadd_filter( 'image_size_names_choose', __NAMESPACE__ . '\\\\my_custom_sizes' );\n</code></pre>\n" } ]
2019/05/01
[ "https://wordpress.stackexchange.com/questions/336821", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109171/" ]
Ultimately I'm wanting to add some custom widget fields to the existing default image widget, and define it as a new custom widget. I'm trying to create my own by extending the `WP_Widget_Media_Image` class, like this: ``` class Theme_Image_Widget extends WP_Widget_Media_Image { /** * Widget identifier. */ const WIDGET_SLUG = 'theme_image_widget'; /** * Widget friendly name. */ const WIDGET_NAME = 'Theme Image Widget'; /** * Widget description. */ const WIDGET_DESCRIPTION = 'foo'; public function __construct() { WP_Widget_Media::__construct( self::WIDGET_SLUG, self::WIDGET_NAME, array( 'classname' => self::WIDGET_SLUG, 'description' => self::WIDGET_DESCRIPTION ) ); } ``` This code gets the new widget to appear in the widgets area, but it doesn't contain the normal UI that the default image widget has. I'm essentially looking to get the same UI over into this widget, and then add some additional fields to it. Is there anyway to do this without having to re-write the JS UI code for the image widget?
You can't define a hook callback function inside another function. You've defined `my_custom_sizes()` inside `setup()`, which means that `my_custom_sizes()` cannot be called outside of the scope of `setup()`. This is a problem because the hook, `image_size_names_choose`, is not run inside your `setup()` function. You need to define your callback in the global scope: ``` function setup() { add_image_size( 'banner-ad', 655, 100, true ); add_image_size( 'banner-rectangle', 655, 250, true ); } add_action('after_setup_theme', __NAMESPACE__ . '\\setup'); function my_custom_sizes( $sizes ) { return array_merge( $sizes, array( 'banner-ad' => __( 'Banner Ad' ), 'banner-rectangle' => __( 'Banner Rectangle' ), ) ); } add_filter( 'image_size_names_choose', __NAMESPACE__ . '\\my_custom_sizes' ); ```
336,839
<p>I am building a custom solution where I am needing to obtain all the meta values for a post into an array. I have many "keys". Is there a way to loop through them all without doing this? I have the post ID at this point in my script.</p> <pre><code>$image_meta = get_post_meta( $post-&gt;ID, 'image', true ); // car year $car_year = get_post_meta( $post-&gt;ID, 'car_year', true ); // car mileage $car_mileage = get_post_meta( $post-&gt;ID, 'car_mileage', true ); // car price $car_price = get_post_meta( $post-&gt;ID, 'car_price', true ); // car model $car_model = get_post_meta( $post-&gt;ID, 'car_model', true ); </code></pre>
[ { "answer_id": 336844, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 2, "selected": false, "text": "<p>As @Sally CJ noted in the comment to your question, you should just omit the meta key:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$meta = get_post_meta( $post-&gt;ID, '', true );\n\necho $meta['car_year']; // 2005\n</code></pre>\n\n<p>In PHP 7.1 you can use <a href=\"https://php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring\" rel=\"nofollow noreferrer\">array destructing</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>[\n 'image_meta' =&gt; $image_meta,\n 'car_year' =&gt; $car_year,\n 'car_mileage' =&gt; $car_mileage,\n 'car_price' =&gt; $car_price,\n 'car_model' =&gt; $car_model,\n] = get_post_meta( $post-&gt;ID, '', true );\n\necho $car_year; // 2005\n</code></pre>\n" }, { "answer_id": 336871, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 1, "selected": false, "text": "<p>I've had similiar needs in the past and as I didn't know about <code>array destructing</code> @phatskat mentioned I created a helper function to do the looping for me.</p>\n\n<p>Helper function,</p>\n\n<pre><code>function get_keyed_meta_data_array( int $post_id, array $keys ) {\n $keyed_meta = array();\n $post_meta = get_post_meta( $post_id, '', true );\n\n foreach ( $keys as $key ) {\n if ( isset( $post_meta[$key] ) ) {\n $keyed_meta[$key] = $post_meta[$key];\n } else {\n $keyed_meta[$key] = '';\n }\n }\n\n return $keyed_meta;\n}\n</code></pre>\n\n<p>Usage,</p>\n\n<pre><code>$keys = array(\n 'image',\n 'car_year',\n 'car_mileage',\n 'car_price',\n 'car_model'\n); // key array could also be returned from a config function for DRY purposes\n\n$data = get_keyed_meta_data_array( $post-&gt;ID, $keys );\n// $data['car_year'] = 2019;\n// $data['car_mileage'] = 123; \n// $data['car_model'] = '';\n</code></pre>\n" } ]
2019/05/01
[ "https://wordpress.stackexchange.com/questions/336839", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116635/" ]
I am building a custom solution where I am needing to obtain all the meta values for a post into an array. I have many "keys". Is there a way to loop through them all without doing this? I have the post ID at this point in my script. ``` $image_meta = get_post_meta( $post->ID, 'image', true ); // car year $car_year = get_post_meta( $post->ID, 'car_year', true ); // car mileage $car_mileage = get_post_meta( $post->ID, 'car_mileage', true ); // car price $car_price = get_post_meta( $post->ID, 'car_price', true ); // car model $car_model = get_post_meta( $post->ID, 'car_model', true ); ```
As @Sally CJ noted in the comment to your question, you should just omit the meta key: ```php $meta = get_post_meta( $post->ID, '', true ); echo $meta['car_year']; // 2005 ``` In PHP 7.1 you can use [array destructing](https://php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring): ```php [ 'image_meta' => $image_meta, 'car_year' => $car_year, 'car_mileage' => $car_mileage, 'car_price' => $car_price, 'car_model' => $car_model, ] = get_post_meta( $post->ID, '', true ); echo $car_year; // 2005 ```
336,857
<p>I have the following, which successfully inserts a dynamic link as the <em>last</em> top-level menu item of the specified menu:</p> <pre><code>add_filter( 'wp_nav_menu_items', 'example_last_nav_item', 10, 2 ); function example_last_nav_item( $items, $args ) { if ( $args - &gt; theme_location == 'account-menu' &amp;&amp; is_user_logged_in() ) { $current_user = wp_get_current_user(); $items .= '&lt;li class="menu-item profile-link"&gt;&lt;a href="https://example.com/profile/' . strtolower( str_replace( ' ', '-', $current_user - &gt; user_login ) ) . '/"&gt;Profile&lt;/a&gt;&lt;/li&gt;'; } return $items; } </code></pre> <p>But, how would I access this menu's <em>sub-menu</em> and insert the link as the <em>first</em> item of the sub-menu?</p> <p>Account Menu Top-level</p> <p>— <strong>DYNAMIC LINK HERE</strong></p> <p>— Sub-menu Item #2</p> <p>— Sub-menu Item #3</p>
[ { "answer_id": 336864, "author": "anton", "author_id": 97934, "author_profile": "https://wordpress.stackexchange.com/users/97934", "pm_score": 0, "selected": false, "text": "<p>I recommend you to use <code>wp_nav_menu_objects</code> hook, which allows you to work with menu items as objects, instead of a string. Inside of your if statement you can create as many items as you want. <br/><br/></p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'example_last_nav_item', 10, 2 );\n\nfunction example_last_nav_item( $items, $args ){\n\n if ( $args-&gt;theme_location=='account-menu' &amp;&amp; is_user_logged_in() ){\n\n //parent menu item\n $parent_item = array(\n 'title' =&gt; __('Profile'),\n 'menu_item_parent' =&gt; 0, //PARENT ELEMENT HAS 0\n 'ID' =&gt; 'profile',\n 'db_id' =&gt; 9999, //MAKE SURE IT's UNIQUE ID\n 'url' =&gt; 'http://google.com',\n 'classes' =&gt; array( 'custom-menu-item' )\n );\n\n //submenu menu item\n $submenu_item = array(\n 'title' =&gt; __('Submenu first element'),\n 'menu_item_parent' =&gt; 9999, //FOR SUBMENU ITEM SET PARENT's db_id\n 'ID' =&gt; 'submenu-item',\n 'db_id' =&gt; 99992,\n 'url' =&gt; 'http://google.com',\n 'classes' =&gt; array( 'custom-menu-item' )\n );\n\n $items[] = (object) $parent_item;\n $items[] = (object) $submenu_item;\n }\n\n return $items;\n\n}\n</code></pre>\n\n<p>About all item properties you can read <a href=\"https://www.ibenic.com/understanding-wordpress-menu-items/\" rel=\"nofollow noreferrer\">here</a> </p>\n" }, { "answer_id": 336872, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 2, "selected": true, "text": "<p>The following code will go through all items and search the first item that has a parent. If found, new item with the same parent will be inserted as \"first child\".</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'se336857_dynamic_submenuitem', 20, 2 );\nfunction se336857_dynamic_submenuitem( $items, $args )\n{\n if ( !is_user_logged_in() || $args-&gt;theme_location != 'account-menu' )\n return $items;\n\n $parent = false;\n $current_user = wp_get_current_user();\n $url = '/profile/' . strtolower(str_replace( ' ', '-', $current_user-&gt;user_login ));\n\n $item_profile = [\n 'title' =&gt; __('Profile'),\n 'url' =&gt; home_url( $url ),\n 'classes' =&gt; 'menu-item profile-link',\n ];\n $item_profile = (object)$item_profile;\n $item_profile = new WP_Post($item_profile);\n $i = -1;\n foreach ( $items as $item )\n {\n ++$i;\n if ( $item-&gt;menu_item_parent == 0 )\n continue;\n //\n // first submenu item\n $item_profile-&gt;menu_item_parent = $item-&gt;menu_item_parent;\n $new_items = [ $item_profile ];\n array_splice($items, $i, 0, $new_items );\n break;\n }\n return $items;\n}\n</code></pre>\n" } ]
2019/05/02
[ "https://wordpress.stackexchange.com/questions/336857", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167210/" ]
I have the following, which successfully inserts a dynamic link as the *last* top-level menu item of the specified menu: ``` add_filter( 'wp_nav_menu_items', 'example_last_nav_item', 10, 2 ); function example_last_nav_item( $items, $args ) { if ( $args - > theme_location == 'account-menu' && is_user_logged_in() ) { $current_user = wp_get_current_user(); $items .= '<li class="menu-item profile-link"><a href="https://example.com/profile/' . strtolower( str_replace( ' ', '-', $current_user - > user_login ) ) . '/">Profile</a></li>'; } return $items; } ``` But, how would I access this menu's *sub-menu* and insert the link as the *first* item of the sub-menu? Account Menu Top-level — **DYNAMIC LINK HERE** — Sub-menu Item #2 — Sub-menu Item #3
The following code will go through all items and search the first item that has a parent. If found, new item with the same parent will be inserted as "first child". ``` add_filter( 'wp_nav_menu_objects', 'se336857_dynamic_submenuitem', 20, 2 ); function se336857_dynamic_submenuitem( $items, $args ) { if ( !is_user_logged_in() || $args->theme_location != 'account-menu' ) return $items; $parent = false; $current_user = wp_get_current_user(); $url = '/profile/' . strtolower(str_replace( ' ', '-', $current_user->user_login )); $item_profile = [ 'title' => __('Profile'), 'url' => home_url( $url ), 'classes' => 'menu-item profile-link', ]; $item_profile = (object)$item_profile; $item_profile = new WP_Post($item_profile); $i = -1; foreach ( $items as $item ) { ++$i; if ( $item->menu_item_parent == 0 ) continue; // // first submenu item $item_profile->menu_item_parent = $item->menu_item_parent; $new_items = [ $item_profile ]; array_splice($items, $i, 0, $new_items ); break; } return $items; } ```
336,859
<p>So what I would like to do is, move the content of example.com/blog to yolo.com/blog. The yolo.com website is already live and has contents in it. So I just want to move my existing blog to a subdirectory on yolo.com. I have access to the Cpanels of both websites.</p>
[ { "answer_id": 336864, "author": "anton", "author_id": 97934, "author_profile": "https://wordpress.stackexchange.com/users/97934", "pm_score": 0, "selected": false, "text": "<p>I recommend you to use <code>wp_nav_menu_objects</code> hook, which allows you to work with menu items as objects, instead of a string. Inside of your if statement you can create as many items as you want. <br/><br/></p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'example_last_nav_item', 10, 2 );\n\nfunction example_last_nav_item( $items, $args ){\n\n if ( $args-&gt;theme_location=='account-menu' &amp;&amp; is_user_logged_in() ){\n\n //parent menu item\n $parent_item = array(\n 'title' =&gt; __('Profile'),\n 'menu_item_parent' =&gt; 0, //PARENT ELEMENT HAS 0\n 'ID' =&gt; 'profile',\n 'db_id' =&gt; 9999, //MAKE SURE IT's UNIQUE ID\n 'url' =&gt; 'http://google.com',\n 'classes' =&gt; array( 'custom-menu-item' )\n );\n\n //submenu menu item\n $submenu_item = array(\n 'title' =&gt; __('Submenu first element'),\n 'menu_item_parent' =&gt; 9999, //FOR SUBMENU ITEM SET PARENT's db_id\n 'ID' =&gt; 'submenu-item',\n 'db_id' =&gt; 99992,\n 'url' =&gt; 'http://google.com',\n 'classes' =&gt; array( 'custom-menu-item' )\n );\n\n $items[] = (object) $parent_item;\n $items[] = (object) $submenu_item;\n }\n\n return $items;\n\n}\n</code></pre>\n\n<p>About all item properties you can read <a href=\"https://www.ibenic.com/understanding-wordpress-menu-items/\" rel=\"nofollow noreferrer\">here</a> </p>\n" }, { "answer_id": 336872, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 2, "selected": true, "text": "<p>The following code will go through all items and search the first item that has a parent. If found, new item with the same parent will be inserted as \"first child\".</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'se336857_dynamic_submenuitem', 20, 2 );\nfunction se336857_dynamic_submenuitem( $items, $args )\n{\n if ( !is_user_logged_in() || $args-&gt;theme_location != 'account-menu' )\n return $items;\n\n $parent = false;\n $current_user = wp_get_current_user();\n $url = '/profile/' . strtolower(str_replace( ' ', '-', $current_user-&gt;user_login ));\n\n $item_profile = [\n 'title' =&gt; __('Profile'),\n 'url' =&gt; home_url( $url ),\n 'classes' =&gt; 'menu-item profile-link',\n ];\n $item_profile = (object)$item_profile;\n $item_profile = new WP_Post($item_profile);\n $i = -1;\n foreach ( $items as $item )\n {\n ++$i;\n if ( $item-&gt;menu_item_parent == 0 )\n continue;\n //\n // first submenu item\n $item_profile-&gt;menu_item_parent = $item-&gt;menu_item_parent;\n $new_items = [ $item_profile ];\n array_splice($items, $i, 0, $new_items );\n break;\n }\n return $items;\n}\n</code></pre>\n" } ]
2019/05/02
[ "https://wordpress.stackexchange.com/questions/336859", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167209/" ]
So what I would like to do is, move the content of example.com/blog to yolo.com/blog. The yolo.com website is already live and has contents in it. So I just want to move my existing blog to a subdirectory on yolo.com. I have access to the Cpanels of both websites.
The following code will go through all items and search the first item that has a parent. If found, new item with the same parent will be inserted as "first child". ``` add_filter( 'wp_nav_menu_objects', 'se336857_dynamic_submenuitem', 20, 2 ); function se336857_dynamic_submenuitem( $items, $args ) { if ( !is_user_logged_in() || $args->theme_location != 'account-menu' ) return $items; $parent = false; $current_user = wp_get_current_user(); $url = '/profile/' . strtolower(str_replace( ' ', '-', $current_user->user_login )); $item_profile = [ 'title' => __('Profile'), 'url' => home_url( $url ), 'classes' => 'menu-item profile-link', ]; $item_profile = (object)$item_profile; $item_profile = new WP_Post($item_profile); $i = -1; foreach ( $items as $item ) { ++$i; if ( $item->menu_item_parent == 0 ) continue; // // first submenu item $item_profile->menu_item_parent = $item->menu_item_parent; $new_items = [ $item_profile ]; array_splice($items, $i, 0, $new_items ); break; } return $items; } ```
336,877
<p>If anyone know, if there's plugin to customize taxonomy list it will be faster to do.<br> But here's my question.</p> <p>i create post type <strong>"product"</strong> and the categories.<br> inside post type <strong>product</strong>, i make categories like this</p> <ul> <li>Book <ul> <li>Novel</li> <li>Dictionary <ul> <li>English</li> <li>Korean </li> </ul></li> </ul></li> <li>Gadget <ul> <li>Phone</li> <li>Tablet</li> </ul></li> </ul> <p>So, in the page<br> i want to list <em>sub-category</em> inside <strong>Book</strong>,<br> the result = Novel and Dictionary.<br> And when i click on Dictionary for example, it will show me<br> list of <strong>Dictionary</strong> <em>sub-category</em>,<br> the result = English and Korean. </p> <p>Then for last, when i click on English<br> page will show all post items inside English category.</p>
[ { "answer_id": 336864, "author": "anton", "author_id": 97934, "author_profile": "https://wordpress.stackexchange.com/users/97934", "pm_score": 0, "selected": false, "text": "<p>I recommend you to use <code>wp_nav_menu_objects</code> hook, which allows you to work with menu items as objects, instead of a string. Inside of your if statement you can create as many items as you want. <br/><br/></p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'example_last_nav_item', 10, 2 );\n\nfunction example_last_nav_item( $items, $args ){\n\n if ( $args-&gt;theme_location=='account-menu' &amp;&amp; is_user_logged_in() ){\n\n //parent menu item\n $parent_item = array(\n 'title' =&gt; __('Profile'),\n 'menu_item_parent' =&gt; 0, //PARENT ELEMENT HAS 0\n 'ID' =&gt; 'profile',\n 'db_id' =&gt; 9999, //MAKE SURE IT's UNIQUE ID\n 'url' =&gt; 'http://google.com',\n 'classes' =&gt; array( 'custom-menu-item' )\n );\n\n //submenu menu item\n $submenu_item = array(\n 'title' =&gt; __('Submenu first element'),\n 'menu_item_parent' =&gt; 9999, //FOR SUBMENU ITEM SET PARENT's db_id\n 'ID' =&gt; 'submenu-item',\n 'db_id' =&gt; 99992,\n 'url' =&gt; 'http://google.com',\n 'classes' =&gt; array( 'custom-menu-item' )\n );\n\n $items[] = (object) $parent_item;\n $items[] = (object) $submenu_item;\n }\n\n return $items;\n\n}\n</code></pre>\n\n<p>About all item properties you can read <a href=\"https://www.ibenic.com/understanding-wordpress-menu-items/\" rel=\"nofollow noreferrer\">here</a> </p>\n" }, { "answer_id": 336872, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 2, "selected": true, "text": "<p>The following code will go through all items and search the first item that has a parent. If found, new item with the same parent will be inserted as \"first child\".</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'se336857_dynamic_submenuitem', 20, 2 );\nfunction se336857_dynamic_submenuitem( $items, $args )\n{\n if ( !is_user_logged_in() || $args-&gt;theme_location != 'account-menu' )\n return $items;\n\n $parent = false;\n $current_user = wp_get_current_user();\n $url = '/profile/' . strtolower(str_replace( ' ', '-', $current_user-&gt;user_login ));\n\n $item_profile = [\n 'title' =&gt; __('Profile'),\n 'url' =&gt; home_url( $url ),\n 'classes' =&gt; 'menu-item profile-link',\n ];\n $item_profile = (object)$item_profile;\n $item_profile = new WP_Post($item_profile);\n $i = -1;\n foreach ( $items as $item )\n {\n ++$i;\n if ( $item-&gt;menu_item_parent == 0 )\n continue;\n //\n // first submenu item\n $item_profile-&gt;menu_item_parent = $item-&gt;menu_item_parent;\n $new_items = [ $item_profile ];\n array_splice($items, $i, 0, $new_items );\n break;\n }\n return $items;\n}\n</code></pre>\n" } ]
2019/05/02
[ "https://wordpress.stackexchange.com/questions/336877", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167224/" ]
If anyone know, if there's plugin to customize taxonomy list it will be faster to do. But here's my question. i create post type **"product"** and the categories. inside post type **product**, i make categories like this * Book + Novel + Dictionary - English - Korean * Gadget + Phone + Tablet So, in the page i want to list *sub-category* inside **Book**, the result = Novel and Dictionary. And when i click on Dictionary for example, it will show me list of **Dictionary** *sub-category*, the result = English and Korean. Then for last, when i click on English page will show all post items inside English category.
The following code will go through all items and search the first item that has a parent. If found, new item with the same parent will be inserted as "first child". ``` add_filter( 'wp_nav_menu_objects', 'se336857_dynamic_submenuitem', 20, 2 ); function se336857_dynamic_submenuitem( $items, $args ) { if ( !is_user_logged_in() || $args->theme_location != 'account-menu' ) return $items; $parent = false; $current_user = wp_get_current_user(); $url = '/profile/' . strtolower(str_replace( ' ', '-', $current_user->user_login )); $item_profile = [ 'title' => __('Profile'), 'url' => home_url( $url ), 'classes' => 'menu-item profile-link', ]; $item_profile = (object)$item_profile; $item_profile = new WP_Post($item_profile); $i = -1; foreach ( $items as $item ) { ++$i; if ( $item->menu_item_parent == 0 ) continue; // // first submenu item $item_profile->menu_item_parent = $item->menu_item_parent; $new_items = [ $item_profile ]; array_splice($items, $i, 0, $new_items ); break; } return $items; } ```
336,890
<p>The title basically says it all. I'm piecing through publishing my first theme and have copied the woocommerce template files right from the plugin. So they should be identical with no current changes. However, when I add theme support in functions.php I no longer have products displayed. The declaration is basically right from their github:</p> <pre><code> function bad_billy_beards_add_woocommerce_support() { add_theme_support( 'woocommerce', array( 'thumbnail_image_width' =&gt; 150, 'single_image_width' =&gt; 300, 'product_grid' =&gt; array( 'default_rows' =&gt; 3, 'min_rows' =&gt; 2, 'max_rows' =&gt; 8, 'default_columns' =&gt; 4, 'min_columns' =&gt; 2, 'max_columns' =&gt; 5, ), ) ); } add_action( 'after_setup_theme', 'bad_billy_beards_add_woocommerce_support' ); </code></pre> <p>Thank you.</p>
[ { "answer_id": 336896, "author": "user3135691", "author_id": 59755, "author_profile": "https://wordpress.stackexchange.com/users/59755", "pm_score": 1, "selected": false, "text": "<p>See this post for <a href=\"https://wordpress.stackexchange.com/questions/304776/how-to-override-woocommerce-specific-loop-or-archive-product-php/304804#304804\">WooCommerce templating mechanism</a>. One basic principle is: only overwrite things that you want to customize, not more.</p>\n\n<p>So you should remove all files that are not changed, look out for double lines of code(meaning you maybe declare the same things twice, maybe with different vars/namespace and/or something else), which might be the cause why it breaks.</p>\n\n<p>For a custom product layout, I'd simply overwrite <strong><em>archive-products.php</em></strong></p>\n\n<p><strong>Edit:</strong> You can use add_theme_support without the array at the end. Try that.</p>\n\n<pre><code>&lt;?php\n function bad_billy_beards_add_woocommerce_support() {\n add_theme_support( 'woocommerce');\n}\nadd_action( 'after_setup_theme', 'bad_billy_beards_add_woocommerce_support' );\n</code></pre>\n" }, { "answer_id": 337311, "author": "Dallas Price", "author_id": 103843, "author_profile": "https://wordpress.stackexchange.com/users/103843", "pm_score": 0, "selected": false, "text": "<p>I guess I kinda figured it out ... It would seem as I'm missing a bit here.</p>\n\n<pre><code>function bad_billy_beard_add_woocommerce_support() {\n add_theme_support( 'woocommerce', array(\n 'thumbnail_image_width' =&gt; 150,\n 'single_image_width' =&gt; 300,\n\n 'product_grid' =&gt; array(\n 'default_rows' =&gt; 3,\n 'min_rows' =&gt; 2,\n 'max_rows' =&gt; 8,\n 'default_columns' =&gt; 4,\n 'min_columns' =&gt; 2,\n 'max_columns' =&gt; 5,\n ),\n ) );\n}\nadd_action( 'after_setup_theme', 'bad_billy_beard_add_woocommerce_support' );\n\nremove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);\nremove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);\n\nadd_action('woocommerce_before_main_content', 'bad_billy_beard_start', 10);\nadd_action('woocommerce_after_main_content', 'bad_billy_beard_end', 10);\n\nfunction bad_billy_beard_start() {\n echo '&lt;section id=\"main\"&gt;';\n}\n\nfunction bad_billy_beard_end() {\n echo '&lt;/section&gt;';\n}\n</code></pre>\n" } ]
2019/05/02
[ "https://wordpress.stackexchange.com/questions/336890", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103843/" ]
The title basically says it all. I'm piecing through publishing my first theme and have copied the woocommerce template files right from the plugin. So they should be identical with no current changes. However, when I add theme support in functions.php I no longer have products displayed. The declaration is basically right from their github: ``` function bad_billy_beards_add_woocommerce_support() { add_theme_support( 'woocommerce', array( 'thumbnail_image_width' => 150, 'single_image_width' => 300, 'product_grid' => array( 'default_rows' => 3, 'min_rows' => 2, 'max_rows' => 8, 'default_columns' => 4, 'min_columns' => 2, 'max_columns' => 5, ), ) ); } add_action( 'after_setup_theme', 'bad_billy_beards_add_woocommerce_support' ); ``` Thank you.
See this post for [WooCommerce templating mechanism](https://wordpress.stackexchange.com/questions/304776/how-to-override-woocommerce-specific-loop-or-archive-product-php/304804#304804). One basic principle is: only overwrite things that you want to customize, not more. So you should remove all files that are not changed, look out for double lines of code(meaning you maybe declare the same things twice, maybe with different vars/namespace and/or something else), which might be the cause why it breaks. For a custom product layout, I'd simply overwrite ***archive-products.php*** **Edit:** You can use add\_theme\_support without the array at the end. Try that. ``` <?php function bad_billy_beards_add_woocommerce_support() { add_theme_support( 'woocommerce'); } add_action( 'after_setup_theme', 'bad_billy_beards_add_woocommerce_support' ); ```
336,891
<p>In wooCommerce admin product pages, on variable products you can have product variations. See below the "variations" settings section:</p> <p><a href="https://i.stack.imgur.com/1fdxE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1fdxE.png" alt="enter image description here"></a></p> <p><strong>What Im trying to achieve:</strong> </p> <p>I have already been able to add a text field for regular price and sales price for simple products on admin "product data" metabox under "General" section. Now I need to add a new text field "Cost price" for variable products under "variations" section, but I had no idea how to add this.</p> <p>So I started searching the scripts/reading WooCommerce documentation and I Managed to add the new text field by editing <code>includes/admin/metabox/html-variation-admin.php</code>, adding the code below to it:</p> <pre><code>woocommerce_wp_text_input( array( 'id' =&gt; "variable_cost_price{$loop}", 'name' =&gt; "variable_cost_price[{$loop}]", 'value' =&gt; wc_format_localized_price( $variation_object-&gt;get_cost_price( 'edit' ) ), 'data_type' =&gt; 'price', 'label' =&gt; $label , 'wrapper_class' =&gt; 'form-row form-row-last', ) ); </code></pre> <p>I knew this was going to work as I cloned this from "Regular Price" form field. </p> <p><strong>My problem:</strong> Of course having the text field there is pointless if it does not save to the database and bring back the data to display on page load. Again I'm not 100% sure but I thought I had to make some more additions. </p> <p><strong>What I have tried:</strong> I have add the the method <code>get_cost_price</code> to the <code>class-wc-ajax.php</code> script as i saw one there already for get_regular_price. I also saw lines in <code>class-wc-meta-box-product-data.php</code> which referred to <code>regular_price</code> so I added an entry for my new <code>cost_price</code>, see below to what I added (I added the cost_price line):</p> <pre><code>$errors = $variation-&gt;set_props( array( 'status' =&gt; isset( $_POST['variable_enabled'][ $i ] ) ? 'publish' : 'private', 'menu_order' =&gt; wc_clean( $_POST['variation_menu_order'][ $i ] ), 'regular_price' =&gt; wc_clean( $_POST['variable_regular_price'][ $i ] ), 'sale_price' =&gt; wc_clean( $_POST['variable_sale_price'][ $i ] ), 'cost_price' =&gt; wc_clean( $_POST['variable_code_price'][ $i ] ), // .. more code here.. </code></pre> <p>What have I missed, did I need to make a change in yet another script? </p> <p>Again, the text field is displaying but entering data and clicking save changes doesn't actually seem to be adding anything to the <code>postmeta</code> table.</p> <p><strong>EDIT:</strong> I do not need this displaying on the front end website, this is purely for backend data for me to store</p>
[ { "answer_id": 336896, "author": "user3135691", "author_id": 59755, "author_profile": "https://wordpress.stackexchange.com/users/59755", "pm_score": 1, "selected": false, "text": "<p>See this post for <a href=\"https://wordpress.stackexchange.com/questions/304776/how-to-override-woocommerce-specific-loop-or-archive-product-php/304804#304804\">WooCommerce templating mechanism</a>. One basic principle is: only overwrite things that you want to customize, not more.</p>\n\n<p>So you should remove all files that are not changed, look out for double lines of code(meaning you maybe declare the same things twice, maybe with different vars/namespace and/or something else), which might be the cause why it breaks.</p>\n\n<p>For a custom product layout, I'd simply overwrite <strong><em>archive-products.php</em></strong></p>\n\n<p><strong>Edit:</strong> You can use add_theme_support without the array at the end. Try that.</p>\n\n<pre><code>&lt;?php\n function bad_billy_beards_add_woocommerce_support() {\n add_theme_support( 'woocommerce');\n}\nadd_action( 'after_setup_theme', 'bad_billy_beards_add_woocommerce_support' );\n</code></pre>\n" }, { "answer_id": 337311, "author": "Dallas Price", "author_id": 103843, "author_profile": "https://wordpress.stackexchange.com/users/103843", "pm_score": 0, "selected": false, "text": "<p>I guess I kinda figured it out ... It would seem as I'm missing a bit here.</p>\n\n<pre><code>function bad_billy_beard_add_woocommerce_support() {\n add_theme_support( 'woocommerce', array(\n 'thumbnail_image_width' =&gt; 150,\n 'single_image_width' =&gt; 300,\n\n 'product_grid' =&gt; array(\n 'default_rows' =&gt; 3,\n 'min_rows' =&gt; 2,\n 'max_rows' =&gt; 8,\n 'default_columns' =&gt; 4,\n 'min_columns' =&gt; 2,\n 'max_columns' =&gt; 5,\n ),\n ) );\n}\nadd_action( 'after_setup_theme', 'bad_billy_beard_add_woocommerce_support' );\n\nremove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);\nremove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);\n\nadd_action('woocommerce_before_main_content', 'bad_billy_beard_start', 10);\nadd_action('woocommerce_after_main_content', 'bad_billy_beard_end', 10);\n\nfunction bad_billy_beard_start() {\n echo '&lt;section id=\"main\"&gt;';\n}\n\nfunction bad_billy_beard_end() {\n echo '&lt;/section&gt;';\n}\n</code></pre>\n" } ]
2019/05/02
[ "https://wordpress.stackexchange.com/questions/336891", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167237/" ]
In wooCommerce admin product pages, on variable products you can have product variations. See below the "variations" settings section: [![enter image description here](https://i.stack.imgur.com/1fdxE.png)](https://i.stack.imgur.com/1fdxE.png) **What Im trying to achieve:** I have already been able to add a text field for regular price and sales price for simple products on admin "product data" metabox under "General" section. Now I need to add a new text field "Cost price" for variable products under "variations" section, but I had no idea how to add this. So I started searching the scripts/reading WooCommerce documentation and I Managed to add the new text field by editing `includes/admin/metabox/html-variation-admin.php`, adding the code below to it: ``` woocommerce_wp_text_input( array( 'id' => "variable_cost_price{$loop}", 'name' => "variable_cost_price[{$loop}]", 'value' => wc_format_localized_price( $variation_object->get_cost_price( 'edit' ) ), 'data_type' => 'price', 'label' => $label , 'wrapper_class' => 'form-row form-row-last', ) ); ``` I knew this was going to work as I cloned this from "Regular Price" form field. **My problem:** Of course having the text field there is pointless if it does not save to the database and bring back the data to display on page load. Again I'm not 100% sure but I thought I had to make some more additions. **What I have tried:** I have add the the method `get_cost_price` to the `class-wc-ajax.php` script as i saw one there already for get\_regular\_price. I also saw lines in `class-wc-meta-box-product-data.php` which referred to `regular_price` so I added an entry for my new `cost_price`, see below to what I added (I added the cost\_price line): ``` $errors = $variation->set_props( array( 'status' => isset( $_POST['variable_enabled'][ $i ] ) ? 'publish' : 'private', 'menu_order' => wc_clean( $_POST['variation_menu_order'][ $i ] ), 'regular_price' => wc_clean( $_POST['variable_regular_price'][ $i ] ), 'sale_price' => wc_clean( $_POST['variable_sale_price'][ $i ] ), 'cost_price' => wc_clean( $_POST['variable_code_price'][ $i ] ), // .. more code here.. ``` What have I missed, did I need to make a change in yet another script? Again, the text field is displaying but entering data and clicking save changes doesn't actually seem to be adding anything to the `postmeta` table. **EDIT:** I do not need this displaying on the front end website, this is purely for backend data for me to store
See this post for [WooCommerce templating mechanism](https://wordpress.stackexchange.com/questions/304776/how-to-override-woocommerce-specific-loop-or-archive-product-php/304804#304804). One basic principle is: only overwrite things that you want to customize, not more. So you should remove all files that are not changed, look out for double lines of code(meaning you maybe declare the same things twice, maybe with different vars/namespace and/or something else), which might be the cause why it breaks. For a custom product layout, I'd simply overwrite ***archive-products.php*** **Edit:** You can use add\_theme\_support without the array at the end. Try that. ``` <?php function bad_billy_beards_add_woocommerce_support() { add_theme_support( 'woocommerce'); } add_action( 'after_setup_theme', 'bad_billy_beards_add_woocommerce_support' ); ```
336,935
<p>Hello am trying to print the user id inside an JavaScript</p> <pre><code>&lt;script type="text/javascript"&gt; Li.re('ab12','$user_id'); &lt;/script&gt; </code></pre> <p>i wanna output like</p> <pre><code>&lt;script type="text/javascript"&gt; Li.re('ab12','12'); &lt;/script&gt; </code></pre> <p>12 is the number of the login in user.</p> <p>Is possible inside shortcode?</p> <pre><code>&lt;?php echo do_shortcode('[mycred_link href="'.get_field('incentivised_url', $taxonomy . '_' . $termId).'subid1='.$get_current_user_id.'[/mycred_link]'); ?&gt; </code></pre> <p>The <code>.$get_current_user_id.</code> inside the shortcode not works.</p> <p>Any help?</p>
[ { "answer_id": 336938, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>You can use <code>get_current_user_id()</code> to get the ID of the current user, and in your case, you can do so to print the user ID in the JavaScript <code>Li.re()</code> call:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;script type=\"text/javascript\"&gt;\n Li.re( 'ab12','&lt;?php echo get_current_user_id(); ?&gt;' );\n&lt;/script&gt;\n</code></pre>\n\n<p>And yes, you can include the user ID as part of a shortcode: (note that I omitted the <code>href</code> parameter for simplicity)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php echo do_shortcode( '[mycred_link subid1=\"' . get_current_user_id() . '\"][/mycred_link]' ); ?&gt;\n</code></pre>\n\n<p>PS: Your shortcode was missing the closing <code>]</code> tag, so I added it above. All shortcode parameter values should also be wrapped in single/double quotes.</p>\n" }, { "answer_id": 336969, "author": "Marshall Fungai", "author_id": 126038, "author_profile": "https://wordpress.stackexchange.com/users/126038", "pm_score": 2, "selected": false, "text": "<p>Another way to approach it, is by using \"wp_localize_script()\" to create objects from php that you can access from anywhere.</p>\n\n<pre><code>//Get User ID\n$user = wp_get_current_user();\n$userID = $user-&gt;roles[0];\n\n//Enqueue script \nwp_register_script( 'script_handle', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '', true );\n\n// Localize the script with new data\n$dataArray = array(\n 'userID' =&gt; $userID,\n 'anyother_value' =&gt; 'more data'\n);\nwp_localize_script( 'script_handle', 'object_name', $dataArray );\n\n// Enqueued script with localized data.\nwp_enqueue_script( 'script_handle' );\n</code></pre>\n\n<p>In your separate javascript file you can simply call the object like below.</p>\n\n<pre><code>Li.re( 'ab12', object_name.userID );\n</code></pre>\n\n<p>And your shortcode call is not working because \".$get_current_user_id.\" is not a variable but a function. The correct way is \".get_current_user_id().\". And I think your calling it wrong. You need to create a new WP_user object.</p>\n\n<pre><code> &lt;?php\n $user = new WP_User(get_current_user_id());\n $userID = $user-&gt;roles[0];\n ?&gt;\n &lt;?php echo do_shortcode( '[mycred_link subid1=\"' . $userID . '\"][/mycred_link]' ); ?&gt;\n</code></pre>\n" } ]
2019/05/02
[ "https://wordpress.stackexchange.com/questions/336935", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108699/" ]
Hello am trying to print the user id inside an JavaScript ``` <script type="text/javascript"> Li.re('ab12','$user_id'); </script> ``` i wanna output like ``` <script type="text/javascript"> Li.re('ab12','12'); </script> ``` 12 is the number of the login in user. Is possible inside shortcode? ``` <?php echo do_shortcode('[mycred_link href="'.get_field('incentivised_url', $taxonomy . '_' . $termId).'subid1='.$get_current_user_id.'[/mycred_link]'); ?> ``` The `.$get_current_user_id.` inside the shortcode not works. Any help?
You can use `get_current_user_id()` to get the ID of the current user, and in your case, you can do so to print the user ID in the JavaScript `Li.re()` call: ```php <script type="text/javascript"> Li.re( 'ab12','<?php echo get_current_user_id(); ?>' ); </script> ``` And yes, you can include the user ID as part of a shortcode: (note that I omitted the `href` parameter for simplicity) ```php <?php echo do_shortcode( '[mycred_link subid1="' . get_current_user_id() . '"][/mycred_link]' ); ?> ``` PS: Your shortcode was missing the closing `]` tag, so I added it above. All shortcode parameter values should also be wrapped in single/double quotes.
336,940
<p>This is a WordPress site and I'm using bootstrap. </p> <p>Site is <a href="https://doodle.gatewaywebdesign.com/" rel="nofollow noreferrer">https://doodle.gatewaywebdesign.com/</a></p> <p>Basically I'm just trying to get rid of the initial top margin. So instead of this:</p> <p><a href="https://i.stack.imgur.com/Iv0Bl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Iv0Bl.png" alt="enter image description here"></a></p> <p>It should look like this:</p> <p><a href="https://i.stack.imgur.com/LNBEk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LNBEk.png" alt="enter image description here"></a></p> <p>I've tried adding styles to the html element in my stylesheet, but nothing has worked. I.e.</p> <pre><code>html { margin-top: 0px!important; } </code></pre> <p>So then I'm wondering if the issue is WordPress related?</p> <p>There is not any top margin when I place relevant code in a <a href="https://codepen.io/HappyHands31/pen/wZVjyE" rel="nofollow noreferrer">Codepen</a>.</p> <p>Any ideas?</p>
[ { "answer_id": 336945, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Your best bet is to use the Inspector tool in your browser (F12, usually). Position the cursor at the top of the page, right-click, Inspect Element. Then click on the code lines until you find the right spot for that CSS element. </p>\n\n<p>Then over on the right side, find the CSS element for margin or padding, and figure out the CSS class that affects that area. Use that class name to add to the theme's Additional CSS (in Theme, Customize) to add the CSS for top margin.</p>\n\n<p>If you have never used the Inspector before, there are many googles (or bings or ducks) that will show you videos. The Inspector is a great way to find the proper CSS class to modify.</p>\n\n<p>(And CSS questions aren't really part of what happens around here.....)</p>\n" }, { "answer_id": 336946, "author": "KFish", "author_id": 158938, "author_profile": "https://wordpress.stackexchange.com/users/158938", "pm_score": 3, "selected": true, "text": "<p>That looks like the margin added by the WP admin bar when you are logged into the site. WP adds an inline style tag which sets the margin on the html element with an !important flag. Since it typically comes after any of your own styles it overrides them even if you also use !important. Since it only displays when you are logged in it shouldn't matter much, but if you really want to remove the admin bar you can change that in the settings Users->Your Profile then uncheck \"Show Toolbar when viewing site\". Or add the following to your functions file.</p>\n\n<pre><code>add_filter(‘show_admin_bar’, ‘__return_false’);\n</code></pre>\n" } ]
2019/05/03
[ "https://wordpress.stackexchange.com/questions/336940", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116029/" ]
This is a WordPress site and I'm using bootstrap. Site is <https://doodle.gatewaywebdesign.com/> Basically I'm just trying to get rid of the initial top margin. So instead of this: [![enter image description here](https://i.stack.imgur.com/Iv0Bl.png)](https://i.stack.imgur.com/Iv0Bl.png) It should look like this: [![enter image description here](https://i.stack.imgur.com/LNBEk.png)](https://i.stack.imgur.com/LNBEk.png) I've tried adding styles to the html element in my stylesheet, but nothing has worked. I.e. ``` html { margin-top: 0px!important; } ``` So then I'm wondering if the issue is WordPress related? There is not any top margin when I place relevant code in a [Codepen](https://codepen.io/HappyHands31/pen/wZVjyE). Any ideas?
That looks like the margin added by the WP admin bar when you are logged into the site. WP adds an inline style tag which sets the margin on the html element with an !important flag. Since it typically comes after any of your own styles it overrides them even if you also use !important. Since it only displays when you are logged in it shouldn't matter much, but if you really want to remove the admin bar you can change that in the settings Users->Your Profile then uncheck "Show Toolbar when viewing site". Or add the following to your functions file. ``` add_filter(‘show_admin_bar’, ‘__return_false’); ```
336,953
<p>At the bottom of my page I am trying to display some recent projects based on a pre-selected list of post IDs.</p> <p>I have built a custom query to try and retrieve the 3 specific posts (WHERE custom_post_type = project) at the bottom of my page</p> <pre><code>$projectIDs = array( [0] =&gt; 79, [1] =&gt; 98, [2] =&gt; 108 ); $args = array( 'post_type' =&gt; 'projects', 'post__in ' =&gt; $projectIDs, 'posts_per_page' =&gt; 3 ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); endwhile; </code></pre> <p>PROBLEM: It is returning 3 completely different posts: 110, 108, 111 - Didn't even return one of them. I can see in the query it filters the post_type but there is no filter for the post__in ...</p> <p>I don't play with WP Query much so not sure if I'm even calling it correctly BUT, when I analyse the results <code>var_dump($loop)</code> I see the posts aren't even being queried:</p> <pre><code>object(WP_Query)#9671 (49) { ["query"]=&gt; array(3) { ["post_type"]=&gt; string(8) "projects" ["post__in "]=&gt; array(3) { [0]=&gt; int(79) [1]=&gt; int(98) [2]=&gt; int(108) } ["posts_per_page"]=&gt; int(3) } ["query_vars"]=&gt; array(65) { ["post_type"]=&gt; string(8) "projects" ["post__in "]=&gt; array(3) { [0]=&gt; int(79) [1]=&gt; int(98) [2]=&gt; int(108) } ["posts_per_page"]=&gt; int(3) ... ["request"]=&gt; string(276) "SELECT SQL_CALC_FOUND_ROWS wpKX_posts.ID FROM wpKX_posts WHERE 1=1 AND wpKX_posts.post_type = 'projects' AND (wpKX_posts.post_status = 'publish' OR wpKX_posts.post_status = 'acf-disabled' OR wpKX_posts.post_status = 'private') ORDER BY wpKX_posts.post_date DESC LIMIT 0, 3" ["posts"]=&gt; array(3) { [0]=&gt; object(WP_Post)#9663 (24) { ["ID"]=&gt; int(110) ... } [1]=&gt; object(WP_Post)#9603 (24) { ["ID"]=&gt; int(108) ... } [2]=&gt; object(WP_Post)#9602 (24) { ["ID"]=&gt; int(111) ... } } ["post_count"]=&gt; int(3) </code></pre> <p>What am I doing wrong?</p>
[ { "answer_id": 336954, "author": "Tanmay Patel", "author_id": 62026, "author_profile": "https://wordpress.stackexchange.com/users/62026", "pm_score": 0, "selected": false, "text": "<p>In Wordpress 3.5 and up you can use 'orderby'=>'post__in' then you must write this:</p>\n\n<pre><code>&lt;?php\n$projectIDs = array(79, 98, 108);\n$args = array( 'post_type' =&gt; 'projects', 'post__in ' =&gt; $projectIDs, 'posts_per_page' =&gt; 3, 'orderby'=&gt;'post__in' );\n$loop = new WP_Query( $args );\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\nendwhile;\n?&gt;\n</code></pre>\n" }, { "answer_id": 336959, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": false, "text": "<p><em>(Revised to improve the wording)</em></p>\n\n<p>Actually, you <strong>do not</strong> have to set the <code>orderby</code> to <code>post__in</code> for <code>post__in</code> query to work. There's no such limitation in WordPress and you'd only need to set <code>'orderby' =&gt; 'post__in'</code> when you want to sort the posts exactly in the same order as the post IDs in the <code>post__in</code> parameter. :)</p>\n\n<p>And the actual problem in your code, is that WordPress (or the <code>WP_Query</code> class) doesn't recognize your <code>post__in</code> parameter because there is a <em>trailing space inside the parameter name</em> &mdash; PHP doesn't automatically remove trailing spaces in array <em>keys</em> or even values, and so does WordPress (i.e. the <strong>spaces are preserved</strong>); so <code>$args['post__in ']</code> (note the space) and <code>$args['post__in']</code> are two different array items:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$args = array( 'post_type' =&gt; 'projects', 'post__in ' =&gt; $projectIDs, 'posts_per_page' =&gt; 3 );\n</code></pre>\n\n<p>And even in the <code>var_dump()</code> output, you could quite clearly see the trailing space here:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>[\"post__in \"]=&gt;\n</code></pre>\n\n<p><em>So the fix is simple: remove the space.</em> And try again with your query, where you should see it now has the proper <code>IN</code> clause:</p>\n\n<pre><code>AND wpKX_posts.ID IN (79,98,108)\n</code></pre>\n\n<p>And actually, you don't need to manually add the indexes here:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>//$projectIDs = array( [0] =&gt; 79, [1] =&gt; 98, [2] =&gt; 108 );\n$projectIDs = array( 79, 98, 108 ); // no manual indexes; still would work fine\n</code></pre>\n" }, { "answer_id": 396391, "author": "user2695006", "author_id": 213137, "author_profile": "https://wordpress.stackexchange.com/users/213137", "pm_score": 1, "selected": false, "text": "<p>If your still having issues with this you can try the following:</p>\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_query/</a></p>\n<p>post__in (array) – use post ids. Specify posts to retrieve. ATTENTION If you use sticky posts, they will be included (prepended!) in the posts you retrieve whether you want it or not. To suppress this behaviour use <strong>ignore_sticky_posts</strong>.</p>\n<p>$args = array( 'post_type' =&gt; 'projects', 'post__in ' =&gt; $projectIDs, 'posts_per_page' =&gt; 3, 'ignore_sticky_posts' =&gt; true );</p>\n" } ]
2019/05/03
[ "https://wordpress.stackexchange.com/questions/336953", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10368/" ]
At the bottom of my page I am trying to display some recent projects based on a pre-selected list of post IDs. I have built a custom query to try and retrieve the 3 specific posts (WHERE custom\_post\_type = project) at the bottom of my page ``` $projectIDs = array( [0] => 79, [1] => 98, [2] => 108 ); $args = array( 'post_type' => 'projects', 'post__in ' => $projectIDs, 'posts_per_page' => 3 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); endwhile; ``` PROBLEM: It is returning 3 completely different posts: 110, 108, 111 - Didn't even return one of them. I can see in the query it filters the post\_type but there is no filter for the post\_\_in ... I don't play with WP Query much so not sure if I'm even calling it correctly BUT, when I analyse the results `var_dump($loop)` I see the posts aren't even being queried: ``` object(WP_Query)#9671 (49) { ["query"]=> array(3) { ["post_type"]=> string(8) "projects" ["post__in "]=> array(3) { [0]=> int(79) [1]=> int(98) [2]=> int(108) } ["posts_per_page"]=> int(3) } ["query_vars"]=> array(65) { ["post_type"]=> string(8) "projects" ["post__in "]=> array(3) { [0]=> int(79) [1]=> int(98) [2]=> int(108) } ["posts_per_page"]=> int(3) ... ["request"]=> string(276) "SELECT SQL_CALC_FOUND_ROWS wpKX_posts.ID FROM wpKX_posts WHERE 1=1 AND wpKX_posts.post_type = 'projects' AND (wpKX_posts.post_status = 'publish' OR wpKX_posts.post_status = 'acf-disabled' OR wpKX_posts.post_status = 'private') ORDER BY wpKX_posts.post_date DESC LIMIT 0, 3" ["posts"]=> array(3) { [0]=> object(WP_Post)#9663 (24) { ["ID"]=> int(110) ... } [1]=> object(WP_Post)#9603 (24) { ["ID"]=> int(108) ... } [2]=> object(WP_Post)#9602 (24) { ["ID"]=> int(111) ... } } ["post_count"]=> int(3) ``` What am I doing wrong?
*(Revised to improve the wording)* Actually, you **do not** have to set the `orderby` to `post__in` for `post__in` query to work. There's no such limitation in WordPress and you'd only need to set `'orderby' => 'post__in'` when you want to sort the posts exactly in the same order as the post IDs in the `post__in` parameter. :) And the actual problem in your code, is that WordPress (or the `WP_Query` class) doesn't recognize your `post__in` parameter because there is a *trailing space inside the parameter name* — PHP doesn't automatically remove trailing spaces in array *keys* or even values, and so does WordPress (i.e. the **spaces are preserved**); so `$args['post__in ']` (note the space) and `$args['post__in']` are two different array items: ```php $args = array( 'post_type' => 'projects', 'post__in ' => $projectIDs, 'posts_per_page' => 3 ); ``` And even in the `var_dump()` output, you could quite clearly see the trailing space here: ```php ["post__in "]=> ``` *So the fix is simple: remove the space.* And try again with your query, where you should see it now has the proper `IN` clause: ``` AND wpKX_posts.ID IN (79,98,108) ``` And actually, you don't need to manually add the indexes here: ```php //$projectIDs = array( [0] => 79, [1] => 98, [2] => 108 ); $projectIDs = array( 79, 98, 108 ); // no manual indexes; still would work fine ```
336,973
<p>I was searching for a solution to remove the "Most Used" group of blocks from Gutenberg editor and couldn't find any, is there any way?</p> <p><a href="https://i.stack.imgur.com/4zNqR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4zNqR.png" alt="enter image description here"></a></p>
[ { "answer_id": 336954, "author": "Tanmay Patel", "author_id": 62026, "author_profile": "https://wordpress.stackexchange.com/users/62026", "pm_score": 0, "selected": false, "text": "<p>In Wordpress 3.5 and up you can use 'orderby'=>'post__in' then you must write this:</p>\n\n<pre><code>&lt;?php\n$projectIDs = array(79, 98, 108);\n$args = array( 'post_type' =&gt; 'projects', 'post__in ' =&gt; $projectIDs, 'posts_per_page' =&gt; 3, 'orderby'=&gt;'post__in' );\n$loop = new WP_Query( $args );\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\nendwhile;\n?&gt;\n</code></pre>\n" }, { "answer_id": 336959, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": false, "text": "<p><em>(Revised to improve the wording)</em></p>\n\n<p>Actually, you <strong>do not</strong> have to set the <code>orderby</code> to <code>post__in</code> for <code>post__in</code> query to work. There's no such limitation in WordPress and you'd only need to set <code>'orderby' =&gt; 'post__in'</code> when you want to sort the posts exactly in the same order as the post IDs in the <code>post__in</code> parameter. :)</p>\n\n<p>And the actual problem in your code, is that WordPress (or the <code>WP_Query</code> class) doesn't recognize your <code>post__in</code> parameter because there is a <em>trailing space inside the parameter name</em> &mdash; PHP doesn't automatically remove trailing spaces in array <em>keys</em> or even values, and so does WordPress (i.e. the <strong>spaces are preserved</strong>); so <code>$args['post__in ']</code> (note the space) and <code>$args['post__in']</code> are two different array items:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$args = array( 'post_type' =&gt; 'projects', 'post__in ' =&gt; $projectIDs, 'posts_per_page' =&gt; 3 );\n</code></pre>\n\n<p>And even in the <code>var_dump()</code> output, you could quite clearly see the trailing space here:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>[\"post__in \"]=&gt;\n</code></pre>\n\n<p><em>So the fix is simple: remove the space.</em> And try again with your query, where you should see it now has the proper <code>IN</code> clause:</p>\n\n<pre><code>AND wpKX_posts.ID IN (79,98,108)\n</code></pre>\n\n<p>And actually, you don't need to manually add the indexes here:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>//$projectIDs = array( [0] =&gt; 79, [1] =&gt; 98, [2] =&gt; 108 );\n$projectIDs = array( 79, 98, 108 ); // no manual indexes; still would work fine\n</code></pre>\n" }, { "answer_id": 396391, "author": "user2695006", "author_id": 213137, "author_profile": "https://wordpress.stackexchange.com/users/213137", "pm_score": 1, "selected": false, "text": "<p>If your still having issues with this you can try the following:</p>\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_query/</a></p>\n<p>post__in (array) – use post ids. Specify posts to retrieve. ATTENTION If you use sticky posts, they will be included (prepended!) in the posts you retrieve whether you want it or not. To suppress this behaviour use <strong>ignore_sticky_posts</strong>.</p>\n<p>$args = array( 'post_type' =&gt; 'projects', 'post__in ' =&gt; $projectIDs, 'posts_per_page' =&gt; 3, 'ignore_sticky_posts' =&gt; true );</p>\n" } ]
2019/05/03
[ "https://wordpress.stackexchange.com/questions/336973", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115614/" ]
I was searching for a solution to remove the "Most Used" group of blocks from Gutenberg editor and couldn't find any, is there any way? [![enter image description here](https://i.stack.imgur.com/4zNqR.png)](https://i.stack.imgur.com/4zNqR.png)
*(Revised to improve the wording)* Actually, you **do not** have to set the `orderby` to `post__in` for `post__in` query to work. There's no such limitation in WordPress and you'd only need to set `'orderby' => 'post__in'` when you want to sort the posts exactly in the same order as the post IDs in the `post__in` parameter. :) And the actual problem in your code, is that WordPress (or the `WP_Query` class) doesn't recognize your `post__in` parameter because there is a *trailing space inside the parameter name* — PHP doesn't automatically remove trailing spaces in array *keys* or even values, and so does WordPress (i.e. the **spaces are preserved**); so `$args['post__in ']` (note the space) and `$args['post__in']` are two different array items: ```php $args = array( 'post_type' => 'projects', 'post__in ' => $projectIDs, 'posts_per_page' => 3 ); ``` And even in the `var_dump()` output, you could quite clearly see the trailing space here: ```php ["post__in "]=> ``` *So the fix is simple: remove the space.* And try again with your query, where you should see it now has the proper `IN` clause: ``` AND wpKX_posts.ID IN (79,98,108) ``` And actually, you don't need to manually add the indexes here: ```php //$projectIDs = array( [0] => 79, [1] => 98, [2] => 108 ); $projectIDs = array( 79, 98, 108 ); // no manual indexes; still would work fine ```
336,998
<p>Is this method of operation on the database is safe and correct?</p> <pre><code> if(isset($_POST['name'])){ $table = $wpdb-&gt;prefix.'_my_table'; $post = trim(sanitize_user($_POST['name'], true)); $part = $this-&gt;wpdb-&gt;prepare("WHERE name = %s", $post) $results = $this-&gt;wpdb-&gt;get_results("SELECT * FROM {$table} $part", ARRAY_A) } </code></pre>
[ { "answer_id": 337001, "author": "Stephan Samuel", "author_id": 85968, "author_profile": "https://wordpress.stackexchange.com/users/85968", "pm_score": 3, "selected": true, "text": "<p>You're asking several questions:</p>\n\n<ol>\n<li><strong>Does WP create a new PHP file for each post?</strong> No, it does not. Your statement, \"[insert] a database [record],\" is correct. The record it creates for a post (and also many other post types) is in the <code>wp_posts</code> (your prefix may not be <code>wp_</code>) table.</li>\n<li><strong>Is it SEO-friendly?</strong> This is a much more complicated question. The short answer is, \"yes,\" but only if you get a lot of other things right.</li>\n</ol>\n\n<p>There are times when WP <em>uses</em> a separate PHP file for a particular post (look <a href=\"https://codex.wordpress.org/Theme_Development\" rel=\"nofollow noreferrer\">in the Codex under Theme Development</a>) but WP does not normally <em>create</em> any PHP files.</p>\n\n<p>It seems that you think that having an individual PHP file for a post and the post being SEO-friendly are related. This is not really the case. Search engines don't really care much about the physical implementation of your website, just the HTML that's created.</p>\n\n<p>There are many resources on making your site SEO-friendly. Most of the work is between the theme and the content on the site but there are many plugins that can help you.</p>\n\n<p>This is a fairly complicated subject and specific methods change over time. If you can't find a good plugin that addresses your needs you may consider consulting a person or firm with SEO expertise to help.</p>\n\n<p>Do know that a <em>significant</em> portion of the Internet runs WP and it is definitely possible to make WP SEO-friendly without a lot of modification. Also keep in mind that many SEO plugins are some of the most-used plugins in WP and therefore some of the most frequently attacked.</p>\n" }, { "answer_id": 337595, "author": "Jagan Mohan Bishoyi", "author_id": 155457, "author_profile": "https://wordpress.stackexchange.com/users/155457", "pm_score": 0, "selected": false, "text": "<p>No, it is just pushing one record into the database.\nAnd about SEO friendly is or not depends upon the quality wording you have written in your post. And the images also matters a lot in this case. If you want a make a post SEO friendly make sure you are writing the image description, alt text, etc.</p>\n" } ]
2019/05/03
[ "https://wordpress.stackexchange.com/questions/336998", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/163538/" ]
Is this method of operation on the database is safe and correct? ``` if(isset($_POST['name'])){ $table = $wpdb->prefix.'_my_table'; $post = trim(sanitize_user($_POST['name'], true)); $part = $this->wpdb->prepare("WHERE name = %s", $post) $results = $this->wpdb->get_results("SELECT * FROM {$table} $part", ARRAY_A) } ```
You're asking several questions: 1. **Does WP create a new PHP file for each post?** No, it does not. Your statement, "[insert] a database [record]," is correct. The record it creates for a post (and also many other post types) is in the `wp_posts` (your prefix may not be `wp_`) table. 2. **Is it SEO-friendly?** This is a much more complicated question. The short answer is, "yes," but only if you get a lot of other things right. There are times when WP *uses* a separate PHP file for a particular post (look [in the Codex under Theme Development](https://codex.wordpress.org/Theme_Development)) but WP does not normally *create* any PHP files. It seems that you think that having an individual PHP file for a post and the post being SEO-friendly are related. This is not really the case. Search engines don't really care much about the physical implementation of your website, just the HTML that's created. There are many resources on making your site SEO-friendly. Most of the work is between the theme and the content on the site but there are many plugins that can help you. This is a fairly complicated subject and specific methods change over time. If you can't find a good plugin that addresses your needs you may consider consulting a person or firm with SEO expertise to help. Do know that a *significant* portion of the Internet runs WP and it is definitely possible to make WP SEO-friendly without a lot of modification. Also keep in mind that many SEO plugins are some of the most-used plugins in WP and therefore some of the most frequently attacked.
337,022
<p>I'm trying to re-order the search results using the <code>pre_get_posts</code> hook and set the <code>orderby</code> parameter to relevance. I also want to put priority posts, which is based on post meta <code>_prioritize_s</code> to be placed first in the results. Then all the posts after will be based on relevance as usual.</p> <p>Here's the code I've been messing with:</p> <pre><code>//runs on pre_get_posts function modify_search_results_order( $query ) { if ( $query-&gt;is_main_query() &amp;&amp; is_search() &amp;&amp; ! is_admin() ) { $query-&gt;query_vars['order'] = 'DESC'; $query-&gt;query_vars['orderby'] = 'relevance'; $query-&gt;query_vars['post_status'] = 'publish'; // $query-&gt;query_vars['meta_query'] = [ // 'relation' =&gt; 'OR', // array( // 'key' =&gt; '_prioritize_s', // 'compare' =&gt; 'EXISTS' // ), // array( // 'key' =&gt; '_prioritize_s', // 'compare' =&gt; 'NOT EXISTS' // ) // ]; } return $query; } </code></pre> <p>I originally had the <code>orderby</code> set to <code>meta_value relevance</code> and it did put the priority posts on top with the meta_query uncommented. However, it doesn't keep the relevance sorting intact for posts afterwards. It seems like the meta query is affecting the overall order.</p> <p>I have a feeling I might need something custom like a database query instead? Doesn't seem like I'm going to get what I need by just setting the <code>$query-&gt;query_vars</code>. Can anyone help out? Thanks in advance!</p> <hr> <p><strong>UPDATE:</strong> Since I haven't figured out how to alter the code I posted above, I'm trying an alternate solution. Let me know if it's the wrong way to go about it. Leaving the above code alone, I can use the <code>found_posts</code> hook to alter the search results query after my <code>pre_get_posts</code> function has already done it's magic. However my only issue is the second parameter that should give me the query is only giving me 10 posts when I know the results should be more than that. Why is it limiting it to 10 posts even if I set <code>posts_per_page</code> to <code>-1</code> in my <code>pre_get_posts</code> function?</p> <pre><code>function modify_search_results_prioritized( $found_posts, $wp_query ) { if ( is_search() ) { //this says 10 - why? error_out($wp_query-&gt;query_vars['posts_per_page']); } return $found_posts; } </code></pre>
[ { "answer_id": 337233, "author": "RachieVee", "author_id": 42783, "author_profile": "https://wordpress.stackexchange.com/users/42783", "pm_score": 3, "selected": true, "text": "<p>So after @Nicolai found that blurb in the WP source confirming that I can't use multiple parameters in the <code>orderby</code> if I am ordering by <code>relevance</code> I had to go a different route. However, this route only works if I don't care for pagination. There probably is a way to put it back, but I'm working on a different solution now and I no longer need to stay on the code I have in my question.</p>\n\n<p>So I kept the function to alter the query on <code>pre_get_posts</code> and removed anything regarding post meta/meta queries:</p>\n\n<pre><code>function modify_search_results_order( $query ) {\n if ( $query-&gt;is_main_query() &amp;&amp; is_search() &amp;&amp; ! is_admin() ) {\n $get_expired_events = Event_Helpers::get_expired_event_ids();\n\n $query-&gt;query_vars['posts_per_page'] = - 1;\n $query-&gt;query_vars['order'] = 'DESC';\n $query-&gt;query_vars['is_search'] = true;\n $query-&gt;query_vars['post__not_in'] = $get_expired_events;\n $query-&gt;query_vars['orderby'] = 'relevance';\n $query-&gt;query_vars['post_status'] = 'publish';\n }\n\n return $query;\n }\n</code></pre>\n\n<p>Then in my search template, I call a function that alters the query after <code>pre_get_posts</code> to look for the priority posts, unset them from the main query, and place them back on top:</p>\n\n<pre><code>//in search.php\n$wp_query-&gt;posts = Search_Modify_Query::rearrange_search_query_for_priority_relevance( $wp_query-&gt;posts );\n\n//in PHP Class\npublic static function rearrange_search_query_for_priority_relevance( $query ) {\n //get prioritized ids\n $get_prioritized = self::get_priority_search_post_ids();\n $get_results_ids = [];\n\n if ( ! is_array( $get_prioritized ) || ! $get_prioritized ) {\n return $query;\n }\n\n //save all ids from current search results query\n foreach ( $query as $key =&gt; $post ) {\n $get_results_ids[ $key ] = $post-&gt;ID;\n }\n\n if ( ! $get_results_ids ) {\n return $query;\n }\n\n //check if there are priority posts in results\n if ( array_intersect( $get_prioritized, $get_results_ids ) ) {\n $priority_matches = array_intersect( $get_results_ids, $get_prioritized );\n $priority_query = false;\n\n //if there are priority matches, pluck them out to put them on top\n if ( $priority_matches ) {\n foreach ( $priority_matches as $key =&gt; $priority_match ) {\n //save these into new array first\n $priority_query[ $key ] = $query[ $key ];\n //then unset them from main query\n unset( $query[ $key ] );\n }\n\n if ( $priority_query &amp;&amp; is_array( $priority_query ) ) {\n //then re-add them on top of main query\n return array_merge( $priority_query, $query );\n } else {\n return $query;\n }\n }\n }\n\n return $query;\n }\n</code></pre>\n\n<p>This works fine but because I needed to have ALL the results to do the comparison with my \"priority post\" ids vs the results ids, I had to set <code>posts_per_page</code> to -1. So while it works, unless I find a way to put back pagination or write something custom, the search results will give me all of the results on search.php whether it's 5 or 500. Still, I'm placing this code here in case it helps someone else in the long run.</p>\n\n<p>For my case though, I've decided to do two separate queries and I confirmed we don't care about having duplicates. So I'll query just the priority posts matching the search term above the main search results query.</p>\n" }, { "answer_id": 337602, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 1, "selected": false, "text": "<p>Just to elaborate on what we've been talking about in the comments. I know you solved this already for your use case, so this is more for completeness’ sake and proof of concept purposes. Untested, for more information see the code comments. </p>\n\n<pre><code>add_action( 'pre_get_posts', 'prioritized_before_rest' );\nfunction prioritized_before_rest( $q ) {\n if ( ! is_admin() &amp;&amp; $q-&gt;is_main_query() &amp;&amp; $q-&gt;is_search() ) { \n // get the search term\n $search_term = $q-&gt;get( 's' );\n // get the prioritized items\n $prioritized = new WP_Query( [ \n // it is a search, so it is ordered by relevance\n 's' =&gt; $search_term,\n // I assumed that is your condition\n 'meta_query' =&gt; [ [ \n 'key' =&gt; '_prioritize_s',\n 'compare' =&gt; 'EXISTS',\n ], ],\n // we want them all\n 'posts_per_page' =&gt; -1,\n // but only ids\n 'fields' =&gt; 'ids',\n ] );\n // array of ids\n $prioritized_ids = $prioritized-&gt;posts;\n\n $rest = new WP_Query( [ \n 's' =&gt; $search_term,\n // get the rest by excluding above queried priorizied items\n 'post__not_in' =&gt; $prioritized_ids,\n 'posts_per_page' =&gt; -1,\n 'fields' =&gt; 'ids',\n ] );\n $rest_ids = $rest-&gt;posts;\n\n // merge above queried ids, order matters\n $prioritized_before_rest = array_merge( $prioritized_ids, $rest_ids );\n\n // use merged array, this alone does nothing \n // but to get all posts as would the unaltered query\n $q-&gt;set( 'post__in', $prioritized_before_rest );\n // we can set orderby to post__in though to preserve the order \n // established with above queries and merging the arrays\n // this keeps standard posts_per_page setting and pagination alive\n $q-&gt;set( 'orderby', 'post__in' );\n }\n}\n</code></pre>\n" } ]
2019/05/03
[ "https://wordpress.stackexchange.com/questions/337022", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/42783/" ]
I'm trying to re-order the search results using the `pre_get_posts` hook and set the `orderby` parameter to relevance. I also want to put priority posts, which is based on post meta `_prioritize_s` to be placed first in the results. Then all the posts after will be based on relevance as usual. Here's the code I've been messing with: ``` //runs on pre_get_posts function modify_search_results_order( $query ) { if ( $query->is_main_query() && is_search() && ! is_admin() ) { $query->query_vars['order'] = 'DESC'; $query->query_vars['orderby'] = 'relevance'; $query->query_vars['post_status'] = 'publish'; // $query->query_vars['meta_query'] = [ // 'relation' => 'OR', // array( // 'key' => '_prioritize_s', // 'compare' => 'EXISTS' // ), // array( // 'key' => '_prioritize_s', // 'compare' => 'NOT EXISTS' // ) // ]; } return $query; } ``` I originally had the `orderby` set to `meta_value relevance` and it did put the priority posts on top with the meta\_query uncommented. However, it doesn't keep the relevance sorting intact for posts afterwards. It seems like the meta query is affecting the overall order. I have a feeling I might need something custom like a database query instead? Doesn't seem like I'm going to get what I need by just setting the `$query->query_vars`. Can anyone help out? Thanks in advance! --- **UPDATE:** Since I haven't figured out how to alter the code I posted above, I'm trying an alternate solution. Let me know if it's the wrong way to go about it. Leaving the above code alone, I can use the `found_posts` hook to alter the search results query after my `pre_get_posts` function has already done it's magic. However my only issue is the second parameter that should give me the query is only giving me 10 posts when I know the results should be more than that. Why is it limiting it to 10 posts even if I set `posts_per_page` to `-1` in my `pre_get_posts` function? ``` function modify_search_results_prioritized( $found_posts, $wp_query ) { if ( is_search() ) { //this says 10 - why? error_out($wp_query->query_vars['posts_per_page']); } return $found_posts; } ```
So after @Nicolai found that blurb in the WP source confirming that I can't use multiple parameters in the `orderby` if I am ordering by `relevance` I had to go a different route. However, this route only works if I don't care for pagination. There probably is a way to put it back, but I'm working on a different solution now and I no longer need to stay on the code I have in my question. So I kept the function to alter the query on `pre_get_posts` and removed anything regarding post meta/meta queries: ``` function modify_search_results_order( $query ) { if ( $query->is_main_query() && is_search() && ! is_admin() ) { $get_expired_events = Event_Helpers::get_expired_event_ids(); $query->query_vars['posts_per_page'] = - 1; $query->query_vars['order'] = 'DESC'; $query->query_vars['is_search'] = true; $query->query_vars['post__not_in'] = $get_expired_events; $query->query_vars['orderby'] = 'relevance'; $query->query_vars['post_status'] = 'publish'; } return $query; } ``` Then in my search template, I call a function that alters the query after `pre_get_posts` to look for the priority posts, unset them from the main query, and place them back on top: ``` //in search.php $wp_query->posts = Search_Modify_Query::rearrange_search_query_for_priority_relevance( $wp_query->posts ); //in PHP Class public static function rearrange_search_query_for_priority_relevance( $query ) { //get prioritized ids $get_prioritized = self::get_priority_search_post_ids(); $get_results_ids = []; if ( ! is_array( $get_prioritized ) || ! $get_prioritized ) { return $query; } //save all ids from current search results query foreach ( $query as $key => $post ) { $get_results_ids[ $key ] = $post->ID; } if ( ! $get_results_ids ) { return $query; } //check if there are priority posts in results if ( array_intersect( $get_prioritized, $get_results_ids ) ) { $priority_matches = array_intersect( $get_results_ids, $get_prioritized ); $priority_query = false; //if there are priority matches, pluck them out to put them on top if ( $priority_matches ) { foreach ( $priority_matches as $key => $priority_match ) { //save these into new array first $priority_query[ $key ] = $query[ $key ]; //then unset them from main query unset( $query[ $key ] ); } if ( $priority_query && is_array( $priority_query ) ) { //then re-add them on top of main query return array_merge( $priority_query, $query ); } else { return $query; } } } return $query; } ``` This works fine but because I needed to have ALL the results to do the comparison with my "priority post" ids vs the results ids, I had to set `posts_per_page` to -1. So while it works, unless I find a way to put back pagination or write something custom, the search results will give me all of the results on search.php whether it's 5 or 500. Still, I'm placing this code here in case it helps someone else in the long run. For my case though, I've decided to do two separate queries and I confirmed we don't care about having duplicates. So I'll query just the priority posts matching the search term above the main search results query.
337,056
<p>I have set 1024M in <code>php.ini</code> file:</p> <pre><code>memory_limit = 1024M </code></pre> <p>I have set it in <code>.htaccess</code> file:</p> <pre><code>&lt;IfModule mod_php7.c&gt; php_value memory_limit 1024M &lt;/IfModule&gt; </code></pre> <p>I have set it in <code>wp-config.php</code> file:</p> <pre><code>define( 'WP_MAX_MEMORY_LIMIT' , '1024M'); define( 'WP_MEMORY_LIMIT', '1024M' ); </code></pre> <p>But I still get the following error on a plugin page in my Wordpress admin area:</p> <pre><code>Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 61440 bytes) in /home/eroticnaughtines/public_html/wp-includes/functions.php on line 4212 </code></pre> <p>And yes, all the files are in the root directory of my Wordpress installation.</p>
[ { "answer_id": 337057, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": 0, "selected": false, "text": "<p>Try to create <code>.user.ini</code> file in root and put below code</p>\n\n<pre><code>upload_max_filesize = 500M\npost_max_size = 256M\nmemory_limit = 500M\nmax_execution_time = 300\nmax_input_vars = 500M\n</code></pre>\n\n<p>Try and let me know if any query.</p>\n\n<p>Hope it will help!</p>\n" }, { "answer_id": 371832, "author": "Amirali", "author_id": 27990, "author_profile": "https://wordpress.stackexchange.com/users/27990", "pm_score": -1, "selected": false, "text": "<p>Adding</p>\n<pre><code>define( 'WP_MAX_MEMORY_LIMIT' , '1024M');\ndefine( 'WP_MEMORY_LIMIT', '1024M' );\n</code></pre>\n<p>before</p>\n<pre><code>define('ABSPATH', dirname(__FILE__) . '/');\n</code></pre>\n<p>in your <code>wp-config.php</code> file should do the trick.</p>\n" } ]
2019/05/04
[ "https://wordpress.stackexchange.com/questions/337056", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130259/" ]
I have set 1024M in `php.ini` file: ``` memory_limit = 1024M ``` I have set it in `.htaccess` file: ``` <IfModule mod_php7.c> php_value memory_limit 1024M </IfModule> ``` I have set it in `wp-config.php` file: ``` define( 'WP_MAX_MEMORY_LIMIT' , '1024M'); define( 'WP_MEMORY_LIMIT', '1024M' ); ``` But I still get the following error on a plugin page in my Wordpress admin area: ``` Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 61440 bytes) in /home/eroticnaughtines/public_html/wp-includes/functions.php on line 4212 ``` And yes, all the files are in the root directory of my Wordpress installation.
Try to create `.user.ini` file in root and put below code ``` upload_max_filesize = 500M post_max_size = 256M memory_limit = 500M max_execution_time = 300 max_input_vars = 500M ``` Try and let me know if any query. Hope it will help!
337,076
<p>I have a quite specific problem, I created a query that currently has to display the first post differently from the rest and everything seemed to work, but there is a problem that displays the title twice can some help? This is my code:</p> <pre><code> // args $args = array( 'showposts' =&gt; 5, 'post_type' =&gt; 'post', 'orderby' =&gt; 'date', // 'order' =&gt; 'ASC', 'meta_query' =&gt; array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'type_id', 'value' =&gt; 'News', 'compare' =&gt; 'LIKE' ), ) ); // query $the_query = new WP_Query( $args ); ?&gt; &lt;?php if( $the_query-&gt;have_posts() ): $i = 0; while ($the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); if ( $i == 0 ) : ?&gt; &lt;div class="card mb-3"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" &gt;&lt;img src="&lt;?php the_post_thumbnail_url() ?&gt;" class="card-img-top"&gt;&lt;/a&gt; &lt;div class="card-body"&gt; &lt;h2 class="card-title"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;p class="card-text"&gt;&lt;small class="text-muted"&gt;&lt;?php the_time('F jS, Y'); ?&gt;&lt;/small&gt;&lt;/p&gt; &lt;p class="card-text"&gt;&lt;?php the_excerpt(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php endif; if ( $i != 0 ) : ?&gt; &lt;div class="secoundposttak"&gt; &lt;?php endif; ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;img src="&lt;?php the_field('thumbnail'); ?&gt;" /&gt; &lt;?php the_title(); ?&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php $i++; endwhile; endif; ?&gt; &lt;?php wp_reset_query(); // Restore global post data stomped by the_post(). ?&gt; </code></pre> <p><a href="https://i.stack.imgur.com/uhXti.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uhXti.png" alt="enter image description here"></a></p>
[ { "answer_id": 337081, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>It shows title twice, because your code should do exactly that...</p>\n\n<p>You can clearly see it, if you format it correctly:</p>\n\n<pre><code>// args\n$args = array(\n 'showposts' =&gt; 5,\n 'post_type' =&gt; 'post',\n 'orderby' =&gt; 'date',\n // 'order' =&gt; 'ASC',\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'key' =&gt; 'type_id',\n 'value' =&gt; 'News',\n 'compare' =&gt; 'LIKE'\n ),\n )\n);\n\n\n// query\n$the_query = new WP_Query( $args );\n?&gt;\n&lt;?php \n if ( $the_query-&gt;have_posts() ): \n $i = 0; \n while ( $the_query-&gt;have_posts() ) :\n $the_query-&gt;the_post();\n?&gt;\n\n &lt;?php if ( $i == 0 ) : ?&gt;\n &lt;div class=\"card mb-3\"&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" &gt;&lt;img src=\"&lt;?php the_post_thumbnail_url() ?&gt;\" class=\"card-img-top\"&gt;&lt;/a&gt;\n &lt;div class=\"card-body\"&gt;\n &lt;?php // here you print the title for first item only ?&gt;\n &lt;h2 class=\"card-title\"&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;p class=\"card-text\"&gt;&lt;small class=\"text-muted\"&gt;&lt;?php the_time('F jS, Y'); ?&gt;&lt;/small&gt;&lt;/p&gt;\n &lt;p class=\"card-text\"&gt;&lt;?php the_excerpt(); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php endif; ?&gt;\n\n &lt;?pho if ( $i != 0 ) : ?&gt;\n &lt;div class=\"secoundposttak\"&gt;\n &lt;?php endif; ?&gt;\n\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;\n &lt;img src=\"&lt;?php the_field('thumbnail'); ?&gt;\" /&gt;\n &lt;?php // and here you print title for every item, so for first item too - so you get it twice ?&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;\n &lt;/div&gt;\n\n &lt;?php\n $i++;\n endwhile;\n endif; ?&gt;\n\n &lt;?php wp_reset_query(); // Restore global post data stomped by the_post(). ?&gt;\n</code></pre>\n\n<p>Now you can clearly see, that you print something special for first item in loop, but you also print normal title for every item in the loop - so for the first item you will print both of them...</p>\n\n<p>And to be honest, it’s a very risky and messy way of enclosing html - it will be very easy to create unclosed tags, if you will code this way. As you already have problems with getting which part is printed when...</p>\n" }, { "answer_id": 337082, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 2, "selected": true, "text": "<p>Try this. The code has comments where modified.</p>\n\n<pre><code>&lt;?php \n\n // args\n $args = array(\n 'showposts' =&gt; 5,\n 'post_type' =&gt; 'post',\n 'orderby' =&gt; 'date',\n // 'order' =&gt; 'ASC',\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'key' =&gt; 'type_id',\n 'value' =&gt; 'News',\n 'compare' =&gt; 'LIKE'\n ),\n\n )\n );\n\n\n // query\n $the_query = new WP_Query( $args );\n ?&gt;\n &lt;?php if( $the_query-&gt;have_posts() ): \n $i = 0; \n while ($the_query-&gt;have_posts() ) :\n $the_query-&gt;the_post();\n\n // First post\n if ( $i == 0 ) : ?&gt;\n &lt;div class=\"card mb-3\"&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" &gt;&lt;img src=\"&lt;?php the_post_thumbnail_url() ?&gt;\" class=\"card-img-top\"&gt;&lt;/a&gt;\n &lt;div class=\"card-body\"&gt;\n &lt;h2 class=\"card-title\"&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;p class=\"card-text\"&gt;&lt;small class=\"text-muted\"&gt;&lt;?php the_time('F jS, Y'); ?&gt;&lt;/small&gt;&lt;/p&gt;\n &lt;p class=\"card-text\"&gt;&lt;?php the_excerpt(); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt; &lt;!-- Add this to close div with class card mb-3 --&gt;\n &lt;?php endif; \n\n\n // Other posts\n if ( $i != 0 ) : \n ?&gt;\n &lt;div class=\"secoundposttak\"&gt;\n &lt;?php //endif; &lt;-- Not needed, move it below (before $i++ ) ?&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;\n &lt;img src=\"&lt;?php the_field('thumbnail'); ?&gt;\" /&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;\n &lt;/div&gt;\n\n &lt;?php endif; // &lt;-- Add this for if ( $i != 0 ) : ?&gt;\n\n\n\n &lt;?php\n $i++;\n endwhile;\n endif; ?&gt;\n\n &lt;?php wp_reset_query(); // Restore global post data stomped by the_post(). ?&gt;\n</code></pre>\n\n<p><strong>Also pay attention</strong> to suggestion at the end of answer by @Krzysiek Dróżdż♦ . I hope this may help.</p>\n" } ]
2019/05/04
[ "https://wordpress.stackexchange.com/questions/337076", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167376/" ]
I have a quite specific problem, I created a query that currently has to display the first post differently from the rest and everything seemed to work, but there is a problem that displays the title twice can some help? This is my code: ``` // args $args = array( 'showposts' => 5, 'post_type' => 'post', 'orderby' => 'date', // 'order' => 'ASC', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'type_id', 'value' => 'News', 'compare' => 'LIKE' ), ) ); // query $the_query = new WP_Query( $args ); ?> <?php if( $the_query->have_posts() ): $i = 0; while ($the_query->have_posts() ) : $the_query->the_post(); if ( $i == 0 ) : ?> <div class="card mb-3"> <a href="<?php the_permalink(); ?>" ><img src="<?php the_post_thumbnail_url() ?>" class="card-img-top"></a> <div class="card-body"> <h2 class="card-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2> <p class="card-text"><small class="text-muted"><?php the_time('F jS, Y'); ?></small></p> <p class="card-text"><?php the_excerpt(); ?></p> </div> <?php endif; if ( $i != 0 ) : ?> <div class="secoundposttak"> <?php endif; ?> <a href="<?php the_permalink(); ?>"> <img src="<?php the_field('thumbnail'); ?>" /> <?php the_title(); ?> </a> </div> <?php $i++; endwhile; endif; ?> <?php wp_reset_query(); // Restore global post data stomped by the_post(). ?> ``` [![enter image description here](https://i.stack.imgur.com/uhXti.png)](https://i.stack.imgur.com/uhXti.png)
Try this. The code has comments where modified. ``` <?php // args $args = array( 'showposts' => 5, 'post_type' => 'post', 'orderby' => 'date', // 'order' => 'ASC', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'type_id', 'value' => 'News', 'compare' => 'LIKE' ), ) ); // query $the_query = new WP_Query( $args ); ?> <?php if( $the_query->have_posts() ): $i = 0; while ($the_query->have_posts() ) : $the_query->the_post(); // First post if ( $i == 0 ) : ?> <div class="card mb-3"> <a href="<?php the_permalink(); ?>" ><img src="<?php the_post_thumbnail_url() ?>" class="card-img-top"></a> <div class="card-body"> <h2 class="card-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2> <p class="card-text"><small class="text-muted"><?php the_time('F jS, Y'); ?></small></p> <p class="card-text"><?php the_excerpt(); ?></p> </div> </div> <!-- Add this to close div with class card mb-3 --> <?php endif; // Other posts if ( $i != 0 ) : ?> <div class="secoundposttak"> <?php //endif; <-- Not needed, move it below (before $i++ ) ?> <a href="<?php the_permalink(); ?>"> <img src="<?php the_field('thumbnail'); ?>" /> <?php the_title(); ?> </a> </div> <?php endif; // <-- Add this for if ( $i != 0 ) : ?> <?php $i++; endwhile; endif; ?> <?php wp_reset_query(); // Restore global post data stomped by the_post(). ?> ``` **Also pay attention** to suggestion at the end of answer by @Krzysiek Dróżdż♦ . I hope this may help.
337,090
<p>Hello can anyone please give me the code, and tell me where to put it, for how to the change the first letter or the active menu item to red?</p> <p>thank you</p>
[ { "answer_id": 337092, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>You can use CSS to change the first letter of a 'div' (class or element). See <a href=\"https://www.w3schools.com/cssref/sel_firstletter.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/cssref/sel_firstletter.asp</a> .</p>\n\n<p>That link (and others found with a simple googles of 'CSS change first letter of div' ) will get you started.</p>\n\n<p>CSS stuff is not really a type of question that is supported here. But the googles/bings/ducks are your friend...</p>\n" }, { "answer_id": 337093, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 2, "selected": false, "text": "<h1>1. CSS <code>::first-letter</code></h1>\n<p>The first option is <a href=\"https://www.w3schools.com/cssref/sel_firstletter.asp\" rel=\"nofollow noreferrer\">selector CSS</a> <code>::first-letter</code>.</p>\n<pre><code>li.menu-item.active a::first-letter {\n color: red;\n}\n</code></pre>\n<p>The <code>a</code> tag inside menu should have <code>display: block</code> / <code>display: inline-block</code>.</p>\n<blockquote>\n<p><strong>Note</strong>: The ::first-letter selector can only be used with block-level elements.</p>\n</blockquote>\n<h1>2. Filter <code>nav_menu_item_title</code></h1>\n<p>Another way is to use <code>nav_menu_item_title</code> filter and surround the first letter with an tag with CSS class.</p>\n<pre><code>add_filter( 'nav_menu_item_title', 'se337090_first_letter', 30, 4 );\nfunction se337090_first_letter( $title, $item, $args, $depth )\n{\n if ( $item-&gt;current )\n {\n //\n // after application of this filter, there is the concatenation:\n // $item_output .= $args-&gt;link_before . $title . $args-&gt;link_after;\n $first_letter = substr( $title, 0, 1);\n $title = substr($title, 1);\n $args-&gt;link_before .= sprintf( '&lt;span class=&quot;menu-item-first-letter&quot;&gt;%s&lt;/span&gt;', $first_letter );\n\n // but you can also add changes to the title:\n // $title_end = substr($title, 1);\n // $title = sprintf( '&lt;span class=&quot;menu-item-first-letter&quot;&gt;%s&lt;/span&gt;%s', $first_letter, $title_end )\n }\n return $title;\n}\n</code></pre>\n" } ]
2019/05/04
[ "https://wordpress.stackexchange.com/questions/337090", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167392/" ]
Hello can anyone please give me the code, and tell me where to put it, for how to the change the first letter or the active menu item to red? thank you
1. CSS `::first-letter` ======================= The first option is [selector CSS](https://www.w3schools.com/cssref/sel_firstletter.asp) `::first-letter`. ``` li.menu-item.active a::first-letter { color: red; } ``` The `a` tag inside menu should have `display: block` / `display: inline-block`. > > **Note**: The ::first-letter selector can only be used with block-level elements. > > > 2. Filter `nav_menu_item_title` =============================== Another way is to use `nav_menu_item_title` filter and surround the first letter with an tag with CSS class. ``` add_filter( 'nav_menu_item_title', 'se337090_first_letter', 30, 4 ); function se337090_first_letter( $title, $item, $args, $depth ) { if ( $item->current ) { // // after application of this filter, there is the concatenation: // $item_output .= $args->link_before . $title . $args->link_after; $first_letter = substr( $title, 0, 1); $title = substr($title, 1); $args->link_before .= sprintf( '<span class="menu-item-first-letter">%s</span>', $first_letter ); // but you can also add changes to the title: // $title_end = substr($title, 1); // $title = sprintf( '<span class="menu-item-first-letter">%s</span>%s', $first_letter, $title_end ) } return $title; } ```
337,160
<p>I am facing an issue in the Avada vertical menu when the homepage is opened. Please note that all "Home", "Company profile" and "Servizi" link to the same page (the homepage).</p> <p>The sub-menu under "Servizi" is already opened while I would prefer it was closed by default, and that it could be opened simply by hovering "servizi", as it works properly when you try hovering "Servizi" from both "Clienti" and "Contatti".</p> <p>I am pretty sure there is an option in Avada/WP to do that, or otherwise by adding some JS code, but I really have no idea how to do it!</p>
[ { "answer_id": 337162, "author": "Vishwa", "author_id": 120712, "author_profile": "https://wordpress.stackexchange.com/users/120712", "pm_score": 2, "selected": true, "text": "<p>To do that, you have to set <code>hidden</code> attribute to the sub menu.</p>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>#wrapper .fusion-vertical-menu-widget.left .menu .sub-menu {\n display: none;\n}\n</code></pre>\n\n<p>to toggle display on the menu on hover over servizi, you can add jQuery hover to the menu item.</p>\n\n<p><strong>jQuery</strong></p>\n\n<pre><code>var subMenu = jQuery(\"#wrapper .fusion-vertical-menu-widget.left .menu .sub-menu\");\n\njQuery(\"#menu-item-12049\").hover(function(){\n subMenu.show();\n }, function(){\n subMenu.hide();\n});\n</code></pre>\n\n<p><strong>Note:</strong> You should change the class values to more appropriate values, these are just extracted from what I saw, but probably a good idea to get better css selectors</p>\n" }, { "answer_id": 337176, "author": "Tommaso Cerci", "author_id": 167468, "author_profile": "https://wordpress.stackexchange.com/users/167468", "pm_score": 0, "selected": false, "text": "<p>So, now it works perfectly as I would like when you hover \"servizi\"! The only problem is for the sub-menu single pages, where the sub-menu should remain opened always, like it did before</p>\n\n<p>This is the code used currently in avada theme options:</p>\n\n<pre><code>&lt;script&gt;\njQuery(document).ready(function($){\nvar subMenu = jQuery(\"#wrapper .fusion-vertical-menu-widget.left .menu .sub-menu\");\njQuery(\"#menu-item-12049\").hover(function(){\nsubMenu.show();\n}, function(){\nsubMenu.hide();\n});\n});\n&lt;/script&gt;\n</code></pre>\n" } ]
2019/05/06
[ "https://wordpress.stackexchange.com/questions/337160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167468/" ]
I am facing an issue in the Avada vertical menu when the homepage is opened. Please note that all "Home", "Company profile" and "Servizi" link to the same page (the homepage). The sub-menu under "Servizi" is already opened while I would prefer it was closed by default, and that it could be opened simply by hovering "servizi", as it works properly when you try hovering "Servizi" from both "Clienti" and "Contatti". I am pretty sure there is an option in Avada/WP to do that, or otherwise by adding some JS code, but I really have no idea how to do it!
To do that, you have to set `hidden` attribute to the sub menu. **CSS** ``` #wrapper .fusion-vertical-menu-widget.left .menu .sub-menu { display: none; } ``` to toggle display on the menu on hover over servizi, you can add jQuery hover to the menu item. **jQuery** ``` var subMenu = jQuery("#wrapper .fusion-vertical-menu-widget.left .menu .sub-menu"); jQuery("#menu-item-12049").hover(function(){ subMenu.show(); }, function(){ subMenu.hide(); }); ``` **Note:** You should change the class values to more appropriate values, these are just extracted from what I saw, but probably a good idea to get better css selectors
337,163
<p>My client's WooCommerce shop is exporting orders as comma separated files for creation of packaging labels and accounting in C5.</p> <p>When users enter an address with a comma upon checkout, this screws up the CSV export. Example: "60 Brickyard Road, Lapeer". The comma after "Road" confuses C5 when importing.</p> <p>How can I filter out any commas before the address value is saved to the order?</p>
[ { "answer_id": 337168, "author": "Skovsgaard", "author_id": 114926, "author_profile": "https://wordpress.stackexchange.com/users/114926", "pm_score": 0, "selected": false, "text": "<p>I managed to prohibit the use of commas in both address fields with the following code. Add it to your functions.php file.</p>\n\n<pre><code>add_action( 'wp_footer', 'checkout_field_name_validator_script');\nfunction checkout_field_name_validator_script() {\n // Only on checkout page\n if( ! ( is_checkout() &amp;&amp; ! is_wc_endpoint_url() ) ) return;\n ?&gt;\n &lt;script&gt;\n jQuery(function($){\n var b = '#billing_', s = '#shipping_',\n a = 'address_1', c = ',';\n\n // Address fields\n $(b+a+c+s+a).bind('keyup blur',function(){\n $(this).val($(this).val().replace(/,/g,''));\n });\n\n });\n &lt;/script&gt;\n &lt;?php\n}\n</code></pre>\n\n<p>Thanks and credit to user <a href=\"https://stackoverflow.com/users/3730754/loictheaztec\">\"LoicTheAztec\"</a> in <a href=\"https://stackoverflow.com/questions/53909349/allow-only-letter-on-specific-woocommerce-checkout-fields/53910134#comment98649540_53910134\">this post</a>.</p>\n\n<p><strong>Important</strong> - This works for the frontend only. To validate and filter the input see the accepted answer.</p>\n" }, { "answer_id": 337247, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 3, "selected": true, "text": "<p>You can remove/replace comas from address_1 and address_2 billing and shipping fields with the following, once order is submitted <em>(before saving data)</em>:</p>\n\n<pre><code>// Checkout/Order: Remove/replace comas from adresses fields\nadd_action('woocommerce_checkout_create_order', 'remove_comas_from_address_fields', 10, 2 );\nfunction remove_comas_from_address_fields( $order, $data ) {\n $replacement = '';\n\n if ( $billing_address_1 = $order-&gt;get_billing_address_1() ) {\n $order-&gt;set_billing_address_1( str_replace( ',', $replacement, $billing_address_1 ) );\n }\n\n if ( $billing_address_2 = $order-&gt;get_billing_address_2() ) {\n $order-&gt;set_billing_address_2( str_replace( ',', $replacement, $billing_address_2 ) );\n }\n\n if ( $shipping_address_1 = $order-&gt;get_shipping_address_1() ) {\n $order-&gt;set_shipping_address_1( str_replace( ',', $replacement, $shipping_address_1 ) );\n }\n\n if ( $shipping_address_2 = $order-&gt;get_shipping_address_2() ) {\n $order-&gt;set_shipping_address_2( str_replace( ',', $replacement, $shipping_address_2 ) );\n }\n}\n</code></pre>\n\n<p>Code goes in function.php file of your active child theme (or active theme). Tested and works.</p>\n\n<p>If you wish, you can also keep your answer code at the same time. This way everything will be secure in case of manipulation.</p>\n" } ]
2019/05/06
[ "https://wordpress.stackexchange.com/questions/337163", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114926/" ]
My client's WooCommerce shop is exporting orders as comma separated files for creation of packaging labels and accounting in C5. When users enter an address with a comma upon checkout, this screws up the CSV export. Example: "60 Brickyard Road, Lapeer". The comma after "Road" confuses C5 when importing. How can I filter out any commas before the address value is saved to the order?
You can remove/replace comas from address\_1 and address\_2 billing and shipping fields with the following, once order is submitted *(before saving data)*: ``` // Checkout/Order: Remove/replace comas from adresses fields add_action('woocommerce_checkout_create_order', 'remove_comas_from_address_fields', 10, 2 ); function remove_comas_from_address_fields( $order, $data ) { $replacement = ''; if ( $billing_address_1 = $order->get_billing_address_1() ) { $order->set_billing_address_1( str_replace( ',', $replacement, $billing_address_1 ) ); } if ( $billing_address_2 = $order->get_billing_address_2() ) { $order->set_billing_address_2( str_replace( ',', $replacement, $billing_address_2 ) ); } if ( $shipping_address_1 = $order->get_shipping_address_1() ) { $order->set_shipping_address_1( str_replace( ',', $replacement, $shipping_address_1 ) ); } if ( $shipping_address_2 = $order->get_shipping_address_2() ) { $order->set_shipping_address_2( str_replace( ',', $replacement, $shipping_address_2 ) ); } } ``` Code goes in function.php file of your active child theme (or active theme). Tested and works. If you wish, you can also keep your answer code at the same time. This way everything will be secure in case of manipulation.
337,180
<p>I'm trying to find a way to permanently remove the <code>delete_attachment</code> button from the media details modal. I don't want to use CSS to do it... and haven't been able to find a way as of now. Does anyone have an idea ? </p>
[ { "answer_id": 337190, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>Rather than focusing on the button itself, focus on what you want users to do. If you don't want your users to be able to delete media, and you are also comfortable with them not being able to delete other post types (Posts, Pages, etc.), you can create a custom role for these users.</p>\n\n<pre><code>&lt;?php\n// In a plugin, add_role will create an entirely new role to assign to users.\nadd_role('media_editor', 'Media Editor', array(\n // The capabilities below will let these users add, edit, read,\n // but not delete any type of content.\n 'create_posts' =&gt; true,\n 'edit_posts' =&gt; true,\n 'edit_others_posts' =&gt; true,\n 'edit_private_posts' =&gt; true,\n 'edit_published_posts' =&gt; true,\n 'read_private_posts' =&gt; true,\n 'read' =&gt; true,\n 'upload_files' =&gt; true\n // You may also wish to add capabilities for other post types,\n // such as create_pages, edit_pages, or custom capabilities\n // for custom post types.\n);\n?&gt;\n</code></pre>\n\n<p>Once this code runs, you can then edit each user and change their role to \"Media Editor\" (or whatever you decide to call it in your code).</p>\n\n<p>By removing the users' ability to delete any type of posts, they will no longer see the delete button in the media details modal, or any other location. If instead you focus on one button in one modal, you may be leaving other locations - such as the Media Library itself - with buttons they can still use.</p>\n" }, { "answer_id": 337191, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>I you look at the code that generates this button in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/media-template.php\" rel=\"nofollow noreferrer\"><code>media-template.php</code></a> (currently on lines 488 and 599) you can see that it is pretty much hard coded. So there is no easy way to make sure this button doesn't show up. Hiding it with CSS seems to be the right way.</p>\n\n<p>That would not prevent people from unhiding by fiddling with the CSS, of course. But if someone really means to do harm, he could copy the whole html node from another install and copy it into the DOM of your site on his user side. Then he could still delete the file ... unless you make sure on the server side that the command is not accepted. Ultimately, if you want to prevent people from deleting files, it is not about what code you send to the user end. It's about what is accepted on the server end. That's what you should manage.</p>\n\n<p>A simple option would be to look into <a href=\"https://developer.wordpress.org/reference/functions/wp_delete_attachment/\" rel=\"nofollow noreferrer\"><code>wp_delete_attachment</code></a>. You could use the <code>delete_attachment</code> hook to see if the current user is supposed to do deleting here and <a href=\"https://codex.wordpress.org/Function_Reference/wp_die\" rel=\"nofollow noreferrer\">kill the page load</a> if he is not. A bit crude, but it works.</p>\n" } ]
2019/05/06
[ "https://wordpress.stackexchange.com/questions/337180", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I'm trying to find a way to permanently remove the `delete_attachment` button from the media details modal. I don't want to use CSS to do it... and haven't been able to find a way as of now. Does anyone have an idea ?
Rather than focusing on the button itself, focus on what you want users to do. If you don't want your users to be able to delete media, and you are also comfortable with them not being able to delete other post types (Posts, Pages, etc.), you can create a custom role for these users. ``` <?php // In a plugin, add_role will create an entirely new role to assign to users. add_role('media_editor', 'Media Editor', array( // The capabilities below will let these users add, edit, read, // but not delete any type of content. 'create_posts' => true, 'edit_posts' => true, 'edit_others_posts' => true, 'edit_private_posts' => true, 'edit_published_posts' => true, 'read_private_posts' => true, 'read' => true, 'upload_files' => true // You may also wish to add capabilities for other post types, // such as create_pages, edit_pages, or custom capabilities // for custom post types. ); ?> ``` Once this code runs, you can then edit each user and change their role to "Media Editor" (or whatever you decide to call it in your code). By removing the users' ability to delete any type of posts, they will no longer see the delete button in the media details modal, or any other location. If instead you focus on one button in one modal, you may be leaving other locations - such as the Media Library itself - with buttons they can still use.
337,192
<p>In WooCommerce, I am trying to send an email notification to the customer, when an order has a status "cancelled". </p> <p>Here is my code placed in my child theme's function.php file:</p> <pre><code>add_filter('woocommerce_order_status_changed', 'send_mail_abandonned_order', 10, 4); function woocommerce_send_mail_abandonned_order($order, $new_status) { if (!$order || $new_status != 'cancelled') return; print("Entering in function"); //nothing append throw new("error"); // Nothing append //$order = new WC_Order($order_id); $order = wc_get_order($order); if ( $new_status == 'cancelled' ) { //$customer_email = $order-&gt;get_billing_email(); // The customer email ob_start(); include( 'email/mail.php' ); $message = ob_get_clean(); define("HTML_EMAIL_HEADERS", array('Content-Type: text/html; charset=UTF-8')); // Get woocommerce mailer from instance $mailer = WC()-&gt;mailer(); // Wrap message using woocommerce html email template $wrapped_message = $mailer-&gt;wrap_message("Vous n'avez pas oublié quelque chose ?", $message); // Create new WC_Email instance $wc_email = new WC_Email; // Style the wrapped message with woocommerce inline styles $html_message = $wc_email-&gt;style_inline($wrapped_message); // Send the email using wordpress mail function wp_mail( "[email protected]", 'Oups Vous n\'avez pas oubliez quelque chose ?', $html_message, HTML_EMAIL_HEADERS ); } } </code></pre> <p>But I don't know why this hook is not working properly. When I change the order status to cancelled and try to throw an error, nothing is appended to my php errors logs. It seems that this hook is not working. </p> <p>How to solve this issue?</p>
[ { "answer_id": 337276, "author": "Oliver", "author_id": 161218, "author_profile": "https://wordpress.stackexchange.com/users/161218", "pm_score": -1, "selected": true, "text": "<p>Here is the solution...</p>\n\n<pre>\n\n// CHANGE THE HOOK DESCRIPTION\nadd_filter('woocommerce_order_status_cancelled', 'woocommerce_send_mail_abandonned_order',21, 1);\nfunction woocommerce_send_mail_abandonned_order($order_id)\n{\n if (!$order_id) return;\n $order = wc_get_order($order_id);\n if ($order->has_status('cancelled')) {\n //$customer_email = $order->get_billing_email(); // The customer email\n ob_start();\n include( 'email/mail.php' );\n $message = ob_get_clean();\n define(\"HTML_EMAIL_HEADERS\", array('Content-Type: text/html; charset=UTF-8'));\n // Get woocommerce mailer from instance\n $mailer = WC()->mailer();\n // Wrap message using woocommerce html email template\n $wrapped_message = $mailer->wrap_message(\"Vous n'avez pas oublié quelque chose ?\", $message);\n // Create new WC_Email instance\n $wc_email = new WC_Email;\n // Style the wrapped message with woocommerce inline styles\n $html_message = $wc_email->style_inline($wrapped_message);\n // Send the email using wordpress mail function\n wp_mail( \"[email protected]\", 'Oups Vous n\\'avez pas oubliez quelque chose ?', $html_message, HTML_EMAIL_HEADERS );\n } \n}\n\n</pre>\n\n<p>Change $order by $order_id too</p>\n" }, { "answer_id": 337282, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 0, "selected": false, "text": "<p>A better solution will be to use all arguments included in <code>woocommerce_order_status_cancelled</code> hooked function, so the missing <code>$order</code> variable. </p>\n\n<p>Also as the action hook <code>woocommerce_order_status_cancelled</code> is triggered when order status change to \"cancelled\", so in your code, <code>if ($order-&gt;has_status('cancelled')) {</code> is not needed.</p>\n\n<p>Then your code will be:</p>\n\n<pre><code>add_filter('woocommerce_order_status_cancelled', 'woocommerce_send_mail_abandonned_order', 10, 2 );\nfunction woocommerce_send_mail_abandonned_order( $order_id, $order )\n{\n define(\"HTML_EMAIL_HEADERS\", array('Content-Type: text/html; charset=UTF-8'));\n\n // Get WooCommerce mailer from instance\n $mailer = WC()-&gt;mailer();\n\n ob_start();\n include( 'email/mail.php' );\n $message = ob_get_clean();\n\n // Wrap message using woocommerce html email template\n $wrapped_message = $mailer-&gt;wrap_message(\"Vous n'avez pas oublié quelque chose ?\", $message);\n\n // Create new WC_Email instance\n $wc_email = new WC_Email;\n\n // Style the wrapped message with woocommerce inline styles\n $html_message = $wc_email-&gt;style_inline($wrapped_message);\n\n // Send the email using wordpress mail function\n wp_mail( $order-&gt;get_billing_email(), 'Oups Vous n\\'avez pas oubliez quelque chose ?', $html_message, HTML_EMAIL_HEADERS );\n}\n</code></pre>\n\n<p>Or with <code>woocommerce_order_status_changed</code> hook <em>(your question hook)</em>:</p>\n\n<pre><code>add_filter('woocommerce_order_status_changed', 'woocommerce_send_mail_abandonned_order', 10, 4 );\nfunction woocommerce_send_mail_abandonned_order( $order_id, $old_status, $new_status, $order )\n{\n if ( $new_status === 'cancelled') \n {\n define(\"HTML_EMAIL_HEADERS\", array('Content-Type: text/html; charset=UTF-8'));\n\n // Get WooCommerce mailer from instance\n $mailer = WC()-&gt;mailer();\n\n ob_start();\n include( 'email/mail.php' );\n $message = ob_get_clean();\n\n // Wrap message using woocommerce html email template\n $wrapped_message = $mailer-&gt;wrap_message(\"Vous n'avez pas oublié quelque chose ?\", $message);\n\n // Create new WC_Email instance\n $wc_email = new WC_Email;\n\n // Style the wrapped message with woocommerce inline styles\n $html_message = $wc_email-&gt;style_inline($wrapped_message);\n\n // Send the email using wordpress mail function\n wp_mail( $order-&gt;get_billing_email(), 'Oups Vous n\\'avez pas oubliez quelque chose ?', $html_message, HTML_EMAIL_HEADERS );\n }\n}\n</code></pre>\n\n<p>Code goes in functions.php file of your active child theme (or active theme). Tested and works.</p>\n" } ]
2019/05/06
[ "https://wordpress.stackexchange.com/questions/337192", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/161218/" ]
In WooCommerce, I am trying to send an email notification to the customer, when an order has a status "cancelled". Here is my code placed in my child theme's function.php file: ``` add_filter('woocommerce_order_status_changed', 'send_mail_abandonned_order', 10, 4); function woocommerce_send_mail_abandonned_order($order, $new_status) { if (!$order || $new_status != 'cancelled') return; print("Entering in function"); //nothing append throw new("error"); // Nothing append //$order = new WC_Order($order_id); $order = wc_get_order($order); if ( $new_status == 'cancelled' ) { //$customer_email = $order->get_billing_email(); // The customer email ob_start(); include( 'email/mail.php' ); $message = ob_get_clean(); define("HTML_EMAIL_HEADERS", array('Content-Type: text/html; charset=UTF-8')); // Get woocommerce mailer from instance $mailer = WC()->mailer(); // Wrap message using woocommerce html email template $wrapped_message = $mailer->wrap_message("Vous n'avez pas oublié quelque chose ?", $message); // Create new WC_Email instance $wc_email = new WC_Email; // Style the wrapped message with woocommerce inline styles $html_message = $wc_email->style_inline($wrapped_message); // Send the email using wordpress mail function wp_mail( "[email protected]", 'Oups Vous n\'avez pas oubliez quelque chose ?', $html_message, HTML_EMAIL_HEADERS ); } } ``` But I don't know why this hook is not working properly. When I change the order status to cancelled and try to throw an error, nothing is appended to my php errors logs. It seems that this hook is not working. How to solve this issue?
Here is the solution... ``` // CHANGE THE HOOK DESCRIPTION add_filter('woocommerce_order_status_cancelled', 'woocommerce_send_mail_abandonned_order',21, 1); function woocommerce_send_mail_abandonned_order($order_id) { if (!$order_id) return; $order = wc_get_order($order_id); if ($order->has_status('cancelled')) { //$customer_email = $order->get_billing_email(); // The customer email ob_start(); include( 'email/mail.php' ); $message = ob_get_clean(); define("HTML_EMAIL_HEADERS", array('Content-Type: text/html; charset=UTF-8')); // Get woocommerce mailer from instance $mailer = WC()->mailer(); // Wrap message using woocommerce html email template $wrapped_message = $mailer->wrap_message("Vous n'avez pas oublié quelque chose ?", $message); // Create new WC_Email instance $wc_email = new WC_Email; // Style the wrapped message with woocommerce inline styles $html_message = $wc_email->style_inline($wrapped_message); // Send the email using wordpress mail function wp_mail( "[email protected]", 'Oups Vous n\'avez pas oubliez quelque chose ?', $html_message, HTML_EMAIL_HEADERS ); } } ``` Change $order by $order\_id too
337,196
<p>I have a custom theme. I've deactivated every plugin. I can't get the Featured Image block on the right sidebar of editing a post to show up so that the user can set the featured image. </p> <p>I have this in my functions.php file:</p> <pre><code>add_theme_support( 'post-thumbnails' ); </code></pre> <p>Note that this worked fine before Wordpress 5 / Gutenberg update.</p> <p>What am I missing?</p>
[ { "answer_id": 337210, "author": "RailsTweeter", "author_id": 48623, "author_profile": "https://wordpress.stackexchange.com/users/48623", "pm_score": 2, "selected": false, "text": "<p>The function with the add_theme_support( 'post-thumbnails' ); wasn't being called for some reason. Once I fixed that, everything works now.</p>\n" }, { "answer_id": 403786, "author": "Sajid Javed", "author_id": 183431, "author_profile": "https://wordpress.stackexchange.com/users/183431", "pm_score": 0, "selected": false, "text": "<p>I'm facing the same issue. I also can't see the thumbnail meta box in Gutenberg editor.</p>\n<p>I tried different ways but unfortunately, still, the same issue exists.</p>\n<p>In the below code, you can see I enable the post-thumbnails for post and page.</p>\n<pre><code>add_theme_support('post-thumbnails', array('post', 'page'));\n</code></pre>\n<p>When I found the above code was not working then I tried the below code</p>\n<pre><code>add_action('after_setup_theme', function () {\n remove_theme_support('post-thumbnails');\n add_theme_support('post-thumbnails', array('post', 'page', 'hero', 'event', 'video'));\n});\n</code></pre>\n<p>But still, the same issue exists.</p>\n<p>Note: If I disable the Gutenberg editor by using this code then I can see the thumbnail image meta box</p>\n<pre><code>add_filter('use_block_editor_for_post', '__return_false', 10);\n</code></pre>\n<p>Waiting for your help!</p>\n<p>Thanks!</p>\n" } ]
2019/05/06
[ "https://wordpress.stackexchange.com/questions/337196", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48623/" ]
I have a custom theme. I've deactivated every plugin. I can't get the Featured Image block on the right sidebar of editing a post to show up so that the user can set the featured image. I have this in my functions.php file: ``` add_theme_support( 'post-thumbnails' ); ``` Note that this worked fine before Wordpress 5 / Gutenberg update. What am I missing?
The function with the add\_theme\_support( 'post-thumbnails' ); wasn't being called for some reason. Once I fixed that, everything works now.
337,238
<p>I have a WordPress site, with WooCommerce. The WooCommerce archives pages as shop display a dropdown sorting filter like in this screenshot: </p> <p><a href="https://i.stack.imgur.com/Z44XN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z44XN.png" alt="enter image description here"></a> Now in another page let's say <code>example.com/foo</code> On that page I use a WooCommerce shortcode: </p> <pre><code>[product_category per_page="90" columns="3" orderby="" order="ASC" category="foo" prdctfltr="yes" pagination="yes"] </code></pre> <p>But the sorting dropdown is not shown.</p> <p>What I am doing wrong? How can I display the sorting dropdown?</p>
[ { "answer_id": 337210, "author": "RailsTweeter", "author_id": 48623, "author_profile": "https://wordpress.stackexchange.com/users/48623", "pm_score": 2, "selected": false, "text": "<p>The function with the add_theme_support( 'post-thumbnails' ); wasn't being called for some reason. Once I fixed that, everything works now.</p>\n" }, { "answer_id": 403786, "author": "Sajid Javed", "author_id": 183431, "author_profile": "https://wordpress.stackexchange.com/users/183431", "pm_score": 0, "selected": false, "text": "<p>I'm facing the same issue. I also can't see the thumbnail meta box in Gutenberg editor.</p>\n<p>I tried different ways but unfortunately, still, the same issue exists.</p>\n<p>In the below code, you can see I enable the post-thumbnails for post and page.</p>\n<pre><code>add_theme_support('post-thumbnails', array('post', 'page'));\n</code></pre>\n<p>When I found the above code was not working then I tried the below code</p>\n<pre><code>add_action('after_setup_theme', function () {\n remove_theme_support('post-thumbnails');\n add_theme_support('post-thumbnails', array('post', 'page', 'hero', 'event', 'video'));\n});\n</code></pre>\n<p>But still, the same issue exists.</p>\n<p>Note: If I disable the Gutenberg editor by using this code then I can see the thumbnail image meta box</p>\n<pre><code>add_filter('use_block_editor_for_post', '__return_false', 10);\n</code></pre>\n<p>Waiting for your help!</p>\n<p>Thanks!</p>\n" } ]
2019/05/06
[ "https://wordpress.stackexchange.com/questions/337238", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165273/" ]
I have a WordPress site, with WooCommerce. The WooCommerce archives pages as shop display a dropdown sorting filter like in this screenshot: [![enter image description here](https://i.stack.imgur.com/Z44XN.png)](https://i.stack.imgur.com/Z44XN.png) Now in another page let's say `example.com/foo` On that page I use a WooCommerce shortcode: ``` [product_category per_page="90" columns="3" orderby="" order="ASC" category="foo" prdctfltr="yes" pagination="yes"] ``` But the sorting dropdown is not shown. What I am doing wrong? How can I display the sorting dropdown?
The function with the add\_theme\_support( 'post-thumbnails' ); wasn't being called for some reason. Once I fixed that, everything works now.
337,261
<p><a href="https://i.stack.imgur.com/rBHsk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rBHsk.png" alt="enter image description here"></a></p> <p>These are actually input fields. paragraph is the textarea field. i query the contents from database and try to show them in this textarea field. But the textarea field is showing me unwanted comments and tags. When I echo them outtside the textarea field, it is fine.</p> <p>My code....</p> <pre><code> &lt;?php while($userNotes-&gt;have_posts()): $userNotes-&gt;the_post(); ?&gt; &lt;li&gt; &lt;input value="&lt;?php echo esc_attr(get_the_title()); ?&gt;" class="note-title-field"&gt; &lt;span class="edit-note"&gt;&lt;i class="fa fa-pencil" aria-hidden="true"&gt;&lt;/i&gt; Edit&lt;/span&gt; &lt;span class="delete-note"&gt;&lt;i class="fa fa-trash-o" aria-hidden="true"&gt;&lt;/i&gt; Delete&lt;/span&gt; &lt;textarea class="note-body-field"&gt;&lt;?php echo esc_attr(get_the_content()); ?&gt;&lt;/textarea&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; </code></pre>
[ { "answer_id": 337262, "author": "Shohidur Rahman", "author_id": 163783, "author_profile": "https://wordpress.stackexchange.com/users/163783", "pm_score": -1, "selected": false, "text": "<p>Can you please try this php function <code>html_entity_decode(get_the_content());</code>. I have used this function on php to remove html tags, you can try this.</p>\n" }, { "answer_id": 367008, "author": "T Kly", "author_id": 188397, "author_profile": "https://wordpress.stackexchange.com/users/188397", "pm_score": -1, "selected": false, "text": "<p>You can try this:</p>\n\n<pre><code>&lt;textarea class=\"note-body-field\"&gt;&lt;?php echo sanitize_text_field(get_the_content()); ?&gt;\n&lt;/textarea&gt;\n</code></pre>\n\n<p>I'm also a beginner, but found this works in the frontend.\nAnd it seems to be intended for similar use cases - <a href=\"https://developer.wordpress.org/reference/functions/sanitize_text_field/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/sanitize_text_field/</a></p>\n" } ]
2019/05/07
[ "https://wordpress.stackexchange.com/questions/337261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149458/" ]
[![enter image description here](https://i.stack.imgur.com/rBHsk.png)](https://i.stack.imgur.com/rBHsk.png) These are actually input fields. paragraph is the textarea field. i query the contents from database and try to show them in this textarea field. But the textarea field is showing me unwanted comments and tags. When I echo them outtside the textarea field, it is fine. My code.... ``` <?php while($userNotes->have_posts()): $userNotes->the_post(); ?> <li> <input value="<?php echo esc_attr(get_the_title()); ?>" class="note-title-field"> <span class="edit-note"><i class="fa fa-pencil" aria-hidden="true"></i> Edit</span> <span class="delete-note"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete</span> <textarea class="note-body-field"><?php echo esc_attr(get_the_content()); ?></textarea> </li> <?php endwhile; ?> ```
Can you please try this php function `html_entity_decode(get_the_content());`. I have used this function on php to remove html tags, you can try this.
337,290
<p>I am trying to add a css file specific to 3 pages using the <code>is_page(postid)</code> for a WordPress website in the <code>functions.php</code> </p> <pre><code> if (is_page(1) || is_page(2) || is_page(3) ) { echo "&lt;script&gt;console.log('insideIf');&lt;/script&gt;"; wp_enqueue_style( 'custom_css', get_template_directory_child() . path); } </code></pre> <p>So considering 1,2 and 3 are the ids of the pages, the pages with the ids 2 and 3 are logging the message in the console and loading the css file whereas <code>is_page(1)</code> does not respond. </p> <p>I tried changing it to <code>is_page('1')</code> or <code>is_single()</code> or <code>is_single(1)</code>. The page that is not getting detected is a blog page and i even tried with the title <code>is_page('blog')</code>.</p> <p>Ps. Cross checked the id many times, so I am definitely not using the wrong id. </p>
[ { "answer_id": 337262, "author": "Shohidur Rahman", "author_id": 163783, "author_profile": "https://wordpress.stackexchange.com/users/163783", "pm_score": -1, "selected": false, "text": "<p>Can you please try this php function <code>html_entity_decode(get_the_content());</code>. I have used this function on php to remove html tags, you can try this.</p>\n" }, { "answer_id": 367008, "author": "T Kly", "author_id": 188397, "author_profile": "https://wordpress.stackexchange.com/users/188397", "pm_score": -1, "selected": false, "text": "<p>You can try this:</p>\n\n<pre><code>&lt;textarea class=\"note-body-field\"&gt;&lt;?php echo sanitize_text_field(get_the_content()); ?&gt;\n&lt;/textarea&gt;\n</code></pre>\n\n<p>I'm also a beginner, but found this works in the frontend.\nAnd it seems to be intended for similar use cases - <a href=\"https://developer.wordpress.org/reference/functions/sanitize_text_field/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/sanitize_text_field/</a></p>\n" } ]
2019/05/07
[ "https://wordpress.stackexchange.com/questions/337290", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150032/" ]
I am trying to add a css file specific to 3 pages using the `is_page(postid)` for a WordPress website in the `functions.php` ``` if (is_page(1) || is_page(2) || is_page(3) ) { echo "<script>console.log('insideIf');</script>"; wp_enqueue_style( 'custom_css', get_template_directory_child() . path); } ``` So considering 1,2 and 3 are the ids of the pages, the pages with the ids 2 and 3 are logging the message in the console and loading the css file whereas `is_page(1)` does not respond. I tried changing it to `is_page('1')` or `is_single()` or `is_single(1)`. The page that is not getting detected is a blog page and i even tried with the title `is_page('blog')`. Ps. Cross checked the id many times, so I am definitely not using the wrong id.
Can you please try this php function `html_entity_decode(get_the_content());`. I have used this function on php to remove html tags, you can try this.
337,331
<p>I'd like my custom post type, products, to not use a slug, eg: domain.com/product-name. The code below sorts that out nicely, however it fails to work with child pages, eg: domain.com/product-name/product-name-feature, it 404s.</p> <p>I originally tried giving the custom post type the rewrite slug as '/', and while this was great for the custom post type, it killed normal pages (404). So if the solution is to use '/' and then fix normal pages, that's fine too.</p> <pre><code>// Post Type function base_types() { $labels = array( 'name' =&gt; 'Products &amp; Features', 'singular_name' =&gt; 'Product', 'add_new' =&gt; 'Add New', 'add_new_item' =&gt; 'Add New Product / Feature', 'edit_item' =&gt; 'Edit Product', 'new_item' =&gt; 'New Product', 'all_items' =&gt; 'All', 'view_item' =&gt; 'View Product / Feature', 'search_items' =&gt; 'Search Product / Feature', 'not_found' =&gt; 'None found', 'not_found_in_trash' =&gt; 'None found in Trash', 'parent_item_colon' =&gt; '', 'menu_name' =&gt; 'Products / Features' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'product', 'with_front' =&gt; false ), 'capability_type' =&gt; 'page', 'has_archive' =&gt; false, 'hierarchical' =&gt; true, 'menu_position' =&gt; 10, 'with_front' =&gt; false, 'menu_icon' =&gt; 'dashicons-chart-bar', 'supports' =&gt; array( 'title', 'editor', 'author', 'page-attributes' ) ); register_post_type( 'product', $args ); } add_action( 'init', 'base_types' ); // Rewrites function remove_slug( $post_link, $post, $leavename ) { if ( 'product' != $post-&gt;post_type || 'publish' != $post-&gt;post_status ) { return $post_link; } if( $post-&gt;post_parent ) { $parent = get_post($post-&gt;post_parent); $post_link = str_replace( '/' . $post-&gt;post_type . '/' . $parent-&gt;post_name . '/', '/' . $parent-&gt;post_name . '/', $post_link ); } else { $post_link = str_replace( '/' . $post-&gt;post_type . '/', '/', $post_link ); } return $post_link; } add_filter( 'post_type_link', 'remove_slug', 10, 3 ); function parse_request( $query ) { if ( ! $query-&gt;is_main_query() || 2 != count( $query-&gt;query ) || ! isset( $query-&gt;query['page'] ) ) { return; } if ( ! empty( $query-&gt;query['name'] ) ) { $query-&gt;set( 'post_type', array( 'post', 'product', 'page' ) ); } } add_action( 'pre_get_posts', 'parse_request' ); </code></pre> <p>First level pages work as expected. The child pages get the correct permalink, but they 404.</p> <p>Can anyone help or point in the right direction? Thank you.</p>
[ { "answer_id": 337262, "author": "Shohidur Rahman", "author_id": 163783, "author_profile": "https://wordpress.stackexchange.com/users/163783", "pm_score": -1, "selected": false, "text": "<p>Can you please try this php function <code>html_entity_decode(get_the_content());</code>. I have used this function on php to remove html tags, you can try this.</p>\n" }, { "answer_id": 367008, "author": "T Kly", "author_id": 188397, "author_profile": "https://wordpress.stackexchange.com/users/188397", "pm_score": -1, "selected": false, "text": "<p>You can try this:</p>\n\n<pre><code>&lt;textarea class=\"note-body-field\"&gt;&lt;?php echo sanitize_text_field(get_the_content()); ?&gt;\n&lt;/textarea&gt;\n</code></pre>\n\n<p>I'm also a beginner, but found this works in the frontend.\nAnd it seems to be intended for similar use cases - <a href=\"https://developer.wordpress.org/reference/functions/sanitize_text_field/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/sanitize_text_field/</a></p>\n" } ]
2019/05/07
[ "https://wordpress.stackexchange.com/questions/337331", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167570/" ]
I'd like my custom post type, products, to not use a slug, eg: domain.com/product-name. The code below sorts that out nicely, however it fails to work with child pages, eg: domain.com/product-name/product-name-feature, it 404s. I originally tried giving the custom post type the rewrite slug as '/', and while this was great for the custom post type, it killed normal pages (404). So if the solution is to use '/' and then fix normal pages, that's fine too. ``` // Post Type function base_types() { $labels = array( 'name' => 'Products & Features', 'singular_name' => 'Product', 'add_new' => 'Add New', 'add_new_item' => 'Add New Product / Feature', 'edit_item' => 'Edit Product', 'new_item' => 'New Product', 'all_items' => 'All', 'view_item' => 'View Product / Feature', 'search_items' => 'Search Product / Feature', 'not_found' => 'None found', 'not_found_in_trash' => 'None found in Trash', 'parent_item_colon' => '', 'menu_name' => 'Products / Features' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'product', 'with_front' => false ), 'capability_type' => 'page', 'has_archive' => false, 'hierarchical' => true, 'menu_position' => 10, 'with_front' => false, 'menu_icon' => 'dashicons-chart-bar', 'supports' => array( 'title', 'editor', 'author', 'page-attributes' ) ); register_post_type( 'product', $args ); } add_action( 'init', 'base_types' ); // Rewrites function remove_slug( $post_link, $post, $leavename ) { if ( 'product' != $post->post_type || 'publish' != $post->post_status ) { return $post_link; } if( $post->post_parent ) { $parent = get_post($post->post_parent); $post_link = str_replace( '/' . $post->post_type . '/' . $parent->post_name . '/', '/' . $parent->post_name . '/', $post_link ); } else { $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link ); } return $post_link; } add_filter( 'post_type_link', 'remove_slug', 10, 3 ); function parse_request( $query ) { if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) { return; } if ( ! empty( $query->query['name'] ) ) { $query->set( 'post_type', array( 'post', 'product', 'page' ) ); } } add_action( 'pre_get_posts', 'parse_request' ); ``` First level pages work as expected. The child pages get the correct permalink, but they 404. Can anyone help or point in the right direction? Thank you.
Can you please try this php function `html_entity_decode(get_the_content());`. I have used this function on php to remove html tags, you can try this.
337,348
<p>I am able to successfully use <code>wp.hooks.applyFilters()</code> and <code>wp.hooks.addFilter()</code>, but I'm not able to render a React Component using <code>wp.hooks.addAction()</code>. However, the <code>console.log()</code> runs just fine within the callback for an action. This is my code:</p> <pre><code>import { createHooks } from '@wordpress/hooks'; let globalHooks = createHooks(); const Header = () =&gt; { return ( &lt;h1&gt;Header Component&lt;/h1&gt; ); } const RevisedHeader = () =&gt; { return ( &lt;h1&gt;Revised Header Component&lt;/h1&gt; ) } export default class App extends Component { constructor( props ) { super(); globalHooks.addFilter( 'replace_header', 'revisedHeaderCallback', this.revisedHeaderCallback ); globalHooks.addAction( 'after_replace_header', 'afterRevisedHeaderCallback', this.afterRevisedHeaderCallback ); }; revisedHeaderCallback( header ) { return &lt;RevisedHeader /&gt;; } afterRevisedHeaderCallback() { return &lt;RevisedHeader /&gt;; } render() { return( &lt;div className="App"&gt; { globalHooks.applyFilters( 'replace_header', &lt;Header /&gt; ) } { globalHooks.doAction( 'after_replace_header' ) } &lt;/div&gt; ); } } </code></pre>
[ { "answer_id": 337349, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 4, "selected": true, "text": "<h2>How to use <code>wp.hooks.addAction</code>?</h2>\n<p>It's basically like so, just like you've attempted:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Hook to the hook_name action.\nwp.hooks.addAction( 'hook_name', 'namespace', function(){\n console.log( 'Foo Bar' );\n} );\n\n// Trigger the hook_name action.\nwp.hooks.doAction( 'hook_name' );\n</code></pre>\n<p>Or for hooks which provide one or more parameters to the callback:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Hook to the hook_name action.\nwp.hooks.addAction( 'hook_name', 'namespace', function( a, b ){\n console.log( a, b );\n} );\n\n// Trigger the hook_name action.\nwp.hooks.doAction( 'hook_name', 'foo', [ 'bar', 'boo' ] );\n</code></pre>\n<blockquote>\n<p>I am able to successfully use <code>wp.hooks.applyFilters()</code> and\n<code>wp.hooks.addFilter()</code>, but I'm not able to render a React Component\nusing <code>wp.hooks.addAction()</code>.</p>\n</blockquote>\n<p><strong>The problem is <em>not</em> with your code</strong>, but it's because unlike the <code>wp.hooks.applyFilters</code> function, <code>wp.hooks.doAction</code> <em>simply returns nothing</em> or it returns <code>undefined</code>:</p>\n<ul>\n<li><p>Here an element is returned and React later rendered the element:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ globalHooks.applyFilters( 'replace_header', &lt;Header /&gt; ) }\n</code></pre>\n<p>The above translates to this, which renders an element:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ &lt;RevisedHeader /&gt; }\n</code></pre>\n</li>\n<li><p>Here <code>undefined</code> is always returned, so no elements are rendered:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ globalHooks.doAction( 'after_replace_header' ) }\n{ globalHooks.doAction( 'after_replace_header', &lt;Header /&gt; ) }\n</code></pre>\n<p>The above translates to this, which &quot;does nothing good&quot;:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ undefined }\n</code></pre>\n</li>\n</ul>\n<p>So once again, the problem is that <code>wp.hooks.doAction</code> <em>always</em> returns an <code>undefined</code> even if for example your <code>afterRevisedHeaderCallback</code> function actually returns an element or component.</p>\n<p>Hence, use <code>globalHooks.applyFilters</code> (or rather <code>wp.hooks.applyFilters</code>) if you wish to render React elements/components like so:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ globalHooks.applyFilters( 'hook_name', &lt;FooBar /&gt; ) }\n</code></pre>\n<h2>UPDATE</h2>\n<blockquote>\n<p>then what purpose does doAction() serve? What would be the use\ncase?</p>\n</blockquote>\n<p>To do other actions than what you've tried to - <code>{ globalHooks.doAction( 'after_replace_header' ) }</code> (here you attempted to <em>render an element or a component</em>). So you could instead perform AJAX requests, modify an object (e.g. an <code>Array</code>), etc. You could also run <a href=\"https://reactjs.org/docs/react-dom.html#render\" rel=\"nofollow noreferrer\"><code>ReactDOM.render</code></a> from a callback hooked via <code>wp.hooks.addAction</code>, but (as you may already know) the element container has to be already attached to the DOM. But one thing <em>for sure</em>, <code>wp.hooks.doAction</code> always returns <code>undefined</code>.</p>\n<p><strong>Example for modifying an object</strong></p>\n<p>The callback (in your component):</p>\n<pre class=\"lang-js prettyprint-override\"><code>afterRevisedHeaderCallback( arr ) {\n arr.push( 'bar' );\n}\n</code></pre>\n<p>It's hooked here:</p>\n<pre class=\"lang-js prettyprint-override\"><code>globalHooks.addAction( 'after_replace_header', 'afterRevisedHeaderCallback', this.afterRevisedHeaderCallback );\n</code></pre>\n<p>Your component's <code>render</code> method:</p>\n<pre class=\"lang-js prettyprint-override\"><code>render() {\n let a = [ 'foo' ];\n globalHooks.doAction( 'after_replace_header', a );\n\n return(\n &lt;div className=&quot;App&quot;&gt;\n { globalHooks.applyFilters( 'replace_header', &lt;Header /&gt; ) }\n { a.join(', ') }\n &lt;/div&gt;\n );\n}\n</code></pre>\n<h2>UPDATE 2</h2>\n<p>Just like in PHP in WordPress, <code>do_action_ref_array</code> and <code>do_action</code> returns nothing/<code>NULL</code>, but <code>apply_filters_ref_array</code> and <code>apply_filters</code> both return whatever returned by the callback to a filter/hook, which yes, could be <code>NULL</code>.</p>\n<p>And if you're skeptical about the <code>undefined</code> returned by <code>wp.hooks.doAction</code>, then check out the source <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/hooks/src/createRunHook.js\" rel=\"nofollow noreferrer\">here</a>.</p>\n<h2>UPDATE 3</h2>\n<p>Based on the example in <strong>UPDATE</strong> above, you could actually render the element/component this way...</p>\n<p>The callback (in your component):</p>\n<pre class=\"lang-js prettyprint-override\"><code>afterRevisedHeaderCallback( arr ) {\n// arr = [ &lt;RevisedHeader /&gt; ]; // doesn't work\n arr[0] = &lt;RevisedHeader /&gt;; // works fine\n}\n</code></pre>\n<p>Your component's <code>render</code> method:</p>\n<pre class=\"lang-js prettyprint-override\"><code>render() {\n let el = [ &lt;Header /&gt; ];\n globalHooks.doAction( 'after_replace_header', el );\n\n return(\n &lt;div className=&quot;App&quot;&gt;\n { globalHooks.applyFilters( 'replace_header', &lt;Header /&gt; ) }\n { el }\n &lt;/div&gt;\n );\n}\n</code></pre>\n<p>I think you could understand the trick in that approach?</p>\n" }, { "answer_id": 358017, "author": "mujuonly", "author_id": 97483, "author_profile": "https://wordpress.stackexchange.com/users/97483", "pm_score": 0, "selected": false, "text": "<p>applyFilters in JS</p>\n\n<pre><code>(function( $ ) {\n 'use strict';\n $(function() {\n\n var cars = wp.hooks.applyFilters( 'carlist', [\"Saab\", \"Volvo\", \"BMW\"]);\n console.log(\"cars=======\"+cars);\n\n });\n})( jQuery );\n</code></pre>\n\n<p>Enqueue addFilter</p>\n\n<pre><code>function wpdocs_scripts_method() {\n $src = 'jQuery(document).ready(function($) { wp.hooks.addFilter( \"carlist\", \"carlist\", function(cars){ var cars = [\"Benz\"]; return cars; }); });';\n wp_add_inline_script( 'jquery', $src );\n\n}\nadd_action( 'admin_enqueue_scripts', 'wpdocs_scripts_method' );\n</code></pre>\n\n<p>Check console for the log</p>\n" } ]
2019/05/06
[ "https://wordpress.stackexchange.com/questions/337348", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67538/" ]
I am able to successfully use `wp.hooks.applyFilters()` and `wp.hooks.addFilter()`, but I'm not able to render a React Component using `wp.hooks.addAction()`. However, the `console.log()` runs just fine within the callback for an action. This is my code: ``` import { createHooks } from '@wordpress/hooks'; let globalHooks = createHooks(); const Header = () => { return ( <h1>Header Component</h1> ); } const RevisedHeader = () => { return ( <h1>Revised Header Component</h1> ) } export default class App extends Component { constructor( props ) { super(); globalHooks.addFilter( 'replace_header', 'revisedHeaderCallback', this.revisedHeaderCallback ); globalHooks.addAction( 'after_replace_header', 'afterRevisedHeaderCallback', this.afterRevisedHeaderCallback ); }; revisedHeaderCallback( header ) { return <RevisedHeader />; } afterRevisedHeaderCallback() { return <RevisedHeader />; } render() { return( <div className="App"> { globalHooks.applyFilters( 'replace_header', <Header /> ) } { globalHooks.doAction( 'after_replace_header' ) } </div> ); } } ```
How to use `wp.hooks.addAction`? -------------------------------- It's basically like so, just like you've attempted: ```js // Hook to the hook_name action. wp.hooks.addAction( 'hook_name', 'namespace', function(){ console.log( 'Foo Bar' ); } ); // Trigger the hook_name action. wp.hooks.doAction( 'hook_name' ); ``` Or for hooks which provide one or more parameters to the callback: ```js // Hook to the hook_name action. wp.hooks.addAction( 'hook_name', 'namespace', function( a, b ){ console.log( a, b ); } ); // Trigger the hook_name action. wp.hooks.doAction( 'hook_name', 'foo', [ 'bar', 'boo' ] ); ``` > > I am able to successfully use `wp.hooks.applyFilters()` and > `wp.hooks.addFilter()`, but I'm not able to render a React Component > using `wp.hooks.addAction()`. > > > **The problem is *not* with your code**, but it's because unlike the `wp.hooks.applyFilters` function, `wp.hooks.doAction` *simply returns nothing* or it returns `undefined`: * Here an element is returned and React later rendered the element: ```js { globalHooks.applyFilters( 'replace_header', <Header /> ) } ``` The above translates to this, which renders an element: ```js { <RevisedHeader /> } ``` * Here `undefined` is always returned, so no elements are rendered: ```js { globalHooks.doAction( 'after_replace_header' ) } { globalHooks.doAction( 'after_replace_header', <Header /> ) } ``` The above translates to this, which "does nothing good": ```js { undefined } ``` So once again, the problem is that `wp.hooks.doAction` *always* returns an `undefined` even if for example your `afterRevisedHeaderCallback` function actually returns an element or component. Hence, use `globalHooks.applyFilters` (or rather `wp.hooks.applyFilters`) if you wish to render React elements/components like so: ```js { globalHooks.applyFilters( 'hook_name', <FooBar /> ) } ``` UPDATE ------ > > then what purpose does doAction() serve? What would be the use > case? > > > To do other actions than what you've tried to - `{ globalHooks.doAction( 'after_replace_header' ) }` (here you attempted to *render an element or a component*). So you could instead perform AJAX requests, modify an object (e.g. an `Array`), etc. You could also run [`ReactDOM.render`](https://reactjs.org/docs/react-dom.html#render) from a callback hooked via `wp.hooks.addAction`, but (as you may already know) the element container has to be already attached to the DOM. But one thing *for sure*, `wp.hooks.doAction` always returns `undefined`. **Example for modifying an object** The callback (in your component): ```js afterRevisedHeaderCallback( arr ) { arr.push( 'bar' ); } ``` It's hooked here: ```js globalHooks.addAction( 'after_replace_header', 'afterRevisedHeaderCallback', this.afterRevisedHeaderCallback ); ``` Your component's `render` method: ```js render() { let a = [ 'foo' ]; globalHooks.doAction( 'after_replace_header', a ); return( <div className="App"> { globalHooks.applyFilters( 'replace_header', <Header /> ) } { a.join(', ') } </div> ); } ``` UPDATE 2 -------- Just like in PHP in WordPress, `do_action_ref_array` and `do_action` returns nothing/`NULL`, but `apply_filters_ref_array` and `apply_filters` both return whatever returned by the callback to a filter/hook, which yes, could be `NULL`. And if you're skeptical about the `undefined` returned by `wp.hooks.doAction`, then check out the source [here](https://github.com/WordPress/gutenberg/blob/master/packages/hooks/src/createRunHook.js). UPDATE 3 -------- Based on the example in **UPDATE** above, you could actually render the element/component this way... The callback (in your component): ```js afterRevisedHeaderCallback( arr ) { // arr = [ <RevisedHeader /> ]; // doesn't work arr[0] = <RevisedHeader />; // works fine } ``` Your component's `render` method: ```js render() { let el = [ <Header /> ]; globalHooks.doAction( 'after_replace_header', el ); return( <div className="App"> { globalHooks.applyFilters( 'replace_header', <Header /> ) } { el } </div> ); } ``` I think you could understand the trick in that approach?
337,353
<p>How can I fetch the post which is posted only this hour?</p> <p>Example: It's 9:00 am here I want to show all the post that is posted within 9:00am to 10am and it will check all the hours in same way.</p>
[ { "answer_id": 337349, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 4, "selected": true, "text": "<h2>How to use <code>wp.hooks.addAction</code>?</h2>\n<p>It's basically like so, just like you've attempted:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Hook to the hook_name action.\nwp.hooks.addAction( 'hook_name', 'namespace', function(){\n console.log( 'Foo Bar' );\n} );\n\n// Trigger the hook_name action.\nwp.hooks.doAction( 'hook_name' );\n</code></pre>\n<p>Or for hooks which provide one or more parameters to the callback:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Hook to the hook_name action.\nwp.hooks.addAction( 'hook_name', 'namespace', function( a, b ){\n console.log( a, b );\n} );\n\n// Trigger the hook_name action.\nwp.hooks.doAction( 'hook_name', 'foo', [ 'bar', 'boo' ] );\n</code></pre>\n<blockquote>\n<p>I am able to successfully use <code>wp.hooks.applyFilters()</code> and\n<code>wp.hooks.addFilter()</code>, but I'm not able to render a React Component\nusing <code>wp.hooks.addAction()</code>.</p>\n</blockquote>\n<p><strong>The problem is <em>not</em> with your code</strong>, but it's because unlike the <code>wp.hooks.applyFilters</code> function, <code>wp.hooks.doAction</code> <em>simply returns nothing</em> or it returns <code>undefined</code>:</p>\n<ul>\n<li><p>Here an element is returned and React later rendered the element:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ globalHooks.applyFilters( 'replace_header', &lt;Header /&gt; ) }\n</code></pre>\n<p>The above translates to this, which renders an element:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ &lt;RevisedHeader /&gt; }\n</code></pre>\n</li>\n<li><p>Here <code>undefined</code> is always returned, so no elements are rendered:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ globalHooks.doAction( 'after_replace_header' ) }\n{ globalHooks.doAction( 'after_replace_header', &lt;Header /&gt; ) }\n</code></pre>\n<p>The above translates to this, which &quot;does nothing good&quot;:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ undefined }\n</code></pre>\n</li>\n</ul>\n<p>So once again, the problem is that <code>wp.hooks.doAction</code> <em>always</em> returns an <code>undefined</code> even if for example your <code>afterRevisedHeaderCallback</code> function actually returns an element or component.</p>\n<p>Hence, use <code>globalHooks.applyFilters</code> (or rather <code>wp.hooks.applyFilters</code>) if you wish to render React elements/components like so:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ globalHooks.applyFilters( 'hook_name', &lt;FooBar /&gt; ) }\n</code></pre>\n<h2>UPDATE</h2>\n<blockquote>\n<p>then what purpose does doAction() serve? What would be the use\ncase?</p>\n</blockquote>\n<p>To do other actions than what you've tried to - <code>{ globalHooks.doAction( 'after_replace_header' ) }</code> (here you attempted to <em>render an element or a component</em>). So you could instead perform AJAX requests, modify an object (e.g. an <code>Array</code>), etc. You could also run <a href=\"https://reactjs.org/docs/react-dom.html#render\" rel=\"nofollow noreferrer\"><code>ReactDOM.render</code></a> from a callback hooked via <code>wp.hooks.addAction</code>, but (as you may already know) the element container has to be already attached to the DOM. But one thing <em>for sure</em>, <code>wp.hooks.doAction</code> always returns <code>undefined</code>.</p>\n<p><strong>Example for modifying an object</strong></p>\n<p>The callback (in your component):</p>\n<pre class=\"lang-js prettyprint-override\"><code>afterRevisedHeaderCallback( arr ) {\n arr.push( 'bar' );\n}\n</code></pre>\n<p>It's hooked here:</p>\n<pre class=\"lang-js prettyprint-override\"><code>globalHooks.addAction( 'after_replace_header', 'afterRevisedHeaderCallback', this.afterRevisedHeaderCallback );\n</code></pre>\n<p>Your component's <code>render</code> method:</p>\n<pre class=\"lang-js prettyprint-override\"><code>render() {\n let a = [ 'foo' ];\n globalHooks.doAction( 'after_replace_header', a );\n\n return(\n &lt;div className=&quot;App&quot;&gt;\n { globalHooks.applyFilters( 'replace_header', &lt;Header /&gt; ) }\n { a.join(', ') }\n &lt;/div&gt;\n );\n}\n</code></pre>\n<h2>UPDATE 2</h2>\n<p>Just like in PHP in WordPress, <code>do_action_ref_array</code> and <code>do_action</code> returns nothing/<code>NULL</code>, but <code>apply_filters_ref_array</code> and <code>apply_filters</code> both return whatever returned by the callback to a filter/hook, which yes, could be <code>NULL</code>.</p>\n<p>And if you're skeptical about the <code>undefined</code> returned by <code>wp.hooks.doAction</code>, then check out the source <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/hooks/src/createRunHook.js\" rel=\"nofollow noreferrer\">here</a>.</p>\n<h2>UPDATE 3</h2>\n<p>Based on the example in <strong>UPDATE</strong> above, you could actually render the element/component this way...</p>\n<p>The callback (in your component):</p>\n<pre class=\"lang-js prettyprint-override\"><code>afterRevisedHeaderCallback( arr ) {\n// arr = [ &lt;RevisedHeader /&gt; ]; // doesn't work\n arr[0] = &lt;RevisedHeader /&gt;; // works fine\n}\n</code></pre>\n<p>Your component's <code>render</code> method:</p>\n<pre class=\"lang-js prettyprint-override\"><code>render() {\n let el = [ &lt;Header /&gt; ];\n globalHooks.doAction( 'after_replace_header', el );\n\n return(\n &lt;div className=&quot;App&quot;&gt;\n { globalHooks.applyFilters( 'replace_header', &lt;Header /&gt; ) }\n { el }\n &lt;/div&gt;\n );\n}\n</code></pre>\n<p>I think you could understand the trick in that approach?</p>\n" }, { "answer_id": 358017, "author": "mujuonly", "author_id": 97483, "author_profile": "https://wordpress.stackexchange.com/users/97483", "pm_score": 0, "selected": false, "text": "<p>applyFilters in JS</p>\n\n<pre><code>(function( $ ) {\n 'use strict';\n $(function() {\n\n var cars = wp.hooks.applyFilters( 'carlist', [\"Saab\", \"Volvo\", \"BMW\"]);\n console.log(\"cars=======\"+cars);\n\n });\n})( jQuery );\n</code></pre>\n\n<p>Enqueue addFilter</p>\n\n<pre><code>function wpdocs_scripts_method() {\n $src = 'jQuery(document).ready(function($) { wp.hooks.addFilter( \"carlist\", \"carlist\", function(cars){ var cars = [\"Benz\"]; return cars; }); });';\n wp_add_inline_script( 'jquery', $src );\n\n}\nadd_action( 'admin_enqueue_scripts', 'wpdocs_scripts_method' );\n</code></pre>\n\n<p>Check console for the log</p>\n" } ]
2019/05/08
[ "https://wordpress.stackexchange.com/questions/337353", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/157754/" ]
How can I fetch the post which is posted only this hour? Example: It's 9:00 am here I want to show all the post that is posted within 9:00am to 10am and it will check all the hours in same way.
How to use `wp.hooks.addAction`? -------------------------------- It's basically like so, just like you've attempted: ```js // Hook to the hook_name action. wp.hooks.addAction( 'hook_name', 'namespace', function(){ console.log( 'Foo Bar' ); } ); // Trigger the hook_name action. wp.hooks.doAction( 'hook_name' ); ``` Or for hooks which provide one or more parameters to the callback: ```js // Hook to the hook_name action. wp.hooks.addAction( 'hook_name', 'namespace', function( a, b ){ console.log( a, b ); } ); // Trigger the hook_name action. wp.hooks.doAction( 'hook_name', 'foo', [ 'bar', 'boo' ] ); ``` > > I am able to successfully use `wp.hooks.applyFilters()` and > `wp.hooks.addFilter()`, but I'm not able to render a React Component > using `wp.hooks.addAction()`. > > > **The problem is *not* with your code**, but it's because unlike the `wp.hooks.applyFilters` function, `wp.hooks.doAction` *simply returns nothing* or it returns `undefined`: * Here an element is returned and React later rendered the element: ```js { globalHooks.applyFilters( 'replace_header', <Header /> ) } ``` The above translates to this, which renders an element: ```js { <RevisedHeader /> } ``` * Here `undefined` is always returned, so no elements are rendered: ```js { globalHooks.doAction( 'after_replace_header' ) } { globalHooks.doAction( 'after_replace_header', <Header /> ) } ``` The above translates to this, which "does nothing good": ```js { undefined } ``` So once again, the problem is that `wp.hooks.doAction` *always* returns an `undefined` even if for example your `afterRevisedHeaderCallback` function actually returns an element or component. Hence, use `globalHooks.applyFilters` (or rather `wp.hooks.applyFilters`) if you wish to render React elements/components like so: ```js { globalHooks.applyFilters( 'hook_name', <FooBar /> ) } ``` UPDATE ------ > > then what purpose does doAction() serve? What would be the use > case? > > > To do other actions than what you've tried to - `{ globalHooks.doAction( 'after_replace_header' ) }` (here you attempted to *render an element or a component*). So you could instead perform AJAX requests, modify an object (e.g. an `Array`), etc. You could also run [`ReactDOM.render`](https://reactjs.org/docs/react-dom.html#render) from a callback hooked via `wp.hooks.addAction`, but (as you may already know) the element container has to be already attached to the DOM. But one thing *for sure*, `wp.hooks.doAction` always returns `undefined`. **Example for modifying an object** The callback (in your component): ```js afterRevisedHeaderCallback( arr ) { arr.push( 'bar' ); } ``` It's hooked here: ```js globalHooks.addAction( 'after_replace_header', 'afterRevisedHeaderCallback', this.afterRevisedHeaderCallback ); ``` Your component's `render` method: ```js render() { let a = [ 'foo' ]; globalHooks.doAction( 'after_replace_header', a ); return( <div className="App"> { globalHooks.applyFilters( 'replace_header', <Header /> ) } { a.join(', ') } </div> ); } ``` UPDATE 2 -------- Just like in PHP in WordPress, `do_action_ref_array` and `do_action` returns nothing/`NULL`, but `apply_filters_ref_array` and `apply_filters` both return whatever returned by the callback to a filter/hook, which yes, could be `NULL`. And if you're skeptical about the `undefined` returned by `wp.hooks.doAction`, then check out the source [here](https://github.com/WordPress/gutenberg/blob/master/packages/hooks/src/createRunHook.js). UPDATE 3 -------- Based on the example in **UPDATE** above, you could actually render the element/component this way... The callback (in your component): ```js afterRevisedHeaderCallback( arr ) { // arr = [ <RevisedHeader /> ]; // doesn't work arr[0] = <RevisedHeader />; // works fine } ``` Your component's `render` method: ```js render() { let el = [ <Header /> ]; globalHooks.doAction( 'after_replace_header', el ); return( <div className="App"> { globalHooks.applyFilters( 'replace_header', <Header /> ) } { el } </div> ); } ``` I think you could understand the trick in that approach?
337,366
<p>Anyone know how can I change the comment reply text in wordpress to only reflect on specific pages only and not the whole site?</p> <p>For example the default text site-wide is “Leave a Reply”. But for some specific pages only, I want the text to read “Leave a Review”.</p> <p>Is there some code I could use in the comments.php file that would make this work?</p>
[ { "answer_id": 337367, "author": "Vishwa", "author_id": 120712, "author_profile": "https://wordpress.stackexchange.com/users/120712", "pm_score": 0, "selected": false, "text": "<p>In your page template, when you call comments template like this, <code>&lt;?php comment_form(); ?&gt;</code> it'll load default theme template. In the page template you need to change comment title, simply call comments template like below,</p>\n\n<pre><code>&lt;?php\n comment_form(array(\n 'title_reply' =&gt; __( 'Leave a Review' ),\n ));?&gt;\n</code></pre>\n" }, { "answer_id": 337368, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 1, "selected": false, "text": "<p>Code is not tested. But theoretically it should work:</p>\n\n<pre><code>add_filter('comment_form_defaults', 'wpse337366_comment_form_modification');\nfunction wpse337366_comment_form_modification($defaults)\n{\n // put your condition here\n if( is_page('my-page') || is_singular('my_post_type') )\n {\n $defaults['title_reply'] = __('Leave a Review');\n }\n return $defaults;\n}\n</code></pre>\n\n<p>You can place the code in a plugin or your theme's <code>functions.php</code>.</p>\n\n<p>The code will filter the default texts passed to the <code>comment_form()</code>.</p>\n\n<h3>Reference</h3>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/comment_form/\" rel=\"nofollow noreferrer\"><code>comment_form()</code> - WordPress Developer Resources</a></li>\n</ul>\n" } ]
2019/05/08
[ "https://wordpress.stackexchange.com/questions/337366", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167600/" ]
Anyone know how can I change the comment reply text in wordpress to only reflect on specific pages only and not the whole site? For example the default text site-wide is “Leave a Reply”. But for some specific pages only, I want the text to read “Leave a Review”. Is there some code I could use in the comments.php file that would make this work?
Code is not tested. But theoretically it should work: ``` add_filter('comment_form_defaults', 'wpse337366_comment_form_modification'); function wpse337366_comment_form_modification($defaults) { // put your condition here if( is_page('my-page') || is_singular('my_post_type') ) { $defaults['title_reply'] = __('Leave a Review'); } return $defaults; } ``` You can place the code in a plugin or your theme's `functions.php`. The code will filter the default texts passed to the `comment_form()`. ### Reference * [`comment_form()` - WordPress Developer Resources](https://developer.wordpress.org/reference/functions/comment_form/)
337,415
<p>I am using this plugin <a href="https://wordpress.org/plugins/content-protector/" rel="nofollow noreferrer">https://wordpress.org/plugins/content-protector/</a></p> <p>Enter the correct password to view the content↓</p> <pre><code>[passster password="123456"]content here[/passster] </code></pre> <p>adding to php↓</p> <pre><code>&lt;?php echo do_shortcode('[passster password="123456"]content here[/passster]'); ?&gt; </code></pre> <p>He can work</p> <p>But I need to hide the content that contains PHP↓</p> <pre><code>&lt;!--&lt;hide content&gt;--&gt; &lt;ul class="TPlayerNv"&gt; &lt;?php echo $optplayer; ?&gt; &lt;/ul&gt; &lt;div class="TPlayerCn BgA"&gt; &lt;div class="EcBgA" style="background-color:#EEEEEE!important;"&gt; &lt;div class="TPlayer"&gt; &lt;?php echo $player; ?&gt; &lt;span class="AAIco-lightbulb_outline lgtbx-lnk"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;span class="lgtbx"&gt;&lt;/span&gt; &lt;!--&lt;/hide content&gt;--&gt; </code></pre> <p>I am a newbie, he looks like this↓</p> <pre><code>&lt;?php echo do_shortcode('[passster password="123456"] &lt;!--&lt;hide content&gt;--&gt; &lt;ul class="TPlayerNv"&gt; &lt;?php echo $optplayer; ?&gt; &lt;/ul&gt; &lt;div class="TPlayerCn BgA"&gt; &lt;div class="EcBgA" style="background-color:#EEEEEE!important;"&gt; &lt;div class="TPlayer"&gt; &lt;?php echo $player; ?&gt; &lt;span class="AAIco-lightbulb_outline lgtbx-lnk"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;span class="lgtbx"&gt;&lt;/span&gt; &lt;!--&lt;/hide content&gt;--&gt; [/passster]'); ?&gt; </code></pre> <p>I know that this doesn't work</p> <p>help</p>
[ { "answer_id": 337371, "author": "Sanaullah Ahmad", "author_id": 141915, "author_profile": "https://wordpress.stackexchange.com/users/141915", "pm_score": -1, "selected": false, "text": "<p>I have the same Problem in Magento, the reason was Views was not added in Database. Once i added Products start showing in stock.</p>\n\n<p><a href=\"https://i.stack.imgur.com/9YBYX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9YBYX.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 337487, "author": "Akshay Rathod", "author_id": 167599, "author_profile": "https://wordpress.stackexchange.com/users/167599", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://github.com/woocommerce/woocommerce/pull/23665/files\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/pull/23665/files</a></p>\n\n<p>Refer above link to solve this error.</p>\n" } ]
2019/05/08
[ "https://wordpress.stackexchange.com/questions/337415", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167638/" ]
I am using this plugin <https://wordpress.org/plugins/content-protector/> Enter the correct password to view the content↓ ``` [passster password="123456"]content here[/passster] ``` adding to php↓ ``` <?php echo do_shortcode('[passster password="123456"]content here[/passster]'); ?> ``` He can work But I need to hide the content that contains PHP↓ ``` <!--<hide content>--> <ul class="TPlayerNv"> <?php echo $optplayer; ?> </ul> <div class="TPlayerCn BgA"> <div class="EcBgA" style="background-color:#EEEEEE!important;"> <div class="TPlayer"> <?php echo $player; ?> <span class="AAIco-lightbulb_outline lgtbx-lnk"></span> </div> </div> </div> <span class="lgtbx"></span> <!--</hide content>--> ``` I am a newbie, he looks like this↓ ``` <?php echo do_shortcode('[passster password="123456"] <!--<hide content>--> <ul class="TPlayerNv"> <?php echo $optplayer; ?> </ul> <div class="TPlayerCn BgA"> <div class="EcBgA" style="background-color:#EEEEEE!important;"> <div class="TPlayer"> <?php echo $player; ?> <span class="AAIco-lightbulb_outline lgtbx-lnk"></span> </div> </div> </div> <span class="lgtbx"></span> <!--</hide content>--> [/passster]'); ?> ``` I know that this doesn't work help
<https://github.com/woocommerce/woocommerce/pull/23665/files> Refer above link to solve this error.
337,421
<p>I am working on a php code as shown below:</p> <pre><code> &lt;div class="case-breaking__content"&gt; &lt;p&gt;&lt;?php echo the_title(); ?&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>The above php code returns the following content:</p> <pre><code>absv shss xcnx shss hshhs shhsw shshs hsnna hssnnss hssns snnss nnshs sjjjjsjsj nsnnnsns jjsnss snsnns nsnns </code></pre> <p>What I want is, after a particular word limit it should display ... Lets say after 8 words it should be like this;</p> <pre><code>absv shss xcnx shss hshhs shhsw shshs hsnna... </code></pre> <p>I tried in the following way but it doesn't seem to work:</p> <pre><code>&lt;div class="case-breaking__content"&gt; p&gt;&lt;?php $out = strlen(the_title()) &gt; 50 ? substr(the_title(),0,50)."..." : the_title(); ?&gt;&lt;/p&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 337423, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 1, "selected": false, "text": "<p>To trim by words you can use WordPress' <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/\" rel=\"nofollow noreferrer\"><code>wp_trim_words()</code></a>. Pass <code>get_the_title()</code> instead of the <code>the_title()</code> to prevent a duplicate <code>echo</code> statement.</p>\n\n<pre><code>&lt;?php echo wp_trim_words( get_the_title(), 8, '...' ); ?&gt;\n</code></pre>\n" }, { "answer_id": 337424, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> prints/retrieve the title while <a href=\"https://developer.wordpress.org/reference/functions/get_the_title/\" rel=\"nofollow noreferrer\"><code>get_the_title()</code></a> retrieve the title. </p>\n\n<p>So your code should be something like this.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n&lt;p&gt;\n &lt;?php\n $out = strlen(get_the_title()) &gt; 50 ? substr(get_the_title(),0,50).\"...\" : get_the_title(); \n echo $out;\n ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>Note</strong> you can use <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> but it is not recommended here to keep the code clean.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n&lt;p&gt;\n &lt;?php\n $out = strlen(the_title('', '', false)) &gt; 50 ? substr(the_title('', '', false),0,50).\"...\" : the_title('', '', false); \n echo $out;\n ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>The above code will place <code>...</code> after 50 <em>characters</em>, However if you want to place it after certain numbers of <em>words</em>, you should go for <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/\" rel=\"nofollow noreferrer\"><code>wp_trim_words()</code></a>.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n &lt;p&gt;\n &lt;?php echo wp_trim_words(get_the_title(), 8, '...'); ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>I hope this may help. </p>\n" } ]
2019/05/08
[ "https://wordpress.stackexchange.com/questions/337421", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143115/" ]
I am working on a php code as shown below: ``` <div class="case-breaking__content"> <p><?php echo the_title(); ?></p> </div> ``` The above php code returns the following content: ``` absv shss xcnx shss hshhs shhsw shshs hsnna hssnnss hssns snnss nnshs sjjjjsjsj nsnnnsns jjsnss snsnns nsnns ``` What I want is, after a particular word limit it should display ... Lets say after 8 words it should be like this; ``` absv shss xcnx shss hshhs shhsw shshs hsnna... ``` I tried in the following way but it doesn't seem to work: ``` <div class="case-breaking__content"> p><?php $out = strlen(the_title()) > 50 ? substr(the_title(),0,50)."..." : the_title(); ?></p> </div> ```
[`the_title()`](https://codex.wordpress.org/Function_Reference/the_title) prints/retrieve the title while [`get_the_title()`](https://developer.wordpress.org/reference/functions/get_the_title/) retrieve the title. So your code should be something like this. ``` <div class="case-breaking__content"> <p> <?php $out = strlen(get_the_title()) > 50 ? substr(get_the_title(),0,50)."..." : get_the_title(); echo $out; ?> </p> </div> ``` **Note** you can use [`the_title()`](https://codex.wordpress.org/Function_Reference/the_title) but it is not recommended here to keep the code clean. ``` <div class="case-breaking__content"> <p> <?php $out = strlen(the_title('', '', false)) > 50 ? substr(the_title('', '', false),0,50)."..." : the_title('', '', false); echo $out; ?> </p> </div> ``` The above code will place `...` after 50 *characters*, However if you want to place it after certain numbers of *words*, you should go for [`wp_trim_words()`](https://developer.wordpress.org/reference/functions/wp_trim_words/). ``` <div class="case-breaking__content"> <p> <?php echo wp_trim_words(get_the_title(), 8, '...'); ?> </p> </div> ``` I hope this may help.
337,437
<p>I am trying to export results to a csv file using the following code. The export appears to work, but when I open the file, it contains the html code from the page. Any help is appreciated.</p> <pre><code>ob_start(); global $wpdb; $domain = $_SERVER['SERVER_NAME']; $table = $wpdb-&gt;prefix . "qi_project_requests"; $filename = "export.csv"; $sql = $wpdb-&gt;get_results("select * from $table"); $header_row = array( 'Date Submitted', 'Requestor Name' ); $data_rows = array(); foreach ($sql as $data) { $row = array( $data-&gt;date, $data-&gt;rname ); $data_rows[] = $row; } $fh = @fopen( 'php://output', 'w' ); fprintf( $fh, chr(0xEF) . chr(0xBB) . chr(0xBF) ); header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' ); header( 'Content-Description: File Transfer' ); header( 'Content-type: text/csv' ); header( "Content-Disposition: attachment; filename=$filename" ); header( 'Expires: 0' ); header( 'Pragma: public' ); fputcsv( $fh, $header_row ); foreach ( $data_rows as $data_row ) { fputcsv( $fh, $data_row ); } fclose( $fh ); ob_end_flush(); die(); </code></pre>
[ { "answer_id": 337423, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 1, "selected": false, "text": "<p>To trim by words you can use WordPress' <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/\" rel=\"nofollow noreferrer\"><code>wp_trim_words()</code></a>. Pass <code>get_the_title()</code> instead of the <code>the_title()</code> to prevent a duplicate <code>echo</code> statement.</p>\n\n<pre><code>&lt;?php echo wp_trim_words( get_the_title(), 8, '...' ); ?&gt;\n</code></pre>\n" }, { "answer_id": 337424, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> prints/retrieve the title while <a href=\"https://developer.wordpress.org/reference/functions/get_the_title/\" rel=\"nofollow noreferrer\"><code>get_the_title()</code></a> retrieve the title. </p>\n\n<p>So your code should be something like this.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n&lt;p&gt;\n &lt;?php\n $out = strlen(get_the_title()) &gt; 50 ? substr(get_the_title(),0,50).\"...\" : get_the_title(); \n echo $out;\n ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>Note</strong> you can use <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> but it is not recommended here to keep the code clean.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n&lt;p&gt;\n &lt;?php\n $out = strlen(the_title('', '', false)) &gt; 50 ? substr(the_title('', '', false),0,50).\"...\" : the_title('', '', false); \n echo $out;\n ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>The above code will place <code>...</code> after 50 <em>characters</em>, However if you want to place it after certain numbers of <em>words</em>, you should go for <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/\" rel=\"nofollow noreferrer\"><code>wp_trim_words()</code></a>.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n &lt;p&gt;\n &lt;?php echo wp_trim_words(get_the_title(), 8, '...'); ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>I hope this may help. </p>\n" } ]
2019/05/08
[ "https://wordpress.stackexchange.com/questions/337437", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154429/" ]
I am trying to export results to a csv file using the following code. The export appears to work, but when I open the file, it contains the html code from the page. Any help is appreciated. ``` ob_start(); global $wpdb; $domain = $_SERVER['SERVER_NAME']; $table = $wpdb->prefix . "qi_project_requests"; $filename = "export.csv"; $sql = $wpdb->get_results("select * from $table"); $header_row = array( 'Date Submitted', 'Requestor Name' ); $data_rows = array(); foreach ($sql as $data) { $row = array( $data->date, $data->rname ); $data_rows[] = $row; } $fh = @fopen( 'php://output', 'w' ); fprintf( $fh, chr(0xEF) . chr(0xBB) . chr(0xBF) ); header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' ); header( 'Content-Description: File Transfer' ); header( 'Content-type: text/csv' ); header( "Content-Disposition: attachment; filename=$filename" ); header( 'Expires: 0' ); header( 'Pragma: public' ); fputcsv( $fh, $header_row ); foreach ( $data_rows as $data_row ) { fputcsv( $fh, $data_row ); } fclose( $fh ); ob_end_flush(); die(); ```
[`the_title()`](https://codex.wordpress.org/Function_Reference/the_title) prints/retrieve the title while [`get_the_title()`](https://developer.wordpress.org/reference/functions/get_the_title/) retrieve the title. So your code should be something like this. ``` <div class="case-breaking__content"> <p> <?php $out = strlen(get_the_title()) > 50 ? substr(get_the_title(),0,50)."..." : get_the_title(); echo $out; ?> </p> </div> ``` **Note** you can use [`the_title()`](https://codex.wordpress.org/Function_Reference/the_title) but it is not recommended here to keep the code clean. ``` <div class="case-breaking__content"> <p> <?php $out = strlen(the_title('', '', false)) > 50 ? substr(the_title('', '', false),0,50)."..." : the_title('', '', false); echo $out; ?> </p> </div> ``` The above code will place `...` after 50 *characters*, However if you want to place it after certain numbers of *words*, you should go for [`wp_trim_words()`](https://developer.wordpress.org/reference/functions/wp_trim_words/). ``` <div class="case-breaking__content"> <p> <?php echo wp_trim_words(get_the_title(), 8, '...'); ?> </p> </div> ``` I hope this may help.
337,438
<p>I need help looping through a simple php code. What I'm trying to achieve is the following:</p> <pre><code>Start Loop Look for all the posts Add the author first &amp; last name as a tag (links to /tag/firstName-lastName) Once clicked on the tag, take me to the author page with all their posts end loop </code></pre> <p>I'm writing all this in single.php (I'm aware it only effects the page I open and doesn't effect all the blogs) </p> <p>My Code so far;</p> <pre><code>&lt;?php $post_id = get_the_ID(); $queried_post = get_post($post_id); $user_info = get_userdata($post-&gt;the_author); $first = $user_info-&gt;last_name; wp_set_post_tags( $post_id, $first, true ); ?&gt; </code></pre>
[ { "answer_id": 337423, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 1, "selected": false, "text": "<p>To trim by words you can use WordPress' <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/\" rel=\"nofollow noreferrer\"><code>wp_trim_words()</code></a>. Pass <code>get_the_title()</code> instead of the <code>the_title()</code> to prevent a duplicate <code>echo</code> statement.</p>\n\n<pre><code>&lt;?php echo wp_trim_words( get_the_title(), 8, '...' ); ?&gt;\n</code></pre>\n" }, { "answer_id": 337424, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> prints/retrieve the title while <a href=\"https://developer.wordpress.org/reference/functions/get_the_title/\" rel=\"nofollow noreferrer\"><code>get_the_title()</code></a> retrieve the title. </p>\n\n<p>So your code should be something like this.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n&lt;p&gt;\n &lt;?php\n $out = strlen(get_the_title()) &gt; 50 ? substr(get_the_title(),0,50).\"...\" : get_the_title(); \n echo $out;\n ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>Note</strong> you can use <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> but it is not recommended here to keep the code clean.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n&lt;p&gt;\n &lt;?php\n $out = strlen(the_title('', '', false)) &gt; 50 ? substr(the_title('', '', false),0,50).\"...\" : the_title('', '', false); \n echo $out;\n ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>The above code will place <code>...</code> after 50 <em>characters</em>, However if you want to place it after certain numbers of <em>words</em>, you should go for <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/\" rel=\"nofollow noreferrer\"><code>wp_trim_words()</code></a>.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n &lt;p&gt;\n &lt;?php echo wp_trim_words(get_the_title(), 8, '...'); ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>I hope this may help. </p>\n" } ]
2019/05/08
[ "https://wordpress.stackexchange.com/questions/337438", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167652/" ]
I need help looping through a simple php code. What I'm trying to achieve is the following: ``` Start Loop Look for all the posts Add the author first & last name as a tag (links to /tag/firstName-lastName) Once clicked on the tag, take me to the author page with all their posts end loop ``` I'm writing all this in single.php (I'm aware it only effects the page I open and doesn't effect all the blogs) My Code so far; ``` <?php $post_id = get_the_ID(); $queried_post = get_post($post_id); $user_info = get_userdata($post->the_author); $first = $user_info->last_name; wp_set_post_tags( $post_id, $first, true ); ?> ```
[`the_title()`](https://codex.wordpress.org/Function_Reference/the_title) prints/retrieve the title while [`get_the_title()`](https://developer.wordpress.org/reference/functions/get_the_title/) retrieve the title. So your code should be something like this. ``` <div class="case-breaking__content"> <p> <?php $out = strlen(get_the_title()) > 50 ? substr(get_the_title(),0,50)."..." : get_the_title(); echo $out; ?> </p> </div> ``` **Note** you can use [`the_title()`](https://codex.wordpress.org/Function_Reference/the_title) but it is not recommended here to keep the code clean. ``` <div class="case-breaking__content"> <p> <?php $out = strlen(the_title('', '', false)) > 50 ? substr(the_title('', '', false),0,50)."..." : the_title('', '', false); echo $out; ?> </p> </div> ``` The above code will place `...` after 50 *characters*, However if you want to place it after certain numbers of *words*, you should go for [`wp_trim_words()`](https://developer.wordpress.org/reference/functions/wp_trim_words/). ``` <div class="case-breaking__content"> <p> <?php echo wp_trim_words(get_the_title(), 8, '...'); ?> </p> </div> ``` I hope this may help.
337,455
<p>I'm Looking for a way to create the grid as on the pictures. A 12 columns based layout with a simple way to add text, images, video etc. etc. Tried the <strong>Bootstrap way</strong> without success. I’m up for everything. Anyone? </p> <p><img src="https://i.stack.imgur.com/P84Gd.png" alt="enter image description here"><img src="https://i.stack.imgur.com/LsbFv.png" alt="enter image description here"></p>
[ { "answer_id": 337423, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 1, "selected": false, "text": "<p>To trim by words you can use WordPress' <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/\" rel=\"nofollow noreferrer\"><code>wp_trim_words()</code></a>. Pass <code>get_the_title()</code> instead of the <code>the_title()</code> to prevent a duplicate <code>echo</code> statement.</p>\n\n<pre><code>&lt;?php echo wp_trim_words( get_the_title(), 8, '...' ); ?&gt;\n</code></pre>\n" }, { "answer_id": 337424, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> prints/retrieve the title while <a href=\"https://developer.wordpress.org/reference/functions/get_the_title/\" rel=\"nofollow noreferrer\"><code>get_the_title()</code></a> retrieve the title. </p>\n\n<p>So your code should be something like this.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n&lt;p&gt;\n &lt;?php\n $out = strlen(get_the_title()) &gt; 50 ? substr(get_the_title(),0,50).\"...\" : get_the_title(); \n echo $out;\n ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>Note</strong> you can use <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> but it is not recommended here to keep the code clean.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n&lt;p&gt;\n &lt;?php\n $out = strlen(the_title('', '', false)) &gt; 50 ? substr(the_title('', '', false),0,50).\"...\" : the_title('', '', false); \n echo $out;\n ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>The above code will place <code>...</code> after 50 <em>characters</em>, However if you want to place it after certain numbers of <em>words</em>, you should go for <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/\" rel=\"nofollow noreferrer\"><code>wp_trim_words()</code></a>.</p>\n\n<pre><code>&lt;div class=\"case-breaking__content\"&gt;\n &lt;p&gt;\n &lt;?php echo wp_trim_words(get_the_title(), 8, '...'); ?&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>I hope this may help. </p>\n" } ]
2019/05/09
[ "https://wordpress.stackexchange.com/questions/337455", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167663/" ]
I'm Looking for a way to create the grid as on the pictures. A 12 columns based layout with a simple way to add text, images, video etc. etc. Tried the **Bootstrap way** without success. I’m up for everything. Anyone? ![enter image description here](https://i.stack.imgur.com/P84Gd.png)![enter image description here](https://i.stack.imgur.com/LsbFv.png)
[`the_title()`](https://codex.wordpress.org/Function_Reference/the_title) prints/retrieve the title while [`get_the_title()`](https://developer.wordpress.org/reference/functions/get_the_title/) retrieve the title. So your code should be something like this. ``` <div class="case-breaking__content"> <p> <?php $out = strlen(get_the_title()) > 50 ? substr(get_the_title(),0,50)."..." : get_the_title(); echo $out; ?> </p> </div> ``` **Note** you can use [`the_title()`](https://codex.wordpress.org/Function_Reference/the_title) but it is not recommended here to keep the code clean. ``` <div class="case-breaking__content"> <p> <?php $out = strlen(the_title('', '', false)) > 50 ? substr(the_title('', '', false),0,50)."..." : the_title('', '', false); echo $out; ?> </p> </div> ``` The above code will place `...` after 50 *characters*, However if you want to place it after certain numbers of *words*, you should go for [`wp_trim_words()`](https://developer.wordpress.org/reference/functions/wp_trim_words/). ``` <div class="case-breaking__content"> <p> <?php echo wp_trim_words(get_the_title(), 8, '...'); ?> </p> </div> ``` I hope this may help.
337,469
<p>I am looking for any built in function that when I add a user or a user wants to register, the username will be automatically prepended with a predefined text.</p> <p>For example, if the user registers with <code>abul</code>, the username will be saved as <code>tk_abul</code>.</p>
[ { "answer_id": 337473, "author": "Nilambar Sharma", "author_id": 27998, "author_profile": "https://wordpress.stackexchange.com/users/27998", "pm_score": 1, "selected": false, "text": "<p>You can use <code>pre_user_login</code> filter to customize username when registered. Example.</p>\n\n<pre><code>add_filter( 'pre_user_login', 'wpse_customize_user' );\n\nfunction wpse_customize_user( $username ) {\n return 'tk_' . $username;\n}\n</code></pre>\n" }, { "answer_id": 337474, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 0, "selected": false, "text": "<p>Try <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/user_register\" rel=\"nofollow noreferrer\"><code>user_register</code></a> hook. The following code wasn't tested.</p>\n\n<pre><code>&lt;?php\nadd_action( 'user_register', 'my_nickname_prepend_function' );\n\nfunction my_nickname_prepend_function( $user_id )\n{\n if ( isset( $_POST['user_login'] ) )\n update_user_meta( $user_id, 'nickname', 'tk_' . $_POST['user_login'] );\n }\n}\n</code></pre>\n\n<p>Remember about user input validation.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">Action Reference</a> is at your service.</p>\n" } ]
2019/05/09
[ "https://wordpress.stackexchange.com/questions/337469", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118077/" ]
I am looking for any built in function that when I add a user or a user wants to register, the username will be automatically prepended with a predefined text. For example, if the user registers with `abul`, the username will be saved as `tk_abul`.
You can use `pre_user_login` filter to customize username when registered. Example. ``` add_filter( 'pre_user_login', 'wpse_customize_user' ); function wpse_customize_user( $username ) { return 'tk_' . $username; } ```
337,508
<p>I have created a plug-in which permits to create a category with slugs.</p> <p>There is the code :</p> <pre><code>wp_insert_term( 'Cat1', 'category', array( 'slug' =&gt; 'slug-cat1', )); wp_insert_term( 'Agenda', 'category', array( 'slug' =&gt; 'slug-agenda', 'parent'=&gt; term_exists( 'Cat1', 'category' )['term_id'] )); </code></pre> <p>It permits to create my category in the default language of the website. So my question is, do you know how can i create a category as before, but i want to create it in another language than the default. I'm using Polylang to translate my website.</p> <p>Have a good day.</p>
[ { "answer_id": 337512, "author": "user3135691", "author_id": 59755, "author_profile": "https://wordpress.stackexchange.com/users/59755", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, you need to buy the pro-version of Polylang. This is a feature, which the pro-version of the plugin provides for custom post types.</p>\n\n<p>That is one of the tricks, which make people buy the pro-version.</p>\n\n<p>I think Polylang pro-version starts at 99,- € (depending on your needs).</p>\n\n<p>In comparison: WPML has the same features (and more) with only 79,- € I think.\nI have recently encountered the same problem and the cheapeast solution, was to buy the pro of WPML.</p>\n\n<p>I know the answer might be not satisfying, but that's how it currently is.</p>\n" }, { "answer_id": 343116, "author": "Daniel", "author_id": 172051, "author_profile": "https://wordpress.stackexchange.com/users/172051", "pm_score": 2, "selected": false, "text": "<p>You can actually make it this way:</p>\n\n<pre><code>$cat1 = wp_insert_term(\n 'Cat1',\n 'category',\n ['slug' =&gt; 'slug-cat1'],\n);\n\n$agenda = wp_insert_term(\n 'Agenda',\n 'category',\n [\n 'slug' =&gt; 'slug-agenda',\n 'parent'=&gt; term_exists( 'Cat1', 'category' )['term_id'],\n ],\n);\n\npll_set_term_language($cat1['term_id'], 'fr');\npll_set_term_language($agenda['term_id'], 'de');\n</code></pre>\n\n<p>Here is link to Polylang Function reference:\n<a href=\"https://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/\" rel=\"nofollow noreferrer\">https://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/</a></p>\n" } ]
2019/05/09
[ "https://wordpress.stackexchange.com/questions/337508", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/144944/" ]
I have created a plug-in which permits to create a category with slugs. There is the code : ``` wp_insert_term( 'Cat1', 'category', array( 'slug' => 'slug-cat1', )); wp_insert_term( 'Agenda', 'category', array( 'slug' => 'slug-agenda', 'parent'=> term_exists( 'Cat1', 'category' )['term_id'] )); ``` It permits to create my category in the default language of the website. So my question is, do you know how can i create a category as before, but i want to create it in another language than the default. I'm using Polylang to translate my website. Have a good day.
You can actually make it this way: ``` $cat1 = wp_insert_term( 'Cat1', 'category', ['slug' => 'slug-cat1'], ); $agenda = wp_insert_term( 'Agenda', 'category', [ 'slug' => 'slug-agenda', 'parent'=> term_exists( 'Cat1', 'category' )['term_id'], ], ); pll_set_term_language($cat1['term_id'], 'fr'); pll_set_term_language($agenda['term_id'], 'de'); ``` Here is link to Polylang Function reference: <https://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/>
337,516
<p>I want to return information about a blog. It could be, author name, title, date, country whatever just to test.</p> <pre><code>&lt;?php $post_id = get_the_ID(); while ($post_id != 0) { $queried_post = get_post($post_id); $author_id = $queried_post-&gt;post_author; echo get_the_author_meta('display_name',$author_id); $post_id++; } ?&gt; </code></pre> <p>In the following code, I'm trying to get all the author's name between post_id 20 to 25. When the code is run, it only displays: </p> <pre><code>The author is: The author is: The author is: The author is: The author is: The author is: </code></pre> <p>Can you tell me how i would fix it so that it would return any kind of information about the blog (in this case, the name of the author).</p> <p><strong>THE UPDATED CODE DOESN'T DISPLAY ANYTHING.</strong></p>
[ { "answer_id": 337518, "author": "J.Bigham", "author_id": 95150, "author_profile": "https://wordpress.stackexchange.com/users/95150", "pm_score": 0, "selected": false, "text": "<p>You will want to get the author name inside the loop. Once your inside the loop you will be dealing with one post at a time, then you can access any post info you need.\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Post\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Post</a></p>\n\n<p>**Qaisar has it right for your while loop. Inside the loop you have to get the post. \n $queried_post = get_post($post_id); \nthen you can get the author...</p>\n\n<p>UPDATED AGAIN</p>\n\n<pre><code>&lt;?php\n\n $args = [\n 'post__in' =&gt; range( 20, 25 ), //**get post in your range**\n ];\n $queried_posts= get_posts( $args ); // **now you have the post you want**\n\n foreach( $queried_posts as $queried_post ) { // **loop through**\n $author_id = $queried_post-&gt;post_author;\n echo get_the_author_meta('display_name', $author_id) .'&lt;/br&gt;';\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 337524, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 2, "selected": true, "text": "<p>You need to re-arrange your code.</p>\n\n<pre><code>&lt;?php \n $post_id = 20;\n\n while($post_id &lt;= 25) {\n $queried_post = get_post($post_id); \n\n $author_id = $queried_post-&gt;post_author;\n echo get_the_author_meta('display_name', $author_id);\n\n\n $post_id++;\n } \n?&gt;\n</code></pre>\n\n<p>Within <code>while</code> loop above you have <code>$queried_post</code> which is an object of class <a href=\"https://codex.wordpress.org/Class_Reference/WP_Post\" rel=\"nofollow noreferrer\"><code>WP_Post</code></a>. <a href=\"https://codex.wordpress.org/Class_Reference/WP_Post#Member_Variables_of_WP_Post\" rel=\"nofollow noreferrer\">Member Variables of WP_Post</a> can be used to display data about each post. </p>\n\n<p>I hope this may help.</p>\n\n<p><strong>UPDATE</strong> </p>\n\n<blockquote>\n <p>what if i want to the loop to apply to all of the post that there are on the site. What would be the changes i would need to make in order for me to apply to all the posts?</p>\n</blockquote>\n\n<p>In that case you may code like that using <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> which returns an array of <a href=\"https://codex.wordpress.org/Class_Reference/WP_Post\" rel=\"nofollow noreferrer\"></a> objects</p>\n\n<pre><code>&lt;?php \n $arg = array( 'numberposts' =&gt; -1 ); // get all posts\n\n $queried_posts = get_posts( $arg);\n\n // Now loop through $queried_posts\n foreach( $queried_posts as $queried_post ) {\n\n $author_id = $queried_post-&gt;post_author;\n echo get_the_author_meta('display_name', $author_id);\n\n } \n ?&gt;\n</code></pre>\n" } ]
2019/05/09
[ "https://wordpress.stackexchange.com/questions/337516", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167693/" ]
I want to return information about a blog. It could be, author name, title, date, country whatever just to test. ``` <?php $post_id = get_the_ID(); while ($post_id != 0) { $queried_post = get_post($post_id); $author_id = $queried_post->post_author; echo get_the_author_meta('display_name',$author_id); $post_id++; } ?> ``` In the following code, I'm trying to get all the author's name between post\_id 20 to 25. When the code is run, it only displays: ``` The author is: The author is: The author is: The author is: The author is: The author is: ``` Can you tell me how i would fix it so that it would return any kind of information about the blog (in this case, the name of the author). **THE UPDATED CODE DOESN'T DISPLAY ANYTHING.**
You need to re-arrange your code. ``` <?php $post_id = 20; while($post_id <= 25) { $queried_post = get_post($post_id); $author_id = $queried_post->post_author; echo get_the_author_meta('display_name', $author_id); $post_id++; } ?> ``` Within `while` loop above you have `$queried_post` which is an object of class [`WP_Post`](https://codex.wordpress.org/Class_Reference/WP_Post). [Member Variables of WP\_Post](https://codex.wordpress.org/Class_Reference/WP_Post#Member_Variables_of_WP_Post) can be used to display data about each post. I hope this may help. **UPDATE** > > what if i want to the loop to apply to all of the post that there are on the site. What would be the changes i would need to make in order for me to apply to all the posts? > > > In that case you may code like that using [`get_posts()`](https://developer.wordpress.org/reference/functions/get_posts/) which returns an array of objects ``` <?php $arg = array( 'numberposts' => -1 ); // get all posts $queried_posts = get_posts( $arg); // Now loop through $queried_posts foreach( $queried_posts as $queried_post ) { $author_id = $queried_post->post_author; echo get_the_author_meta('display_name', $author_id); } ?> ```
337,525
<p>be gentle, I'm pretty new (just over from Joomla).</p> <p>This is part of an array...</p> <pre><code>echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $item_1_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_url( wp_get_attachment_url($row['item_code1']) ) . '&lt;/td&gt;&lt;/tr&gt;'; </code></pre> <p>It works fine, but at the front end, the output is plain text. I can't seem to figure out how to render an encoded URL (clickable link).</p> <p>Should I be using get_attachment_link or 'image source'?</p> <p>Any help would be gratefully received.</p> <p>Thanks</p> <p>Mark</p> <p>.........</p> <p>Complete php (pertinent lines; 203, 403, 463)</p> <pre><code>&lt;?php </code></pre> <p>if ( ! defined( 'ABSPATH' ) ) { exit; }</p> <p>/** * Class WC_LD_Code_Assignment * * assign codes when user pruchase a product */ class WC_LD_Code_Assignment {</p> <pre><code>public function setup() { // assign codes on processing or complete order status $delivery_order_status = get_option( 'wc_ld_delivery_order_status' ); $order_status = ( empty( $delivery_order_status ) ? 'completed' : $delivery_order_status ); add_action( 'woocommerce_order_status_' . $order_status, array( $this, 'assign_license_codes_to_order' ), 10, 1 ); add_action( 'woocommerce_order_item_meta_start', array( $this, 'display_license_codes_in_user_account' ), 10, 3 ); add_action( 'woocommerce_email_after_order_table', array( $this, 'email_after_order_table' ), 100, 4 ); add_filter( "woocommerce_can_reduce_order_stock", array( $this, 'dont_reduce_order_stock' ), 10, 2 ); add_action( 'woocommerce_order_status_changed', array( $this, 'manage_stock_for_simple_products' ), 100, 3 ); } /** * * As we disabled auto stock reduction for all product * here, we reduce order manually for simple products * * @param $order_id * @param $old_status * @param $new_status * * @return bool */ public function manage_stock_for_simple_products( $order_id, $old_status, $new_status ) { if ( is_object( $order_id ) ) { $order_id = $order_id-&gt;id; } // if order stock already reduced if ( get_post_meta( $order_id, '_order_stock_reduced', true ) ) { return false; } if ( $new_status == 'processing' || $new_status == 'completed' ) { // get the order details $order = new WC_Order( $order_id ); $order_items = $order-&gt;get_items(); $reduced = false; foreach ( $order_items as $item ) { $qty = $item['qty']; if ( $item['product_id'] &gt; 0 ) { $is_license_code = get_post_meta( $item['product_id'], '_wc_ld_license_code', true ); if ( empty( $is_license_code ) || $is_license_code == 'no' ) { $_product = $order-&gt;get_product_from_item( $item ); if ( $_product &amp;&amp; $_product-&gt;exists() &amp;&amp; $_product-&gt;managing_stock() ) { if(version_compare( WC_VERSION, '3.0.0', '&gt;' )){ $new_stock = wc_update_product_stock($item['product_id'], $qty, 'decrease' ); } else{ $new_stock = $_product-&gt;reduce_stock( $qty ); } $item_name = $_product-&gt;get_sku() ? $_product-&gt;get_sku() : $item['product_id']; if ( isset( $item['variation_id'] ) &amp;&amp; $item['variation_id'] ) { $order-&gt;add_order_note( sprintf( __( 'Item %s variation #%s stock reduced from %s to %s.', 'highthemes' ), $item_name, $item['variation_id'], $new_stock + $qty, $new_stock ) ); } else { $order-&gt;add_order_note( sprintf( __( 'Item %s stock reduced from %s to %s.', 'highthemes' ), $item_name, $new_stock + $qty, $new_stock ) ); } if(version_compare( WC_VERSION, '3.0.0', '&gt;' )){ } else{ $order-&gt;send_stock_notifications( $_product, $new_stock, $item['qty'] ); } $reduced = true; } } } } if ( $reduced ) { add_post_meta( $order_id, '_order_stock_reduced', '1', true ); } } } /** * @return bool * * prevent payment proccessing addons to reduce stock. It is done with this plugin */ public function dont_reduce_order_stock( $current_value, $order ) { return false; } /** * @param $order * @param $sent_to_admin * @param $plain_text * @param $email * * included the license codes in the order email sent to the user */ public function email_after_order_table( $order, $sent_to_admin, $plain_text, $email ) { if ( is_object( $order ) ) { $delivery_order_status = get_option( 'wc_ld_delivery_order_status' ); $order_id = $order-&gt;get_id(); $order_status = ( empty( $delivery_order_status ) ? 'completed' : $delivery_order_status ); if ( $order-&gt;get_status() == $order_status ) { echo $this-&gt;get_assigned_codes( $order_id ); } } } /** * @param $order_id * * get the assigned codes to an order * * @return string|void */ public function get_assigned_codes( $order_id ) { if ( is_object( $order_id ) ) { $order_id = $order_id-&gt;id; } // get the order details $order = new WC_Order( $order_id ); // check order items to get quantity and product id $order_items = $order-&gt;get_items(); $codes_table = ''; foreach ( $order_items as $key =&gt; $value ) { if ( ! isset( $value['license_code_ids'] ) ) { continue; } $license_code_ids = is_array($value['license_code_ids']) ? $value['license_code_ids']: unserialize( $value['license_code_ids'] ); if ( empty( $license_code_ids ) ) { return; } $product_id = (isset($value['variation_id']) &amp;&amp; !empty($value['variation_id'])) ? $value['variation_id'] : $value['product_id']; $rows = WC_LD_Model::get_codes_by_id( implode( ",", $license_code_ids ) ); $code_1_title = WC_LD_Model::get_code_title( 1, $product_id ); $code_2_title = WC_LD_Model::get_code_title( 2, $product_id ); $code_3_title = WC_LD_Model::get_code_title( 3, $product_id ); $code_4_title = WC_LD_Model::get_code_title( 4, $product_id ); $code_5_title = WC_LD_Model::get_code_title( 5, $product_id ); $description = get_post_meta( $value['product_id'], '_wc_ld_product_code_description', true ); $codes_table .= '&lt;h3&gt;' . $value['name'] . '&lt;/h3&gt;'; $codes_table .= '&lt;div style="padding-bottom:20px;"&gt;' . $description . '&lt;/div&gt;'; foreach ( $rows as $row ) { $codes_table .= '&lt;table class="td" cellspacing="0" cellpadding="6" style="margin-bottom:20px;width: 100%; font-family: \'Helvetica Neue\', Helvetica, Roboto, Arial, sans-serif;" border="1"&gt;'; $codes_table .= ' &lt;tbody&gt;'; if ( ! empty( $row['license_code1'] ) ) { $codes_table .= '&lt;tr&gt;&lt;th class="td" scope="col" style="text-align:left;width:40%; background-color:#eeeeee;"&gt;' . esc_html( $code_1_title ) . '&lt;/th&gt;&lt;td class="td" scope="col" style="text-align:left;"&gt;' . esc_html( $row['license_code1'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code2'] ) ) { $codes_table .= '&lt;tr&gt;&lt;th class="td" scope="col" style="text-align:left;"&gt;' . esc_html( $code_2_title ) . '&lt;/th&gt;&lt;td class="td" scope="col" style="text-align:left;"&gt;' . esc_html( $row['license_code2'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code3'] ) ) { $codes_table .= '&lt;tr&gt;&lt;th class="td" scope="col" style="text-align:left;"&gt;' . esc_html( $code_3_title ) . '&lt;/th&gt;&lt;td class="td" scope="col" style="text-align:left;"&gt;' . esc_html( $row['license_code3'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code4'] ) ) { $codes_table .= '&lt;tr&gt;&lt;th class="td" scope="col" style="text-align:left;"&gt;' . esc_html( $code_4_title ) . '&lt;/th&gt;&lt;td class="td" scope="col" style="text-align:left;"&gt;' . esc_html( $row['license_code4'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code5'] ) ) { $codes_table .= '&lt;tr&gt;&lt;th class="td" scope="col" style="text-align:left;"&gt;' . esc_url( wp_get_attachment_url($code_5_title) ) . '&lt;/th&gt;&lt;td class="td" scope="col" style="text-align:left;"&gt;' . esc_html( $row['license_code5'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } $codes_table .= '&lt;/tbody&gt;&lt;/table&gt;'; } } return $codes_table; } /** * @param $order_id * * do the license code assignment to order */ public function assign_license_codes_to_order( $order_id ) { global $wpdb; if ( is_object( $order_id ) ) { $order_id = $order_id-&gt;id; } // get the order details $order = new WC_Order( $order_id ); // check order items to get quantity and product id $order_items = $order-&gt;get_items(); // assign license codes to order items foreach ( $order_items as $item_id =&gt; $item ) { // if there is no code assigned to this order item if ( empty( $item['license_code_ids'] ) ) { // if product has marked as license code product $is_license_code = get_post_meta( $item['product_id'], '_wc_ld_license_code', true ); if ( empty( $is_license_code ) || $is_license_code == 'no' ) { continue; } $this-&gt;assign_license_to_item( $item_id, $item, $order, $order_id ); } } } /** * @param $item_id * @param $item * @param $order * @param $order_id * * does the license assignment for each order item */ public function assign_license_to_item( $item_id, $item, $order, $order_id ) { global $wpdb; $product_id = (isset($item['variation_id']) &amp;&amp; !empty($item['variation_id'])) ? $item['variation_id'] : $item['product_id']; $qty = $item['qty']; // get license codes from databse based on requested qty $rows = $wpdb-&gt;get_results( "SELECT * FROM {$wpdb-&gt;wc_ld_license_codes} WHERE product_id = $product_id AND license_code1 &lt;&gt; '' AND license_status = '0' LIMIT $qty" ); // build an array of license code ids foreach ( $rows as $query ) { $license_code_ids[] = $query-&gt;id; } // only assign license codes if we have the requested quantity of the item if ( count( $license_code_ids ) == $qty ) { // save the order id in license codes table $this-&gt;assign_order_id_to_license_codes( $order_id, $license_code_ids ); // save the assigned license codes in order item meta wc_add_order_item_meta( $item_id, '_license_code_ids', $license_code_ids ); // change sold license codes status to sold WC_LD_Model::change_license_codes_status( implode( $license_code_ids, ',' ), '1' ); // reduce stock $_product = $order-&gt;get_product_from_item( $item ); if ( $_product &amp;&amp; $_product-&gt;exists() &amp;&amp; $_product-&gt;managing_stock() ) { if(version_compare( WC_VERSION, '3.0.0', '&gt;' ) ){ $new_stock = wc_update_product_stock($product_id , $qty, 'decrease' ); update_post_meta( $order_id, '_order_stock_reduced', '1', true ); } else{ $new_stock = $_product-&gt;reduce_stock( $qty ); update_post_meta( $order_id, '_order_stock_reduced', '1', true ); } $item_name = $_product-&gt;get_sku() ? $_product-&gt;get_sku() : $item['product_id']; if ( isset( $item['variation_id'] ) &amp;&amp; $item['variation_id'] ) { $order-&gt;add_order_note( sprintf( __( 'Item %s variation #%s stock reduced from %s to %s.', 'highthemes' ), $item_name, $item['variation_id'], $new_stock + $qty, $new_stock ) ); } else { $order-&gt;add_order_note( sprintf( __( 'Item %s stock reduced from %s to %s.', 'highthemes' ), $item_name, $new_stock + $qty, $new_stock ) ); } if(version_compare( WC_VERSION, '3.0.0', '&gt;' )){ } else{ $order-&gt;send_stock_notifications( $_product, $new_stock, $item['qty'] ); } } } else { $order-&gt;add_order_note( sprintf( __( 'Not enough license code available for product &lt;strong&gt;%s&lt;/strong&gt;.', 'highthemes' ), $item['name'] ), 1, false ); } } /** * @param $order_id * @param $license_code_ids * * saves order id into license codes table for later usages */ public function assign_order_id_to_license_codes( $order_id, $license_code_ids ) { global $wpdb; $wpdb-&gt;query( "UPDATE {$wpdb-&gt;wc_ld_license_codes} SET order_id=$order_id WHERE id IN (" . implode( $license_code_ids, ',' ) . ")" ); } /** * @param $item_id * @param $item * @param $order * * displays the purchased license codes in my account page * * @return bool */ public function display_license_codes_in_user_account( $item_id, $item, $order ) { if ( ! is_account_page() &amp;&amp; !is_wc_endpoint_url( 'order-received' ) ) { return false; } if ( empty( $item['license_code_ids'] ) ) { return false; } $license_code_ids = is_array( $item['license_code_ids']) ? $item['license_code_ids']:unserialize( $item['license_code_ids'] ); $rows = WC_LD_Model::get_codes_by_id( implode( ",", $license_code_ids ) ); $product_id = (isset($item['variation_id']) &amp;&amp; !empty($item['variation_id'])) ? $item['variation_id'] : $item['product_id']; $code_1_title = WC_LD_Model::get_code_title( 1, $product_id ); $code_2_title = WC_LD_Model::get_code_title( 2, $product_id ); $code_3_title = WC_LD_Model::get_code_title( 3, $product_id ); $code_4_title = WC_LD_Model::get_code_title( 4, $product_id ); $code_5_title = WC_LD_Model::get_code_title( 5, $product_id ); // checking the user capability echo '&lt;table class="license-codes-table" style="width:100%;"&gt;'; echo ' &lt;tbody&gt;'; foreach ( $rows as $row ) { echo ''; if ( ! empty( $row['license_code1'] ) ) { echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $code_1_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_html( $row['license_code1'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code2'] ) ) { echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $code_2_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_html( $row['license_code2'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code3'] ) ) { echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $code_3_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_html( $row['license_code3'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code4'] ) ) { echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $code_4_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_html( $row['license_code4'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code5'] ) ) { echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $code_5_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_url( wp_get_attachment_url($row['license_code5']) ) . '&lt;/td&gt;&lt;/tr&gt;'; } echo '&lt;tr class="order-gap"&gt;&lt;td colspan="2"&gt;&amp;nbsp;&lt;/td&gt;&lt;/tr&gt;'; } echo '&lt;/tbody&gt;&lt;/table&gt;'; } /** * @param $item_id * @param $item * @param $order * * displays the purchased license codes in my account page * * @return bool */ public function display_license_codes( $item ) { //echo $this-&gt;get_assigned_codes(15); $license_ids=wc_get_order_item_meta( $item-&gt;get_id(), '_license_code_ids' ); if ( empty( $license_ids ) ) { return false; } //$license_code_ids=$license_ids; $license_code_ids = is_array( $license_ids) ? $license_ids : unserialize( $license_ids ); $rows = WC_LD_Model::get_codes_by_id( implode( ",", $license_code_ids ) ); $product_id = (isset($item['variation_id']) &amp;&amp; !empty($item['variation_id'])) ? $item['variation_id'] : $item['product_id']; $code_1_title = WC_LD_Model::get_code_title( 1, $product_id); $code_2_title = WC_LD_Model::get_code_title( 2, $product_id ); $code_3_title = WC_LD_Model::get_code_title( 3, $product_id ); $code_4_title = WC_LD_Model::get_code_title( 4, $product_id ); $code_5_title = WC_LD_Model::get_code_title( 5, $product_id ); // checking the user capability echo '&lt;table class="license-codes-table" style="width:100%;"&gt;'; echo ' &lt;tbody&gt;'; foreach ( $rows as $row ) { echo ''; if ( ! empty( $row['license_code1'] ) ) { echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $code_1_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_html( $row['license_code1'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code2'] ) ) { echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $code_2_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_html( $row['license_code2'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code3'] ) ) { echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $code_3_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_html( $row['license_code3'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code4'] ) ) { echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $code_4_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_html( $row['license_code4'] ) . '&lt;/td&gt;&lt;/tr&gt;'; } if ( ! empty( $row['license_code5'] ) ) { echo '&lt;tr&gt;&lt;th&gt;' . esc_html( $code_5_title ) . '&lt;/th&gt;&lt;td&gt;' . esc_url( wp_get_attachment_url($row['license_code5']) ) . '&lt;/td&gt;&lt;/tr&gt;'; } echo '&lt;tr class="order-gap"&gt;&lt;td colspan="2"&gt;&amp;nbsp;&lt;/td&gt;&lt;/tr&gt;'; } echo '&lt;/tbody&gt;&lt;/table&gt;'; } /** * @param $code * * this function used to mask license codes * * @return string */ public function mask_license_code( $code ) { if ( is_admin() &amp;&amp; ! current_user_can( 'manage_woocommerce' ) ) { if ( strlen( $code ) &lt;= 4 ) { $padsize = 2; $n = - 2; } else { $padsize = strlen( $code ) - 4; $n = - 4; } return str_repeat( '*', $padsize ) . substr( $code, $n ); } else { return $code; } } </code></pre> <p>}</p>
[ { "answer_id": 337528, "author": "Stephan Samuel", "author_id": 85968, "author_profile": "https://wordpress.stackexchange.com/users/85968", "pm_score": 1, "selected": false, "text": "<p>You're onto the answer...</p>\n\n<p>The function, <code>wp_get_attachment_url()</code> (see <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"nofollow noreferrer\">Codex</a>) just gives you the URL. You could wrap it in a link:</p>\n\n<pre><code>echo '&lt;tr&gt;&lt;td&gt;&lt;a href=\"' . esc_attr(wp_get_attachment_url($row['item_code1'])) . '\"&gt;' . esc_html($item_1_title) . '&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>Alternately, you can use <code>wp_get_attachment_link()</code> (see <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_link\" rel=\"nofollow noreferrer\">Codex</a>) as you mentioned:</p>\n\n<pre><code>echo wp_get_attachment_link($row['item_code1'], 'medium', false, false, esc_html($item_1_title));\n</code></pre>\n\n<p>Neither is specifically better all the time, it'll depend on what you're doing.</p>\n\n<p>Keep in mind that if you use the first bit of code above, your <code>&lt;a&gt;</code> tag <em>should</em> have an <code>alt</code> attribute. I believe this is for accessibility. You could use the link text, wrapped in <code>esc_attr()</code> for this.</p>\n\n<p><strong>Updated</strong> (after added code module)</p>\n\n<p>I've looked at your code.</p>\n\n<p>I must be missing something because I don't see anywhere it's rendering <code>&lt;a&gt;</code> tags. Going with what you're saying, that they're rendered in the front-end HTML, I'd have to <em>guess</em> that someone somewhere has some filter that's modifying what <code>esc_url()</code> does.</p>\n\n<p>Looking at the <a href=\"https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/formatting.php#L4171\" rel=\"nofollow noreferrer\">core code</a> (line 4171), there's one filter, <code>clean_url</code>, that's applied to the output of <code>esc_url()</code> before it returns. It's messy and poor according to WP best practices, but I've seen worse than someone editing that to do something like this. You'd probably have to do a text search on the code base (probably <code>wp-content/plugins</code>, although that could be a lot of code) to find if there's an instance of this filter being hooked. My spidey sense tells me that this isn't the place to start though.</p>\n\n<p>Not to be snarky, and I mean this in the most straightforward way, but I'm not completely sure I understand what you're saying is going wrong. I <em>think</em> you mean that the browser is rendering something like this:</p>\n\n<pre><code>&lt;td&gt;\n &lt;a href=\"http://domain.com/path-to-something\"&gt;http://domain.com/path-to-something&lt;/a&gt;\n&lt;/td&gt;\n</code></pre>\n\n<p>That would seem like the right output <em>to me,</em> but you're asking this question because the output isn't right <em>to you.</em> This leads me to believe that I don't fully understand the question, reinforced by the fact that I don't understand the thing about pasting a URL into a text box.</p>\n\n<p>Could you maybe edit with a snippet of HTML as rendered, and a snippet of HTML as you <em>want</em> it rendered? Given the code you posted, I could try to reconcile the two and see what's going on.</p>\n\n<p><strong>Updated</strong> (let's try this)</p>\n\n<p>For starters, welcome to WordPress. Also welcome to WP SE.</p>\n\n<p>(Your code doesn't show in your post with line numbers so please bear with me.)</p>\n\n<p>In the function, <code>get_assigned_codes</code>, try changing this line:</p>\n\n<pre><code>$codes_table .= '&lt;tr&gt;&lt;th class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_url( wp_get_attachment_url($code_5_title) ) . '&lt;/th&gt;&lt;td class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_html( $row['license_code5'] ) . '&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>(it's the third-to-last line in the function that isn't whitespace or curlies) with this:</p>\n\n<pre><code>$codes_table .= '&lt;tr&gt;&lt;th class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;&lt;a href=\"' . esc_attr(esc_url(wp_get_attachment_url($code_5_title))) . '\"&gt;' . esc_url(wp_get_attachment_url($code_5_title)) . '&lt;/a&gt;&lt;/th&gt;&lt;td class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_html( $row['license_code5'] ) . '&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>To see if that works, you'll have to go to the right place that uses that function and compare the output.</p>\n\n<p>There appear to be a few other places where it's doing about the same thing (hence why you referenced several code lines) but let's try one to see what it does.</p>\n\n<p>If you try that, do you get more of what you want?</p>\n\n<p><strong>Updating</strong> (a bit more info but we're onto something)</p>\n\n<p>Try this:</p>\n\n<pre><code>$codes_table .= '&lt;tr&gt;&lt;th class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_url( wp_get_attachment_url($code_5_title) ) . '&lt;/th&gt;&lt;td class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;&lt;a href=\"' . esc_attr( $row['license_code5'] ) . '\"&gt;' . esc_html($row['license_code5']) . '&lt;/a&gt;&amp;nbsp;&lt;a href=\"' . esc_attr(wp_get_attachment_url($row['license_code5'])) . '\"&gt;' . esc_html($row['license_code5']) . '&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>My apologies, the previous suggestion was incorrect. I put the change in the wrong place.</p>\n\n<p>This should print 2 items in the URL field. If either of them is correct, remove the incorrect one and the extra stuff around it. Also, you probably don't need <code>wp_get_attachment_url()</code> in the left-hand field.</p>\n" }, { "answer_id": 337547, "author": "Stephan Samuel", "author_id": 85968, "author_profile": "https://wordpress.stackexchange.com/users/85968", "pm_score": 0, "selected": false, "text": "<p>My previous answer wasn't helping. Let me approach this a different way that may be of some use to someone in the future.</p>\n\n<p><strong>You're coming from Joomla.</strong> It's been forever since I used it but Google tells me it's based on PHP. WP is somewhat object-oriented but I've seen more non-object-oriented plugins than I've seen object-oriented ones.</p>\n\n<p>So you've got a basis in PHP.</p>\n\n<p><strong>A filter</strong> is a thing that lets you modify things at runtime. Filter names are ephemeral but core <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference\" rel=\"nofollow noreferrer\">uses a whole bunch of them</a>. You hook using <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\"><code>add_filter()</code></a> with a priority and a number of arguments. The return value of a filter is always supposed to be of the same type as the first argument, thereby making the remaining arguments modifiers for how the filter is supposed to work. Also, if you call a filter (using <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\"><code>apply_filters()</code></a>) and there are no filters defined, it'll just give you back your argument. <code>add_action()</code> does the same thing without returning a value (PHP void).</p>\n\n<p><strong>The <code>wp_posts</code> table</strong> contains stuff. Some CMS systems do it differently but many just use a big flat table like this. The <code>post_type</code> column tells you what kind of post it is, with <code>post</code> (re-use of the name) being a blog and <code>page</code> being a front-end page. You can <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">define custom post types</a>. Additional metadata about a post is stored in <code>wp_postmeta</code>, using the post ID.</p>\n\n<p>(Tables are prefixed and your prefix may not be <code>wp_</code>. The suffix is the same.)</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_url()</code></a> <strong>takes a post ID</strong> and returns the URL of a post of <code>post_type</code> <code>attachment</code> that's associated with that post. (Therefore, <code>attachment</code> is another core post type.) It returns just the URL, not a link. If you want a link, you have to either use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_link\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_link()</code></a> or draw the link yourself. That's something like this:</p>\n\n<pre><code>?&gt;\n &lt;a href=\"&lt;?php echo wp_get_attachment_link($id); ?&gt;\"&gt;link text&lt;/a&gt;\n&lt;?php\n</code></pre>\n\n<p>I'm not sure which of your variables contains the post ID and which contains the text to display. This is based on how WooCommerce is set up. In WC (it appears as if you're in Europe so please excuse the abbreviation), products are stored as posts. I forgot the exact <code>post_type</code> and I don't have a WC setup handy. Therefore, you're probably looking for the post ID for a product.</p>\n\n<p><strong>You can use direct database access</strong> to get things using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">the <code>wpdb</code> class</a> but the way you're, \"supposed to,\" do it is with <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">the <code>WP_Query</code> class</a>. Instantiate one with an array like so:</p>\n\n<pre><code>$query = new WP_Query(array('post_type' =&gt; 'product', 'nopaging' =&gt; true));\n</code></pre>\n\n<p>Then use <code>$query-&gt;posts</code> to get an array of the matched records.</p>\n\n<p><strong>The helper functions</strong> <a href=\"https://codex.wordpress.org/Function_Reference/esc_html\" rel=\"nofollow noreferrer\"><code>esc_html()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/esc_attr/\" rel=\"nofollow noreferrer\"><code>esc_attr()</code></a> escape text for output for element content and attributes, respectively. <a href=\"https://developer.wordpress.org/reference/functions/esc_url/\" rel=\"nofollow noreferrer\"><code>esc_url()</code></a> is similar. As with any other CMS, never trust anything that comes from the user (even an admin) or the database. These functions help you wrap it.</p>\n\n<p><strong>You can debug</strong> using <code>printf()</code>. <code>print_r()</code> works for arrays and objects. I prefer <code>var_export($object, true)</code> because it always pretty-prints everything. If you can set up your PHP log, <code>error_log()</code> works well (that's what I use). I've never found an IDE that really helps me debug well enough.</p>\n\n<p>That having been said, you're dumping data into an HTML table. Find out (using some debugging method) what your post ID is and what text you want to display. Then use <code>wp_get_attachment_url()</code> with your post ID to get the URL of the image you want to display. If <code>$id</code> has the post ID and <code>$linktext</code> has the link text, do this:</p>\n\n<pre><code>echo '&lt;a href=\"' . esc_attr(wp_get_attachment_url($id)) . '\"&gt;' . $linktext . '&lt;/a&gt;';\n</code></pre>\n\n<p>Stick that somewhere into a <code>&lt;th&gt;</code> or <code>&lt;td&gt;</code> and you'll get a clickable link. If you want to display the image, do this:</p>\n\n<pre><code>echo '&lt;img src=\"' . esc_attr(wp_get_attachment_url($id)) . '\" /&gt;';\n</code></pre>\n\n<p>Hopefully, somewhere in there is all you need to get this to work.</p>\n" } ]
2019/05/09
[ "https://wordpress.stackexchange.com/questions/337525", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167709/" ]
be gentle, I'm pretty new (just over from Joomla). This is part of an array... ``` echo '<tr><th>' . esc_html( $item_1_title ) . '</th><td>' . esc_url( wp_get_attachment_url($row['item_code1']) ) . '</td></tr>'; ``` It works fine, but at the front end, the output is plain text. I can't seem to figure out how to render an encoded URL (clickable link). Should I be using get\_attachment\_link or 'image source'? Any help would be gratefully received. Thanks Mark ......... Complete php (pertinent lines; 203, 403, 463) ``` <?php ``` if ( ! defined( 'ABSPATH' ) ) { exit; } /\*\* \* Class WC\_LD\_Code\_Assignment \* \* assign codes when user pruchase a product \*/ class WC\_LD\_Code\_Assignment { ``` public function setup() { // assign codes on processing or complete order status $delivery_order_status = get_option( 'wc_ld_delivery_order_status' ); $order_status = ( empty( $delivery_order_status ) ? 'completed' : $delivery_order_status ); add_action( 'woocommerce_order_status_' . $order_status, array( $this, 'assign_license_codes_to_order' ), 10, 1 ); add_action( 'woocommerce_order_item_meta_start', array( $this, 'display_license_codes_in_user_account' ), 10, 3 ); add_action( 'woocommerce_email_after_order_table', array( $this, 'email_after_order_table' ), 100, 4 ); add_filter( "woocommerce_can_reduce_order_stock", array( $this, 'dont_reduce_order_stock' ), 10, 2 ); add_action( 'woocommerce_order_status_changed', array( $this, 'manage_stock_for_simple_products' ), 100, 3 ); } /** * * As we disabled auto stock reduction for all product * here, we reduce order manually for simple products * * @param $order_id * @param $old_status * @param $new_status * * @return bool */ public function manage_stock_for_simple_products( $order_id, $old_status, $new_status ) { if ( is_object( $order_id ) ) { $order_id = $order_id->id; } // if order stock already reduced if ( get_post_meta( $order_id, '_order_stock_reduced', true ) ) { return false; } if ( $new_status == 'processing' || $new_status == 'completed' ) { // get the order details $order = new WC_Order( $order_id ); $order_items = $order->get_items(); $reduced = false; foreach ( $order_items as $item ) { $qty = $item['qty']; if ( $item['product_id'] > 0 ) { $is_license_code = get_post_meta( $item['product_id'], '_wc_ld_license_code', true ); if ( empty( $is_license_code ) || $is_license_code == 'no' ) { $_product = $order->get_product_from_item( $item ); if ( $_product && $_product->exists() && $_product->managing_stock() ) { if(version_compare( WC_VERSION, '3.0.0', '>' )){ $new_stock = wc_update_product_stock($item['product_id'], $qty, 'decrease' ); } else{ $new_stock = $_product->reduce_stock( $qty ); } $item_name = $_product->get_sku() ? $_product->get_sku() : $item['product_id']; if ( isset( $item['variation_id'] ) && $item['variation_id'] ) { $order->add_order_note( sprintf( __( 'Item %s variation #%s stock reduced from %s to %s.', 'highthemes' ), $item_name, $item['variation_id'], $new_stock + $qty, $new_stock ) ); } else { $order->add_order_note( sprintf( __( 'Item %s stock reduced from %s to %s.', 'highthemes' ), $item_name, $new_stock + $qty, $new_stock ) ); } if(version_compare( WC_VERSION, '3.0.0', '>' )){ } else{ $order->send_stock_notifications( $_product, $new_stock, $item['qty'] ); } $reduced = true; } } } } if ( $reduced ) { add_post_meta( $order_id, '_order_stock_reduced', '1', true ); } } } /** * @return bool * * prevent payment proccessing addons to reduce stock. It is done with this plugin */ public function dont_reduce_order_stock( $current_value, $order ) { return false; } /** * @param $order * @param $sent_to_admin * @param $plain_text * @param $email * * included the license codes in the order email sent to the user */ public function email_after_order_table( $order, $sent_to_admin, $plain_text, $email ) { if ( is_object( $order ) ) { $delivery_order_status = get_option( 'wc_ld_delivery_order_status' ); $order_id = $order->get_id(); $order_status = ( empty( $delivery_order_status ) ? 'completed' : $delivery_order_status ); if ( $order->get_status() == $order_status ) { echo $this->get_assigned_codes( $order_id ); } } } /** * @param $order_id * * get the assigned codes to an order * * @return string|void */ public function get_assigned_codes( $order_id ) { if ( is_object( $order_id ) ) { $order_id = $order_id->id; } // get the order details $order = new WC_Order( $order_id ); // check order items to get quantity and product id $order_items = $order->get_items(); $codes_table = ''; foreach ( $order_items as $key => $value ) { if ( ! isset( $value['license_code_ids'] ) ) { continue; } $license_code_ids = is_array($value['license_code_ids']) ? $value['license_code_ids']: unserialize( $value['license_code_ids'] ); if ( empty( $license_code_ids ) ) { return; } $product_id = (isset($value['variation_id']) && !empty($value['variation_id'])) ? $value['variation_id'] : $value['product_id']; $rows = WC_LD_Model::get_codes_by_id( implode( ",", $license_code_ids ) ); $code_1_title = WC_LD_Model::get_code_title( 1, $product_id ); $code_2_title = WC_LD_Model::get_code_title( 2, $product_id ); $code_3_title = WC_LD_Model::get_code_title( 3, $product_id ); $code_4_title = WC_LD_Model::get_code_title( 4, $product_id ); $code_5_title = WC_LD_Model::get_code_title( 5, $product_id ); $description = get_post_meta( $value['product_id'], '_wc_ld_product_code_description', true ); $codes_table .= '<h3>' . $value['name'] . '</h3>'; $codes_table .= '<div style="padding-bottom:20px;">' . $description . '</div>'; foreach ( $rows as $row ) { $codes_table .= '<table class="td" cellspacing="0" cellpadding="6" style="margin-bottom:20px;width: 100%; font-family: \'Helvetica Neue\', Helvetica, Roboto, Arial, sans-serif;" border="1">'; $codes_table .= ' <tbody>'; if ( ! empty( $row['license_code1'] ) ) { $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;width:40%; background-color:#eeeeee;">' . esc_html( $code_1_title ) . '</th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code1'] ) . '</td></tr>'; } if ( ! empty( $row['license_code2'] ) ) { $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;">' . esc_html( $code_2_title ) . '</th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code2'] ) . '</td></tr>'; } if ( ! empty( $row['license_code3'] ) ) { $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;">' . esc_html( $code_3_title ) . '</th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code3'] ) . '</td></tr>'; } if ( ! empty( $row['license_code4'] ) ) { $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;">' . esc_html( $code_4_title ) . '</th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code4'] ) . '</td></tr>'; } if ( ! empty( $row['license_code5'] ) ) { $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;">' . esc_url( wp_get_attachment_url($code_5_title) ) . '</th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code5'] ) . '</td></tr>'; } $codes_table .= '</tbody></table>'; } } return $codes_table; } /** * @param $order_id * * do the license code assignment to order */ public function assign_license_codes_to_order( $order_id ) { global $wpdb; if ( is_object( $order_id ) ) { $order_id = $order_id->id; } // get the order details $order = new WC_Order( $order_id ); // check order items to get quantity and product id $order_items = $order->get_items(); // assign license codes to order items foreach ( $order_items as $item_id => $item ) { // if there is no code assigned to this order item if ( empty( $item['license_code_ids'] ) ) { // if product has marked as license code product $is_license_code = get_post_meta( $item['product_id'], '_wc_ld_license_code', true ); if ( empty( $is_license_code ) || $is_license_code == 'no' ) { continue; } $this->assign_license_to_item( $item_id, $item, $order, $order_id ); } } } /** * @param $item_id * @param $item * @param $order * @param $order_id * * does the license assignment for each order item */ public function assign_license_to_item( $item_id, $item, $order, $order_id ) { global $wpdb; $product_id = (isset($item['variation_id']) && !empty($item['variation_id'])) ? $item['variation_id'] : $item['product_id']; $qty = $item['qty']; // get license codes from databse based on requested qty $rows = $wpdb->get_results( "SELECT * FROM {$wpdb->wc_ld_license_codes} WHERE product_id = $product_id AND license_code1 <> '' AND license_status = '0' LIMIT $qty" ); // build an array of license code ids foreach ( $rows as $query ) { $license_code_ids[] = $query->id; } // only assign license codes if we have the requested quantity of the item if ( count( $license_code_ids ) == $qty ) { // save the order id in license codes table $this->assign_order_id_to_license_codes( $order_id, $license_code_ids ); // save the assigned license codes in order item meta wc_add_order_item_meta( $item_id, '_license_code_ids', $license_code_ids ); // change sold license codes status to sold WC_LD_Model::change_license_codes_status( implode( $license_code_ids, ',' ), '1' ); // reduce stock $_product = $order->get_product_from_item( $item ); if ( $_product && $_product->exists() && $_product->managing_stock() ) { if(version_compare( WC_VERSION, '3.0.0', '>' ) ){ $new_stock = wc_update_product_stock($product_id , $qty, 'decrease' ); update_post_meta( $order_id, '_order_stock_reduced', '1', true ); } else{ $new_stock = $_product->reduce_stock( $qty ); update_post_meta( $order_id, '_order_stock_reduced', '1', true ); } $item_name = $_product->get_sku() ? $_product->get_sku() : $item['product_id']; if ( isset( $item['variation_id'] ) && $item['variation_id'] ) { $order->add_order_note( sprintf( __( 'Item %s variation #%s stock reduced from %s to %s.', 'highthemes' ), $item_name, $item['variation_id'], $new_stock + $qty, $new_stock ) ); } else { $order->add_order_note( sprintf( __( 'Item %s stock reduced from %s to %s.', 'highthemes' ), $item_name, $new_stock + $qty, $new_stock ) ); } if(version_compare( WC_VERSION, '3.0.0', '>' )){ } else{ $order->send_stock_notifications( $_product, $new_stock, $item['qty'] ); } } } else { $order->add_order_note( sprintf( __( 'Not enough license code available for product <strong>%s</strong>.', 'highthemes' ), $item['name'] ), 1, false ); } } /** * @param $order_id * @param $license_code_ids * * saves order id into license codes table for later usages */ public function assign_order_id_to_license_codes( $order_id, $license_code_ids ) { global $wpdb; $wpdb->query( "UPDATE {$wpdb->wc_ld_license_codes} SET order_id=$order_id WHERE id IN (" . implode( $license_code_ids, ',' ) . ")" ); } /** * @param $item_id * @param $item * @param $order * * displays the purchased license codes in my account page * * @return bool */ public function display_license_codes_in_user_account( $item_id, $item, $order ) { if ( ! is_account_page() && !is_wc_endpoint_url( 'order-received' ) ) { return false; } if ( empty( $item['license_code_ids'] ) ) { return false; } $license_code_ids = is_array( $item['license_code_ids']) ? $item['license_code_ids']:unserialize( $item['license_code_ids'] ); $rows = WC_LD_Model::get_codes_by_id( implode( ",", $license_code_ids ) ); $product_id = (isset($item['variation_id']) && !empty($item['variation_id'])) ? $item['variation_id'] : $item['product_id']; $code_1_title = WC_LD_Model::get_code_title( 1, $product_id ); $code_2_title = WC_LD_Model::get_code_title( 2, $product_id ); $code_3_title = WC_LD_Model::get_code_title( 3, $product_id ); $code_4_title = WC_LD_Model::get_code_title( 4, $product_id ); $code_5_title = WC_LD_Model::get_code_title( 5, $product_id ); // checking the user capability echo '<table class="license-codes-table" style="width:100%;">'; echo ' <tbody>'; foreach ( $rows as $row ) { echo ''; if ( ! empty( $row['license_code1'] ) ) { echo '<tr><th>' . esc_html( $code_1_title ) . '</th><td>' . esc_html( $row['license_code1'] ) . '</td></tr>'; } if ( ! empty( $row['license_code2'] ) ) { echo '<tr><th>' . esc_html( $code_2_title ) . '</th><td>' . esc_html( $row['license_code2'] ) . '</td></tr>'; } if ( ! empty( $row['license_code3'] ) ) { echo '<tr><th>' . esc_html( $code_3_title ) . '</th><td>' . esc_html( $row['license_code3'] ) . '</td></tr>'; } if ( ! empty( $row['license_code4'] ) ) { echo '<tr><th>' . esc_html( $code_4_title ) . '</th><td>' . esc_html( $row['license_code4'] ) . '</td></tr>'; } if ( ! empty( $row['license_code5'] ) ) { echo '<tr><th>' . esc_html( $code_5_title ) . '</th><td>' . esc_url( wp_get_attachment_url($row['license_code5']) ) . '</td></tr>'; } echo '<tr class="order-gap"><td colspan="2">&nbsp;</td></tr>'; } echo '</tbody></table>'; } /** * @param $item_id * @param $item * @param $order * * displays the purchased license codes in my account page * * @return bool */ public function display_license_codes( $item ) { //echo $this->get_assigned_codes(15); $license_ids=wc_get_order_item_meta( $item->get_id(), '_license_code_ids' ); if ( empty( $license_ids ) ) { return false; } //$license_code_ids=$license_ids; $license_code_ids = is_array( $license_ids) ? $license_ids : unserialize( $license_ids ); $rows = WC_LD_Model::get_codes_by_id( implode( ",", $license_code_ids ) ); $product_id = (isset($item['variation_id']) && !empty($item['variation_id'])) ? $item['variation_id'] : $item['product_id']; $code_1_title = WC_LD_Model::get_code_title( 1, $product_id); $code_2_title = WC_LD_Model::get_code_title( 2, $product_id ); $code_3_title = WC_LD_Model::get_code_title( 3, $product_id ); $code_4_title = WC_LD_Model::get_code_title( 4, $product_id ); $code_5_title = WC_LD_Model::get_code_title( 5, $product_id ); // checking the user capability echo '<table class="license-codes-table" style="width:100%;">'; echo ' <tbody>'; foreach ( $rows as $row ) { echo ''; if ( ! empty( $row['license_code1'] ) ) { echo '<tr><th>' . esc_html( $code_1_title ) . '</th><td>' . esc_html( $row['license_code1'] ) . '</td></tr>'; } if ( ! empty( $row['license_code2'] ) ) { echo '<tr><th>' . esc_html( $code_2_title ) . '</th><td>' . esc_html( $row['license_code2'] ) . '</td></tr>'; } if ( ! empty( $row['license_code3'] ) ) { echo '<tr><th>' . esc_html( $code_3_title ) . '</th><td>' . esc_html( $row['license_code3'] ) . '</td></tr>'; } if ( ! empty( $row['license_code4'] ) ) { echo '<tr><th>' . esc_html( $code_4_title ) . '</th><td>' . esc_html( $row['license_code4'] ) . '</td></tr>'; } if ( ! empty( $row['license_code5'] ) ) { echo '<tr><th>' . esc_html( $code_5_title ) . '</th><td>' . esc_url( wp_get_attachment_url($row['license_code5']) ) . '</td></tr>'; } echo '<tr class="order-gap"><td colspan="2">&nbsp;</td></tr>'; } echo '</tbody></table>'; } /** * @param $code * * this function used to mask license codes * * @return string */ public function mask_license_code( $code ) { if ( is_admin() && ! current_user_can( 'manage_woocommerce' ) ) { if ( strlen( $code ) <= 4 ) { $padsize = 2; $n = - 2; } else { $padsize = strlen( $code ) - 4; $n = - 4; } return str_repeat( '*', $padsize ) . substr( $code, $n ); } else { return $code; } } ``` }
You're onto the answer... The function, `wp_get_attachment_url()` (see [Codex](https://codex.wordpress.org/Function_Reference/wp_get_attachment_url)) just gives you the URL. You could wrap it in a link: ``` echo '<tr><td><a href="' . esc_attr(wp_get_attachment_url($row['item_code1'])) . '">' . esc_html($item_1_title) . '</a></td></tr>'; ``` Alternately, you can use `wp_get_attachment_link()` (see [Codex](https://codex.wordpress.org/Function_Reference/wp_get_attachment_link)) as you mentioned: ``` echo wp_get_attachment_link($row['item_code1'], 'medium', false, false, esc_html($item_1_title)); ``` Neither is specifically better all the time, it'll depend on what you're doing. Keep in mind that if you use the first bit of code above, your `<a>` tag *should* have an `alt` attribute. I believe this is for accessibility. You could use the link text, wrapped in `esc_attr()` for this. **Updated** (after added code module) I've looked at your code. I must be missing something because I don't see anywhere it's rendering `<a>` tags. Going with what you're saying, that they're rendered in the front-end HTML, I'd have to *guess* that someone somewhere has some filter that's modifying what `esc_url()` does. Looking at the [core code](https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/formatting.php#L4171) (line 4171), there's one filter, `clean_url`, that's applied to the output of `esc_url()` before it returns. It's messy and poor according to WP best practices, but I've seen worse than someone editing that to do something like this. You'd probably have to do a text search on the code base (probably `wp-content/plugins`, although that could be a lot of code) to find if there's an instance of this filter being hooked. My spidey sense tells me that this isn't the place to start though. Not to be snarky, and I mean this in the most straightforward way, but I'm not completely sure I understand what you're saying is going wrong. I *think* you mean that the browser is rendering something like this: ``` <td> <a href="http://domain.com/path-to-something">http://domain.com/path-to-something</a> </td> ``` That would seem like the right output *to me,* but you're asking this question because the output isn't right *to you.* This leads me to believe that I don't fully understand the question, reinforced by the fact that I don't understand the thing about pasting a URL into a text box. Could you maybe edit with a snippet of HTML as rendered, and a snippet of HTML as you *want* it rendered? Given the code you posted, I could try to reconcile the two and see what's going on. **Updated** (let's try this) For starters, welcome to WordPress. Also welcome to WP SE. (Your code doesn't show in your post with line numbers so please bear with me.) In the function, `get_assigned_codes`, try changing this line: ``` $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;">' . esc_url( wp_get_attachment_url($code_5_title) ) . '</th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code5'] ) . '</td></tr>'; ``` (it's the third-to-last line in the function that isn't whitespace or curlies) with this: ``` $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;"><a href="' . esc_attr(esc_url(wp_get_attachment_url($code_5_title))) . '">' . esc_url(wp_get_attachment_url($code_5_title)) . '</a></th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code5'] ) . '</td></tr>'; ``` To see if that works, you'll have to go to the right place that uses that function and compare the output. There appear to be a few other places where it's doing about the same thing (hence why you referenced several code lines) but let's try one to see what it does. If you try that, do you get more of what you want? **Updating** (a bit more info but we're onto something) Try this: ``` $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;">' . esc_url( wp_get_attachment_url($code_5_title) ) . '</th><td class="td" scope="col" style="text-align:left;"><a href="' . esc_attr( $row['license_code5'] ) . '">' . esc_html($row['license_code5']) . '</a>&nbsp;<a href="' . esc_attr(wp_get_attachment_url($row['license_code5'])) . '">' . esc_html($row['license_code5']) . '</a></td></tr>'; ``` My apologies, the previous suggestion was incorrect. I put the change in the wrong place. This should print 2 items in the URL field. If either of them is correct, remove the incorrect one and the extra stuff around it. Also, you probably don't need `wp_get_attachment_url()` in the left-hand field.
337,647
<p>I recently took over a WordPress site with the following directory structure inside of <strong>/public_html</strong>:</p> <pre><code>wp_config.php /wp-admin /wp-content /wp-includes ... ... ... /development </code></pre> <p>The root (production) site is pointed to <strong>/public_html</strong>. Inside of <strong>/public_html</strong>, I have a sub-folder called <strong>/development</strong>. This subfolder has its own separate installation of Wordpress with a directory tree that looks like:</p> <pre><code>wp_config.php /wp-admin /wp-content /wp-includes ... ... ... </code></pre> <p>You can access this WordPress instance via <em>www.mywebsite.com/development</em>. I am at a point where I would like to promote the development build to production. </p> <p>What's the "WordPress" way of doing this? This is hosted on a machine that can be accessed via cPanel. I've noticed that while you can add "Addon Domains" and "Subdomains" via cPanel, you can't change the root public directory through cPanel. I would like to avoid SSHing into the machine and manually editing the <strong>httpd.conf</strong> file since that can cause conflicts with cPanel. </p> <p>Ideally, I would like to avoid moving files all together and just point Apache's root directory to <strong>/public_html/development</strong>.</p>
[ { "answer_id": 337528, "author": "Stephan Samuel", "author_id": 85968, "author_profile": "https://wordpress.stackexchange.com/users/85968", "pm_score": 1, "selected": false, "text": "<p>You're onto the answer...</p>\n\n<p>The function, <code>wp_get_attachment_url()</code> (see <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"nofollow noreferrer\">Codex</a>) just gives you the URL. You could wrap it in a link:</p>\n\n<pre><code>echo '&lt;tr&gt;&lt;td&gt;&lt;a href=\"' . esc_attr(wp_get_attachment_url($row['item_code1'])) . '\"&gt;' . esc_html($item_1_title) . '&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>Alternately, you can use <code>wp_get_attachment_link()</code> (see <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_link\" rel=\"nofollow noreferrer\">Codex</a>) as you mentioned:</p>\n\n<pre><code>echo wp_get_attachment_link($row['item_code1'], 'medium', false, false, esc_html($item_1_title));\n</code></pre>\n\n<p>Neither is specifically better all the time, it'll depend on what you're doing.</p>\n\n<p>Keep in mind that if you use the first bit of code above, your <code>&lt;a&gt;</code> tag <em>should</em> have an <code>alt</code> attribute. I believe this is for accessibility. You could use the link text, wrapped in <code>esc_attr()</code> for this.</p>\n\n<p><strong>Updated</strong> (after added code module)</p>\n\n<p>I've looked at your code.</p>\n\n<p>I must be missing something because I don't see anywhere it's rendering <code>&lt;a&gt;</code> tags. Going with what you're saying, that they're rendered in the front-end HTML, I'd have to <em>guess</em> that someone somewhere has some filter that's modifying what <code>esc_url()</code> does.</p>\n\n<p>Looking at the <a href=\"https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/formatting.php#L4171\" rel=\"nofollow noreferrer\">core code</a> (line 4171), there's one filter, <code>clean_url</code>, that's applied to the output of <code>esc_url()</code> before it returns. It's messy and poor according to WP best practices, but I've seen worse than someone editing that to do something like this. You'd probably have to do a text search on the code base (probably <code>wp-content/plugins</code>, although that could be a lot of code) to find if there's an instance of this filter being hooked. My spidey sense tells me that this isn't the place to start though.</p>\n\n<p>Not to be snarky, and I mean this in the most straightforward way, but I'm not completely sure I understand what you're saying is going wrong. I <em>think</em> you mean that the browser is rendering something like this:</p>\n\n<pre><code>&lt;td&gt;\n &lt;a href=\"http://domain.com/path-to-something\"&gt;http://domain.com/path-to-something&lt;/a&gt;\n&lt;/td&gt;\n</code></pre>\n\n<p>That would seem like the right output <em>to me,</em> but you're asking this question because the output isn't right <em>to you.</em> This leads me to believe that I don't fully understand the question, reinforced by the fact that I don't understand the thing about pasting a URL into a text box.</p>\n\n<p>Could you maybe edit with a snippet of HTML as rendered, and a snippet of HTML as you <em>want</em> it rendered? Given the code you posted, I could try to reconcile the two and see what's going on.</p>\n\n<p><strong>Updated</strong> (let's try this)</p>\n\n<p>For starters, welcome to WordPress. Also welcome to WP SE.</p>\n\n<p>(Your code doesn't show in your post with line numbers so please bear with me.)</p>\n\n<p>In the function, <code>get_assigned_codes</code>, try changing this line:</p>\n\n<pre><code>$codes_table .= '&lt;tr&gt;&lt;th class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_url( wp_get_attachment_url($code_5_title) ) . '&lt;/th&gt;&lt;td class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_html( $row['license_code5'] ) . '&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>(it's the third-to-last line in the function that isn't whitespace or curlies) with this:</p>\n\n<pre><code>$codes_table .= '&lt;tr&gt;&lt;th class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;&lt;a href=\"' . esc_attr(esc_url(wp_get_attachment_url($code_5_title))) . '\"&gt;' . esc_url(wp_get_attachment_url($code_5_title)) . '&lt;/a&gt;&lt;/th&gt;&lt;td class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_html( $row['license_code5'] ) . '&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>To see if that works, you'll have to go to the right place that uses that function and compare the output.</p>\n\n<p>There appear to be a few other places where it's doing about the same thing (hence why you referenced several code lines) but let's try one to see what it does.</p>\n\n<p>If you try that, do you get more of what you want?</p>\n\n<p><strong>Updating</strong> (a bit more info but we're onto something)</p>\n\n<p>Try this:</p>\n\n<pre><code>$codes_table .= '&lt;tr&gt;&lt;th class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_url( wp_get_attachment_url($code_5_title) ) . '&lt;/th&gt;&lt;td class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;&lt;a href=\"' . esc_attr( $row['license_code5'] ) . '\"&gt;' . esc_html($row['license_code5']) . '&lt;/a&gt;&amp;nbsp;&lt;a href=\"' . esc_attr(wp_get_attachment_url($row['license_code5'])) . '\"&gt;' . esc_html($row['license_code5']) . '&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>My apologies, the previous suggestion was incorrect. I put the change in the wrong place.</p>\n\n<p>This should print 2 items in the URL field. If either of them is correct, remove the incorrect one and the extra stuff around it. Also, you probably don't need <code>wp_get_attachment_url()</code> in the left-hand field.</p>\n" }, { "answer_id": 337547, "author": "Stephan Samuel", "author_id": 85968, "author_profile": "https://wordpress.stackexchange.com/users/85968", "pm_score": 0, "selected": false, "text": "<p>My previous answer wasn't helping. Let me approach this a different way that may be of some use to someone in the future.</p>\n\n<p><strong>You're coming from Joomla.</strong> It's been forever since I used it but Google tells me it's based on PHP. WP is somewhat object-oriented but I've seen more non-object-oriented plugins than I've seen object-oriented ones.</p>\n\n<p>So you've got a basis in PHP.</p>\n\n<p><strong>A filter</strong> is a thing that lets you modify things at runtime. Filter names are ephemeral but core <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference\" rel=\"nofollow noreferrer\">uses a whole bunch of them</a>. You hook using <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\"><code>add_filter()</code></a> with a priority and a number of arguments. The return value of a filter is always supposed to be of the same type as the first argument, thereby making the remaining arguments modifiers for how the filter is supposed to work. Also, if you call a filter (using <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\"><code>apply_filters()</code></a>) and there are no filters defined, it'll just give you back your argument. <code>add_action()</code> does the same thing without returning a value (PHP void).</p>\n\n<p><strong>The <code>wp_posts</code> table</strong> contains stuff. Some CMS systems do it differently but many just use a big flat table like this. The <code>post_type</code> column tells you what kind of post it is, with <code>post</code> (re-use of the name) being a blog and <code>page</code> being a front-end page. You can <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">define custom post types</a>. Additional metadata about a post is stored in <code>wp_postmeta</code>, using the post ID.</p>\n\n<p>(Tables are prefixed and your prefix may not be <code>wp_</code>. The suffix is the same.)</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_url()</code></a> <strong>takes a post ID</strong> and returns the URL of a post of <code>post_type</code> <code>attachment</code> that's associated with that post. (Therefore, <code>attachment</code> is another core post type.) It returns just the URL, not a link. If you want a link, you have to either use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_link\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_link()</code></a> or draw the link yourself. That's something like this:</p>\n\n<pre><code>?&gt;\n &lt;a href=\"&lt;?php echo wp_get_attachment_link($id); ?&gt;\"&gt;link text&lt;/a&gt;\n&lt;?php\n</code></pre>\n\n<p>I'm not sure which of your variables contains the post ID and which contains the text to display. This is based on how WooCommerce is set up. In WC (it appears as if you're in Europe so please excuse the abbreviation), products are stored as posts. I forgot the exact <code>post_type</code> and I don't have a WC setup handy. Therefore, you're probably looking for the post ID for a product.</p>\n\n<p><strong>You can use direct database access</strong> to get things using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">the <code>wpdb</code> class</a> but the way you're, \"supposed to,\" do it is with <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">the <code>WP_Query</code> class</a>. Instantiate one with an array like so:</p>\n\n<pre><code>$query = new WP_Query(array('post_type' =&gt; 'product', 'nopaging' =&gt; true));\n</code></pre>\n\n<p>Then use <code>$query-&gt;posts</code> to get an array of the matched records.</p>\n\n<p><strong>The helper functions</strong> <a href=\"https://codex.wordpress.org/Function_Reference/esc_html\" rel=\"nofollow noreferrer\"><code>esc_html()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/esc_attr/\" rel=\"nofollow noreferrer\"><code>esc_attr()</code></a> escape text for output for element content and attributes, respectively. <a href=\"https://developer.wordpress.org/reference/functions/esc_url/\" rel=\"nofollow noreferrer\"><code>esc_url()</code></a> is similar. As with any other CMS, never trust anything that comes from the user (even an admin) or the database. These functions help you wrap it.</p>\n\n<p><strong>You can debug</strong> using <code>printf()</code>. <code>print_r()</code> works for arrays and objects. I prefer <code>var_export($object, true)</code> because it always pretty-prints everything. If you can set up your PHP log, <code>error_log()</code> works well (that's what I use). I've never found an IDE that really helps me debug well enough.</p>\n\n<p>That having been said, you're dumping data into an HTML table. Find out (using some debugging method) what your post ID is and what text you want to display. Then use <code>wp_get_attachment_url()</code> with your post ID to get the URL of the image you want to display. If <code>$id</code> has the post ID and <code>$linktext</code> has the link text, do this:</p>\n\n<pre><code>echo '&lt;a href=\"' . esc_attr(wp_get_attachment_url($id)) . '\"&gt;' . $linktext . '&lt;/a&gt;';\n</code></pre>\n\n<p>Stick that somewhere into a <code>&lt;th&gt;</code> or <code>&lt;td&gt;</code> and you'll get a clickable link. If you want to display the image, do this:</p>\n\n<pre><code>echo '&lt;img src=\"' . esc_attr(wp_get_attachment_url($id)) . '\" /&gt;';\n</code></pre>\n\n<p>Hopefully, somewhere in there is all you need to get this to work.</p>\n" } ]
2019/05/11
[ "https://wordpress.stackexchange.com/questions/337647", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167796/" ]
I recently took over a WordPress site with the following directory structure inside of **/public\_html**: ``` wp_config.php /wp-admin /wp-content /wp-includes ... ... ... /development ``` The root (production) site is pointed to **/public\_html**. Inside of **/public\_html**, I have a sub-folder called **/development**. This subfolder has its own separate installation of Wordpress with a directory tree that looks like: ``` wp_config.php /wp-admin /wp-content /wp-includes ... ... ... ``` You can access this WordPress instance via *www.mywebsite.com/development*. I am at a point where I would like to promote the development build to production. What's the "WordPress" way of doing this? This is hosted on a machine that can be accessed via cPanel. I've noticed that while you can add "Addon Domains" and "Subdomains" via cPanel, you can't change the root public directory through cPanel. I would like to avoid SSHing into the machine and manually editing the **httpd.conf** file since that can cause conflicts with cPanel. Ideally, I would like to avoid moving files all together and just point Apache's root directory to **/public\_html/development**.
You're onto the answer... The function, `wp_get_attachment_url()` (see [Codex](https://codex.wordpress.org/Function_Reference/wp_get_attachment_url)) just gives you the URL. You could wrap it in a link: ``` echo '<tr><td><a href="' . esc_attr(wp_get_attachment_url($row['item_code1'])) . '">' . esc_html($item_1_title) . '</a></td></tr>'; ``` Alternately, you can use `wp_get_attachment_link()` (see [Codex](https://codex.wordpress.org/Function_Reference/wp_get_attachment_link)) as you mentioned: ``` echo wp_get_attachment_link($row['item_code1'], 'medium', false, false, esc_html($item_1_title)); ``` Neither is specifically better all the time, it'll depend on what you're doing. Keep in mind that if you use the first bit of code above, your `<a>` tag *should* have an `alt` attribute. I believe this is for accessibility. You could use the link text, wrapped in `esc_attr()` for this. **Updated** (after added code module) I've looked at your code. I must be missing something because I don't see anywhere it's rendering `<a>` tags. Going with what you're saying, that they're rendered in the front-end HTML, I'd have to *guess* that someone somewhere has some filter that's modifying what `esc_url()` does. Looking at the [core code](https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/formatting.php#L4171) (line 4171), there's one filter, `clean_url`, that's applied to the output of `esc_url()` before it returns. It's messy and poor according to WP best practices, but I've seen worse than someone editing that to do something like this. You'd probably have to do a text search on the code base (probably `wp-content/plugins`, although that could be a lot of code) to find if there's an instance of this filter being hooked. My spidey sense tells me that this isn't the place to start though. Not to be snarky, and I mean this in the most straightforward way, but I'm not completely sure I understand what you're saying is going wrong. I *think* you mean that the browser is rendering something like this: ``` <td> <a href="http://domain.com/path-to-something">http://domain.com/path-to-something</a> </td> ``` That would seem like the right output *to me,* but you're asking this question because the output isn't right *to you.* This leads me to believe that I don't fully understand the question, reinforced by the fact that I don't understand the thing about pasting a URL into a text box. Could you maybe edit with a snippet of HTML as rendered, and a snippet of HTML as you *want* it rendered? Given the code you posted, I could try to reconcile the two and see what's going on. **Updated** (let's try this) For starters, welcome to WordPress. Also welcome to WP SE. (Your code doesn't show in your post with line numbers so please bear with me.) In the function, `get_assigned_codes`, try changing this line: ``` $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;">' . esc_url( wp_get_attachment_url($code_5_title) ) . '</th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code5'] ) . '</td></tr>'; ``` (it's the third-to-last line in the function that isn't whitespace or curlies) with this: ``` $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;"><a href="' . esc_attr(esc_url(wp_get_attachment_url($code_5_title))) . '">' . esc_url(wp_get_attachment_url($code_5_title)) . '</a></th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code5'] ) . '</td></tr>'; ``` To see if that works, you'll have to go to the right place that uses that function and compare the output. There appear to be a few other places where it's doing about the same thing (hence why you referenced several code lines) but let's try one to see what it does. If you try that, do you get more of what you want? **Updating** (a bit more info but we're onto something) Try this: ``` $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;">' . esc_url( wp_get_attachment_url($code_5_title) ) . '</th><td class="td" scope="col" style="text-align:left;"><a href="' . esc_attr( $row['license_code5'] ) . '">' . esc_html($row['license_code5']) . '</a>&nbsp;<a href="' . esc_attr(wp_get_attachment_url($row['license_code5'])) . '">' . esc_html($row['license_code5']) . '</a></td></tr>'; ``` My apologies, the previous suggestion was incorrect. I put the change in the wrong place. This should print 2 items in the URL field. If either of them is correct, remove the incorrect one and the extra stuff around it. Also, you probably don't need `wp_get_attachment_url()` in the left-hand field.
337,650
<p>I am using CentOS 7 (<code>CentOS Linux release 7.6.1810 (Core)</code>), NGINX 1.15.12, WordPress 5.1</p> <p>Error</p> <blockquote> <p>Update WordPress<br> Downloading update from <a href="https://downloads.wordpress.org/release/wordpress-5.2-no-content.zip" rel="nofollow noreferrer">https://downloads.wordpress.org/release/wordpress-5.2-no-content.zip</a>…</p> <p>Unpacking the update…</p> <p>The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.: wp-admin/includes/update-core.php</p> <p>Installation Failed</p> </blockquote> <p>My screenshoots</p> <p><a href="https://i.stack.imgur.com/cOC9A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cOC9A.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/BwJHX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BwJHX.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/uN9ZL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uN9ZL.png" alt="enter image description here"></a></p>
[ { "answer_id": 337528, "author": "Stephan Samuel", "author_id": 85968, "author_profile": "https://wordpress.stackexchange.com/users/85968", "pm_score": 1, "selected": false, "text": "<p>You're onto the answer...</p>\n\n<p>The function, <code>wp_get_attachment_url()</code> (see <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"nofollow noreferrer\">Codex</a>) just gives you the URL. You could wrap it in a link:</p>\n\n<pre><code>echo '&lt;tr&gt;&lt;td&gt;&lt;a href=\"' . esc_attr(wp_get_attachment_url($row['item_code1'])) . '\"&gt;' . esc_html($item_1_title) . '&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>Alternately, you can use <code>wp_get_attachment_link()</code> (see <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_link\" rel=\"nofollow noreferrer\">Codex</a>) as you mentioned:</p>\n\n<pre><code>echo wp_get_attachment_link($row['item_code1'], 'medium', false, false, esc_html($item_1_title));\n</code></pre>\n\n<p>Neither is specifically better all the time, it'll depend on what you're doing.</p>\n\n<p>Keep in mind that if you use the first bit of code above, your <code>&lt;a&gt;</code> tag <em>should</em> have an <code>alt</code> attribute. I believe this is for accessibility. You could use the link text, wrapped in <code>esc_attr()</code> for this.</p>\n\n<p><strong>Updated</strong> (after added code module)</p>\n\n<p>I've looked at your code.</p>\n\n<p>I must be missing something because I don't see anywhere it's rendering <code>&lt;a&gt;</code> tags. Going with what you're saying, that they're rendered in the front-end HTML, I'd have to <em>guess</em> that someone somewhere has some filter that's modifying what <code>esc_url()</code> does.</p>\n\n<p>Looking at the <a href=\"https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/formatting.php#L4171\" rel=\"nofollow noreferrer\">core code</a> (line 4171), there's one filter, <code>clean_url</code>, that's applied to the output of <code>esc_url()</code> before it returns. It's messy and poor according to WP best practices, but I've seen worse than someone editing that to do something like this. You'd probably have to do a text search on the code base (probably <code>wp-content/plugins</code>, although that could be a lot of code) to find if there's an instance of this filter being hooked. My spidey sense tells me that this isn't the place to start though.</p>\n\n<p>Not to be snarky, and I mean this in the most straightforward way, but I'm not completely sure I understand what you're saying is going wrong. I <em>think</em> you mean that the browser is rendering something like this:</p>\n\n<pre><code>&lt;td&gt;\n &lt;a href=\"http://domain.com/path-to-something\"&gt;http://domain.com/path-to-something&lt;/a&gt;\n&lt;/td&gt;\n</code></pre>\n\n<p>That would seem like the right output <em>to me,</em> but you're asking this question because the output isn't right <em>to you.</em> This leads me to believe that I don't fully understand the question, reinforced by the fact that I don't understand the thing about pasting a URL into a text box.</p>\n\n<p>Could you maybe edit with a snippet of HTML as rendered, and a snippet of HTML as you <em>want</em> it rendered? Given the code you posted, I could try to reconcile the two and see what's going on.</p>\n\n<p><strong>Updated</strong> (let's try this)</p>\n\n<p>For starters, welcome to WordPress. Also welcome to WP SE.</p>\n\n<p>(Your code doesn't show in your post with line numbers so please bear with me.)</p>\n\n<p>In the function, <code>get_assigned_codes</code>, try changing this line:</p>\n\n<pre><code>$codes_table .= '&lt;tr&gt;&lt;th class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_url( wp_get_attachment_url($code_5_title) ) . '&lt;/th&gt;&lt;td class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_html( $row['license_code5'] ) . '&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>(it's the third-to-last line in the function that isn't whitespace or curlies) with this:</p>\n\n<pre><code>$codes_table .= '&lt;tr&gt;&lt;th class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;&lt;a href=\"' . esc_attr(esc_url(wp_get_attachment_url($code_5_title))) . '\"&gt;' . esc_url(wp_get_attachment_url($code_5_title)) . '&lt;/a&gt;&lt;/th&gt;&lt;td class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_html( $row['license_code5'] ) . '&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>To see if that works, you'll have to go to the right place that uses that function and compare the output.</p>\n\n<p>There appear to be a few other places where it's doing about the same thing (hence why you referenced several code lines) but let's try one to see what it does.</p>\n\n<p>If you try that, do you get more of what you want?</p>\n\n<p><strong>Updating</strong> (a bit more info but we're onto something)</p>\n\n<p>Try this:</p>\n\n<pre><code>$codes_table .= '&lt;tr&gt;&lt;th class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;' . esc_url( wp_get_attachment_url($code_5_title) ) . '&lt;/th&gt;&lt;td class=\"td\" scope=\"col\" style=\"text-align:left;\"&gt;&lt;a href=\"' . esc_attr( $row['license_code5'] ) . '\"&gt;' . esc_html($row['license_code5']) . '&lt;/a&gt;&amp;nbsp;&lt;a href=\"' . esc_attr(wp_get_attachment_url($row['license_code5'])) . '\"&gt;' . esc_html($row['license_code5']) . '&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n\n<p>My apologies, the previous suggestion was incorrect. I put the change in the wrong place.</p>\n\n<p>This should print 2 items in the URL field. If either of them is correct, remove the incorrect one and the extra stuff around it. Also, you probably don't need <code>wp_get_attachment_url()</code> in the left-hand field.</p>\n" }, { "answer_id": 337547, "author": "Stephan Samuel", "author_id": 85968, "author_profile": "https://wordpress.stackexchange.com/users/85968", "pm_score": 0, "selected": false, "text": "<p>My previous answer wasn't helping. Let me approach this a different way that may be of some use to someone in the future.</p>\n\n<p><strong>You're coming from Joomla.</strong> It's been forever since I used it but Google tells me it's based on PHP. WP is somewhat object-oriented but I've seen more non-object-oriented plugins than I've seen object-oriented ones.</p>\n\n<p>So you've got a basis in PHP.</p>\n\n<p><strong>A filter</strong> is a thing that lets you modify things at runtime. Filter names are ephemeral but core <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference\" rel=\"nofollow noreferrer\">uses a whole bunch of them</a>. You hook using <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\"><code>add_filter()</code></a> with a priority and a number of arguments. The return value of a filter is always supposed to be of the same type as the first argument, thereby making the remaining arguments modifiers for how the filter is supposed to work. Also, if you call a filter (using <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\"><code>apply_filters()</code></a>) and there are no filters defined, it'll just give you back your argument. <code>add_action()</code> does the same thing without returning a value (PHP void).</p>\n\n<p><strong>The <code>wp_posts</code> table</strong> contains stuff. Some CMS systems do it differently but many just use a big flat table like this. The <code>post_type</code> column tells you what kind of post it is, with <code>post</code> (re-use of the name) being a blog and <code>page</code> being a front-end page. You can <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">define custom post types</a>. Additional metadata about a post is stored in <code>wp_postmeta</code>, using the post ID.</p>\n\n<p>(Tables are prefixed and your prefix may not be <code>wp_</code>. The suffix is the same.)</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_url()</code></a> <strong>takes a post ID</strong> and returns the URL of a post of <code>post_type</code> <code>attachment</code> that's associated with that post. (Therefore, <code>attachment</code> is another core post type.) It returns just the URL, not a link. If you want a link, you have to either use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_link\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_link()</code></a> or draw the link yourself. That's something like this:</p>\n\n<pre><code>?&gt;\n &lt;a href=\"&lt;?php echo wp_get_attachment_link($id); ?&gt;\"&gt;link text&lt;/a&gt;\n&lt;?php\n</code></pre>\n\n<p>I'm not sure which of your variables contains the post ID and which contains the text to display. This is based on how WooCommerce is set up. In WC (it appears as if you're in Europe so please excuse the abbreviation), products are stored as posts. I forgot the exact <code>post_type</code> and I don't have a WC setup handy. Therefore, you're probably looking for the post ID for a product.</p>\n\n<p><strong>You can use direct database access</strong> to get things using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">the <code>wpdb</code> class</a> but the way you're, \"supposed to,\" do it is with <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">the <code>WP_Query</code> class</a>. Instantiate one with an array like so:</p>\n\n<pre><code>$query = new WP_Query(array('post_type' =&gt; 'product', 'nopaging' =&gt; true));\n</code></pre>\n\n<p>Then use <code>$query-&gt;posts</code> to get an array of the matched records.</p>\n\n<p><strong>The helper functions</strong> <a href=\"https://codex.wordpress.org/Function_Reference/esc_html\" rel=\"nofollow noreferrer\"><code>esc_html()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/esc_attr/\" rel=\"nofollow noreferrer\"><code>esc_attr()</code></a> escape text for output for element content and attributes, respectively. <a href=\"https://developer.wordpress.org/reference/functions/esc_url/\" rel=\"nofollow noreferrer\"><code>esc_url()</code></a> is similar. As with any other CMS, never trust anything that comes from the user (even an admin) or the database. These functions help you wrap it.</p>\n\n<p><strong>You can debug</strong> using <code>printf()</code>. <code>print_r()</code> works for arrays and objects. I prefer <code>var_export($object, true)</code> because it always pretty-prints everything. If you can set up your PHP log, <code>error_log()</code> works well (that's what I use). I've never found an IDE that really helps me debug well enough.</p>\n\n<p>That having been said, you're dumping data into an HTML table. Find out (using some debugging method) what your post ID is and what text you want to display. Then use <code>wp_get_attachment_url()</code> with your post ID to get the URL of the image you want to display. If <code>$id</code> has the post ID and <code>$linktext</code> has the link text, do this:</p>\n\n<pre><code>echo '&lt;a href=\"' . esc_attr(wp_get_attachment_url($id)) . '\"&gt;' . $linktext . '&lt;/a&gt;';\n</code></pre>\n\n<p>Stick that somewhere into a <code>&lt;th&gt;</code> or <code>&lt;td&gt;</code> and you'll get a clickable link. If you want to display the image, do this:</p>\n\n<pre><code>echo '&lt;img src=\"' . esc_attr(wp_get_attachment_url($id)) . '\" /&gt;';\n</code></pre>\n\n<p>Hopefully, somewhere in there is all you need to get this to work.</p>\n" } ]
2019/05/11
[ "https://wordpress.stackexchange.com/questions/337650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/164690/" ]
I am using CentOS 7 (`CentOS Linux release 7.6.1810 (Core)`), NGINX 1.15.12, WordPress 5.1 Error > > Update WordPress > > Downloading update from <https://downloads.wordpress.org/release/wordpress-5.2-no-content.zip>… > > > Unpacking the update… > > > The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.: wp-admin/includes/update-core.php > > > Installation Failed > > > My screenshoots [![enter image description here](https://i.stack.imgur.com/cOC9A.png)](https://i.stack.imgur.com/cOC9A.png) [![enter image description here](https://i.stack.imgur.com/BwJHX.png)](https://i.stack.imgur.com/BwJHX.png) [![enter image description here](https://i.stack.imgur.com/uN9ZL.png)](https://i.stack.imgur.com/uN9ZL.png)
You're onto the answer... The function, `wp_get_attachment_url()` (see [Codex](https://codex.wordpress.org/Function_Reference/wp_get_attachment_url)) just gives you the URL. You could wrap it in a link: ``` echo '<tr><td><a href="' . esc_attr(wp_get_attachment_url($row['item_code1'])) . '">' . esc_html($item_1_title) . '</a></td></tr>'; ``` Alternately, you can use `wp_get_attachment_link()` (see [Codex](https://codex.wordpress.org/Function_Reference/wp_get_attachment_link)) as you mentioned: ``` echo wp_get_attachment_link($row['item_code1'], 'medium', false, false, esc_html($item_1_title)); ``` Neither is specifically better all the time, it'll depend on what you're doing. Keep in mind that if you use the first bit of code above, your `<a>` tag *should* have an `alt` attribute. I believe this is for accessibility. You could use the link text, wrapped in `esc_attr()` for this. **Updated** (after added code module) I've looked at your code. I must be missing something because I don't see anywhere it's rendering `<a>` tags. Going with what you're saying, that they're rendered in the front-end HTML, I'd have to *guess* that someone somewhere has some filter that's modifying what `esc_url()` does. Looking at the [core code](https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/formatting.php#L4171) (line 4171), there's one filter, `clean_url`, that's applied to the output of `esc_url()` before it returns. It's messy and poor according to WP best practices, but I've seen worse than someone editing that to do something like this. You'd probably have to do a text search on the code base (probably `wp-content/plugins`, although that could be a lot of code) to find if there's an instance of this filter being hooked. My spidey sense tells me that this isn't the place to start though. Not to be snarky, and I mean this in the most straightforward way, but I'm not completely sure I understand what you're saying is going wrong. I *think* you mean that the browser is rendering something like this: ``` <td> <a href="http://domain.com/path-to-something">http://domain.com/path-to-something</a> </td> ``` That would seem like the right output *to me,* but you're asking this question because the output isn't right *to you.* This leads me to believe that I don't fully understand the question, reinforced by the fact that I don't understand the thing about pasting a URL into a text box. Could you maybe edit with a snippet of HTML as rendered, and a snippet of HTML as you *want* it rendered? Given the code you posted, I could try to reconcile the two and see what's going on. **Updated** (let's try this) For starters, welcome to WordPress. Also welcome to WP SE. (Your code doesn't show in your post with line numbers so please bear with me.) In the function, `get_assigned_codes`, try changing this line: ``` $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;">' . esc_url( wp_get_attachment_url($code_5_title) ) . '</th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code5'] ) . '</td></tr>'; ``` (it's the third-to-last line in the function that isn't whitespace or curlies) with this: ``` $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;"><a href="' . esc_attr(esc_url(wp_get_attachment_url($code_5_title))) . '">' . esc_url(wp_get_attachment_url($code_5_title)) . '</a></th><td class="td" scope="col" style="text-align:left;">' . esc_html( $row['license_code5'] ) . '</td></tr>'; ``` To see if that works, you'll have to go to the right place that uses that function and compare the output. There appear to be a few other places where it's doing about the same thing (hence why you referenced several code lines) but let's try one to see what it does. If you try that, do you get more of what you want? **Updating** (a bit more info but we're onto something) Try this: ``` $codes_table .= '<tr><th class="td" scope="col" style="text-align:left;">' . esc_url( wp_get_attachment_url($code_5_title) ) . '</th><td class="td" scope="col" style="text-align:left;"><a href="' . esc_attr( $row['license_code5'] ) . '">' . esc_html($row['license_code5']) . '</a>&nbsp;<a href="' . esc_attr(wp_get_attachment_url($row['license_code5'])) . '">' . esc_html($row['license_code5']) . '</a></td></tr>'; ``` My apologies, the previous suggestion was incorrect. I put the change in the wrong place. This should print 2 items in the URL field. If either of them is correct, remove the incorrect one and the extra stuff around it. Also, you probably don't need `wp_get_attachment_url()` in the left-hand field.
337,651
<p>How to change / delete product short description in Woocommerce</p> <p>I use</p> <pre><code>$short_desc = $post-&gt;post_excerpt; </code></pre> <p>to read the property but I cant change it with</p> <pre><code> wp_set_object_terms($post-&gt;ID, $post-&gt;post_excerpt, 'new excerpt'); </code></pre>
[ { "answer_id": 337659, "author": "Alexander Holsgrove", "author_id": 48962, "author_profile": "https://wordpress.stackexchange.com/users/48962", "pm_score": 2, "selected": false, "text": "<p>You should have the <code>$product</code> global available to you, which lets you call <a href=\"https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html#_set_short_description\" rel=\"nofollow noreferrer\">set_short_description</a> and then <a href=\"https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html#_save\" rel=\"nofollow noreferrer\">save</a> to store the changes:</p>\n\n<pre><code>$product-&gt;set_short_description('some description');\n$product-&gt;save();\n</code></pre>\n" }, { "answer_id": 337689, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 3, "selected": true, "text": "<p>Th function <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\"><code>wp_set_object_terms()</code></a> will not work to set post object properties.</p>\n\n<p>To add/update/delete product short description <strong>there is mainly 2 ways</strong>:</p>\n\n<p>1) <strong>the WordPress way</strong> from a <strong>post ID</strong> using <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_post\" rel=\"nofollow noreferrer\"><code>wp_update_post()</code></a> function this way:</p>\n\n<pre><code>$product_id = $post-&gt;ID; // or get_the_id() or $product-&gt;get_id() (when $product is available);\n\n// The product short description (for testing)\n$new_short_description = \"&lt;strong&gt;Here&lt;/strong&gt; is is the product short description content.\"\n\n// Add/Update/delete the product short description\nwp_update_post( array('ID' =&gt; $product_id, 'post_excerpt' =&gt; $new_short_description ) );\n</code></pre>\n\n<p>2) <strong>The WooCommerce way</strong> from the <strong><code>WC_product</code> Object</strong> using <a href=\"https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html#_set_short_description\" rel=\"nofollow noreferrer\"><code>set_short_description()</code></a>:</p>\n\n<pre><code>// Optional: get the WC_product Object instance from the post ID\n$product_id = $post-&gt;ID; // or get_the_id()\n$product = wc_get_product( $product_id );\n\n// The product short description (for testing)\n$new_short_description = \"&lt;strong&gt;Here&lt;/strong&gt; is is the product short description content.\"\n\n$product-&gt;set_short_description( $new_short_description ); // Add/Set the new short description\n$product-&gt;save(); // Store changes in database\n</code></pre>\n\n<hr>\n\n<p>To <strong>delete</strong> the product description you will set an <strong>empty string</strong>.</p>\n\n<hr>\n\n<p>Related: <a href=\"https://stackoverflow.com/questions/56022415/how-to-programmatically-get-the-product-description-in-woocommerce/56022850#56022850\">How to programmatically grab the product description in WooCommerce?</a></p>\n" } ]
2019/05/11
[ "https://wordpress.stackexchange.com/questions/337651", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/163748/" ]
How to change / delete product short description in Woocommerce I use ``` $short_desc = $post->post_excerpt; ``` to read the property but I cant change it with ``` wp_set_object_terms($post->ID, $post->post_excerpt, 'new excerpt'); ```
Th function [`wp_set_object_terms()`](https://codex.wordpress.org/Function_Reference/wp_set_object_terms) will not work to set post object properties. To add/update/delete product short description **there is mainly 2 ways**: 1) **the WordPress way** from a **post ID** using [`wp_update_post()`](https://codex.wordpress.org/Function_Reference/wp_update_post) function this way: ``` $product_id = $post->ID; // or get_the_id() or $product->get_id() (when $product is available); // The product short description (for testing) $new_short_description = "<strong>Here</strong> is is the product short description content." // Add/Update/delete the product short description wp_update_post( array('ID' => $product_id, 'post_excerpt' => $new_short_description ) ); ``` 2) **The WooCommerce way** from the **`WC_product` Object** using [`set_short_description()`](https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html#_set_short_description): ``` // Optional: get the WC_product Object instance from the post ID $product_id = $post->ID; // or get_the_id() $product = wc_get_product( $product_id ); // The product short description (for testing) $new_short_description = "<strong>Here</strong> is is the product short description content." $product->set_short_description( $new_short_description ); // Add/Set the new short description $product->save(); // Store changes in database ``` --- To **delete** the product description you will set an **empty string**. --- Related: [How to programmatically grab the product description in WooCommerce?](https://stackoverflow.com/questions/56022415/how-to-programmatically-get-the-product-description-in-woocommerce/56022850#56022850)
337,684
<p>I have a series of image posts displayed on a page of a WP site that uses Bootstrap 4 _ The link to the development site is also online <a href="http://inputforcolor.net/wpstudio/paintings/" rel="nofollow noreferrer">here</a> </p> <p>The images normally display in a larger size when they're clicked on but I want to display them in a dropdown modal _ The problem is that when I implement the modal it only displays the last post on the page NOT the image that was clicked on _ </p> <p>I realise this is because I need to get the post ID and add the same ID to the modal code _ However, I have tried several ways of doing this but not been successful </p> <p>this is the code I currently have on the page >>></p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="container fadeIn" id="perimeter"&gt; &lt;section class="gallery" id="mainGallery"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;?php $featured_query = new WP_Query( array( 'category_name' =&gt; 'canvas' )); ?&gt; &lt;?php while($featured_query-&gt;have_posts()) : $featured_query-&gt;the_post(); ?&gt; &lt;div class="col-md-6"&gt; &lt;div class="divPad"&gt; &lt;a data-toggle="modal" data-target="#galleryModal" href="&lt;?php echo the_permalink(); ?&gt;"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;?php $post_id = get_the_ID(); ?&gt; &lt;/a&gt; &lt;br /&gt; &lt;span class="fontBrand1 fontType1 text"&gt;&lt;?php echo the_title(); ?&gt;&lt;/span&gt; &lt;span class="fontBrand2 fontOpenSans smallText"&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'Materials', true); ?&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'Dimensions', true); ?&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'Price', true); ?&gt;&lt;/span&gt; &lt;/div&gt;&lt;!-- /.divPad --&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt;&lt;!-- /.row --&gt; &lt;/div&gt;&lt;!-- /.container --&gt; &lt;/section&gt;&lt;!-- /#mainGallery --&gt; &lt;div class="horizBuffer2"&gt;&lt;/div&gt; &lt;/div&gt;&lt;!-- /#perimeter --&gt; &lt;!-- modal --&gt; &lt;div class="modal fade" id="galleryModal" tabindex="-1" role="dialog" aria-labelledby="galleryModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog modal-lg" role="document"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;h5 class="modal-title" id="galleryModalLabel"&gt;Modal title&lt;/h5&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt; &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-secondary" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- /.modal-content --&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- /#galleryModal --&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>Any help would be greatly appreciated _ thanks </p>
[ { "answer_id": 337690, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>I realise this is because I need to get the post ID and add the same\n ID to the modal code</p>\n</blockquote>\n\n<p>No, that's not true in your case. If you want to use a <em>single</em> modal for all the different images &mdash; i.e. a different image is displayed in the modal <em>based on the button/link which triggers the modal</em> (or simply, the button/link that was clicked), you need JavaScript to achieve that, just as what stated in the <a href=\"https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content\" rel=\"nofollow noreferrer\">Bootstrap 4's Modal documentation</a> &mdash; and after all, the modal itself is a JavaScript plugin:</p>\n\n<blockquote>\n <h2>Varying modal content</h2>\n \n <p>Have a bunch of buttons that all trigger the same modal with slightly\n different contents? Use <code>event.relatedTarget</code> and HTML <code>data-*</code>\n attributes (possibly via jQuery) to vary the contents of the modal\n depending on which button was clicked.</p>\n</blockquote>\n\n<p>So based on the example <a href=\"https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content\" rel=\"nofollow noreferrer\">there</a> and your code:</p>\n\n<p><strong>Option 1:</strong> You can simply use this script to replace the modal content with the inner HTML of the button/link which triggers the modal:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>jQuery( function( $ ){\n $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) {\n var button = $( event.relatedTarget ); // Button/link that triggered the modal\n var modal = $( this );\n\n // Update the modal's content.\n modal.find('.modal-body').html(\n button.html()\n );\n });\n});\n</code></pre>\n\n<p><strong>Option 2:</strong> Or use the <code>data-*</code> attribute for more control such as displaying a larger preview of the post thumbnail. And here I use <code>data-image</code> and <code>large</code> as the thumbnail size:</p>\n\n<ol>\n<li><p>Add the <code>data-image</code>: (wrapped for clarity)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;a data-toggle=\"modal\" data-target=\"#galleryModal\" href=\"&lt;?php echo the_permalink(); ?&gt;\"\n data-image=\"&lt;?php the_post_thumbnail_url( 'large' ); ?&gt;\"&gt;\n</code></pre>\n\n<p><em>See the <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail_url/\" rel=\"nofollow noreferrer\">reference</a> if you need help with the <code>the_post_thumbnail_url()</code>.</em></p></li>\n<li><p>Add the script: (take note of the new <code>image</code> variable)</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>jQuery( function( $ ){\n $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) {\n var button = $( event.relatedTarget ); // Button/link that triggered the modal\n var image = button.data( 'image' ); // Get the image URL from the data-image\n // attribute of the button/link above.\n var modal = $( this );\n\n // Update the modal's content.\n modal.find('.modal-body').html(\n '&lt;img src=\"' + image + '\" alt=\"\" /&gt;'\n );\n });\n});\n</code></pre></li>\n</ol>\n\n<p>Note that you should place the script in an external JavaScript file (e.g. in <code>wp-content/themes/your-theme/custom.js</code>) and load the file via the theme's <code>functions.php</code> file. Or wrap the script code with <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> tags and then add the script in the <code>footer.php</code> or <code>header.php</code> file. ( Check <a href=\"https://www.wpbeginner.com/wp-tutorials/how-to-easily-add-javascript-in-wordpress-pages-or-posts/\" rel=\"nofollow noreferrer\">this article</a> if you need help. You can also search on WPSE. :) )</p>\n\n<p>And in the <code>modal-body</code> DIV, you don't need the <code>the_post_thumbnail()</code>.. or you can change it to <code>Loading...</code> or display a \"special\" image/content which serves similar purposes like a video's poster image. But then, it's just a <em>suggestion</em>. =)</p>\n" }, { "answer_id": 409899, "author": "Alexandre Rodrigues", "author_id": 226152, "author_profile": "https://wordpress.stackexchange.com/users/226152", "pm_score": 1, "selected": false, "text": "<p>i has trying to create a wordpress buit-in gallery and open a entire page on bostrap modal; When the modal was open the gallery show with issue. All images displayed one below another and i fugred out how fix. just add this css</p>\n<pre><code>/* FIX GALLERY MODAL BUG */\n.wp-block-gallery {\n display: flex!important;\n gap: 0.5em;\n flex-wrap: wrap;\n align-items: center;\n}\n</code></pre>\n" } ]
2019/05/11
[ "https://wordpress.stackexchange.com/questions/337684", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114778/" ]
I have a series of image posts displayed on a page of a WP site that uses Bootstrap 4 \_ The link to the development site is also online [here](http://inputforcolor.net/wpstudio/paintings/) The images normally display in a larger size when they're clicked on but I want to display them in a dropdown modal \_ The problem is that when I implement the modal it only displays the last post on the page NOT the image that was clicked on \_ I realise this is because I need to get the post ID and add the same ID to the modal code \_ However, I have tried several ways of doing this but not been successful this is the code I currently have on the page >>> ``` <?php get_header(); ?> <div class="container fadeIn" id="perimeter"> <section class="gallery" id="mainGallery"> <div class="container"> <div class="row"> <?php $featured_query = new WP_Query( array( 'category_name' => 'canvas' )); ?> <?php while($featured_query->have_posts()) : $featured_query->the_post(); ?> <div class="col-md-6"> <div class="divPad"> <a data-toggle="modal" data-target="#galleryModal" href="<?php echo the_permalink(); ?>"> <?php the_post_thumbnail(); ?> <?php $post_id = get_the_ID(); ?> </a> <br /> <span class="fontBrand1 fontType1 text"><?php echo the_title(); ?></span> <span class="fontBrand2 fontOpenSans smallText"><?php echo get_post_meta($post->ID, 'Materials', true); ?><?php echo get_post_meta($post->ID, 'Dimensions', true); ?><?php echo get_post_meta($post->ID, 'Price', true); ?></span> </div><!-- /.divPad --> </div> <?php endwhile; ?> </div><!-- /.row --> </div><!-- /.container --> </section><!-- /#mainGallery --> <div class="horizBuffer2"></div> </div><!-- /#perimeter --> <!-- modal --> <div class="modal fade" id="galleryModal" tabindex="-1" role="dialog" aria-labelledby="galleryModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="galleryModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <?php the_post_thumbnail(); ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div> </div><!-- /#galleryModal --> <?php get_footer(); ?> ``` Any help would be greatly appreciated \_ thanks
> > I realise this is because I need to get the post ID and add the same > ID to the modal code > > > No, that's not true in your case. If you want to use a *single* modal for all the different images — i.e. a different image is displayed in the modal *based on the button/link which triggers the modal* (or simply, the button/link that was clicked), you need JavaScript to achieve that, just as what stated in the [Bootstrap 4's Modal documentation](https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content) — and after all, the modal itself is a JavaScript plugin: > > Varying modal content > --------------------- > > > Have a bunch of buttons that all trigger the same modal with slightly > different contents? Use `event.relatedTarget` and HTML `data-*` > attributes (possibly via jQuery) to vary the contents of the modal > depending on which button was clicked. > > > So based on the example [there](https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content) and your code: **Option 1:** You can simply use this script to replace the modal content with the inner HTML of the button/link which triggers the modal: ```js jQuery( function( $ ){ $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) { var button = $( event.relatedTarget ); // Button/link that triggered the modal var modal = $( this ); // Update the modal's content. modal.find('.modal-body').html( button.html() ); }); }); ``` **Option 2:** Or use the `data-*` attribute for more control such as displaying a larger preview of the post thumbnail. And here I use `data-image` and `large` as the thumbnail size: 1. Add the `data-image`: (wrapped for clarity) ```php <a data-toggle="modal" data-target="#galleryModal" href="<?php echo the_permalink(); ?>" data-image="<?php the_post_thumbnail_url( 'large' ); ?>"> ``` *See the [reference](https://developer.wordpress.org/reference/functions/the_post_thumbnail_url/) if you need help with the `the_post_thumbnail_url()`.* 2. Add the script: (take note of the new `image` variable) ```js jQuery( function( $ ){ $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) { var button = $( event.relatedTarget ); // Button/link that triggered the modal var image = button.data( 'image' ); // Get the image URL from the data-image // attribute of the button/link above. var modal = $( this ); // Update the modal's content. modal.find('.modal-body').html( '<img src="' + image + '" alt="" />' ); }); }); ``` Note that you should place the script in an external JavaScript file (e.g. in `wp-content/themes/your-theme/custom.js`) and load the file via the theme's `functions.php` file. Or wrap the script code with `<script>` and `</script>` tags and then add the script in the `footer.php` or `header.php` file. ( Check [this article](https://www.wpbeginner.com/wp-tutorials/how-to-easily-add-javascript-in-wordpress-pages-or-posts/) if you need help. You can also search on WPSE. :) ) And in the `modal-body` DIV, you don't need the `the_post_thumbnail()`.. or you can change it to `Loading...` or display a "special" image/content which serves similar purposes like a video's poster image. But then, it's just a *suggestion*. =)
337,708
<p>i had a wordpress website on xampp let's say in "localhost/listing" and it was working perfectly then i installed another copy of this website on "localhost/mylisting" now the problem is that when i type "localhost/listing/wp-admin" the site redirects itself to "localhost/mylisting/wp-admin" i dont know how to solve this problem. i tried making another directory and copying all contents on listing in it and the problem was same.</p>
[ { "answer_id": 337690, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>I realise this is because I need to get the post ID and add the same\n ID to the modal code</p>\n</blockquote>\n\n<p>No, that's not true in your case. If you want to use a <em>single</em> modal for all the different images &mdash; i.e. a different image is displayed in the modal <em>based on the button/link which triggers the modal</em> (or simply, the button/link that was clicked), you need JavaScript to achieve that, just as what stated in the <a href=\"https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content\" rel=\"nofollow noreferrer\">Bootstrap 4's Modal documentation</a> &mdash; and after all, the modal itself is a JavaScript plugin:</p>\n\n<blockquote>\n <h2>Varying modal content</h2>\n \n <p>Have a bunch of buttons that all trigger the same modal with slightly\n different contents? Use <code>event.relatedTarget</code> and HTML <code>data-*</code>\n attributes (possibly via jQuery) to vary the contents of the modal\n depending on which button was clicked.</p>\n</blockquote>\n\n<p>So based on the example <a href=\"https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content\" rel=\"nofollow noreferrer\">there</a> and your code:</p>\n\n<p><strong>Option 1:</strong> You can simply use this script to replace the modal content with the inner HTML of the button/link which triggers the modal:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>jQuery( function( $ ){\n $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) {\n var button = $( event.relatedTarget ); // Button/link that triggered the modal\n var modal = $( this );\n\n // Update the modal's content.\n modal.find('.modal-body').html(\n button.html()\n );\n });\n});\n</code></pre>\n\n<p><strong>Option 2:</strong> Or use the <code>data-*</code> attribute for more control such as displaying a larger preview of the post thumbnail. And here I use <code>data-image</code> and <code>large</code> as the thumbnail size:</p>\n\n<ol>\n<li><p>Add the <code>data-image</code>: (wrapped for clarity)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;a data-toggle=\"modal\" data-target=\"#galleryModal\" href=\"&lt;?php echo the_permalink(); ?&gt;\"\n data-image=\"&lt;?php the_post_thumbnail_url( 'large' ); ?&gt;\"&gt;\n</code></pre>\n\n<p><em>See the <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail_url/\" rel=\"nofollow noreferrer\">reference</a> if you need help with the <code>the_post_thumbnail_url()</code>.</em></p></li>\n<li><p>Add the script: (take note of the new <code>image</code> variable)</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>jQuery( function( $ ){\n $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) {\n var button = $( event.relatedTarget ); // Button/link that triggered the modal\n var image = button.data( 'image' ); // Get the image URL from the data-image\n // attribute of the button/link above.\n var modal = $( this );\n\n // Update the modal's content.\n modal.find('.modal-body').html(\n '&lt;img src=\"' + image + '\" alt=\"\" /&gt;'\n );\n });\n});\n</code></pre></li>\n</ol>\n\n<p>Note that you should place the script in an external JavaScript file (e.g. in <code>wp-content/themes/your-theme/custom.js</code>) and load the file via the theme's <code>functions.php</code> file. Or wrap the script code with <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> tags and then add the script in the <code>footer.php</code> or <code>header.php</code> file. ( Check <a href=\"https://www.wpbeginner.com/wp-tutorials/how-to-easily-add-javascript-in-wordpress-pages-or-posts/\" rel=\"nofollow noreferrer\">this article</a> if you need help. You can also search on WPSE. :) )</p>\n\n<p>And in the <code>modal-body</code> DIV, you don't need the <code>the_post_thumbnail()</code>.. or you can change it to <code>Loading...</code> or display a \"special\" image/content which serves similar purposes like a video's poster image. But then, it's just a <em>suggestion</em>. =)</p>\n" }, { "answer_id": 409899, "author": "Alexandre Rodrigues", "author_id": 226152, "author_profile": "https://wordpress.stackexchange.com/users/226152", "pm_score": 1, "selected": false, "text": "<p>i has trying to create a wordpress buit-in gallery and open a entire page on bostrap modal; When the modal was open the gallery show with issue. All images displayed one below another and i fugred out how fix. just add this css</p>\n<pre><code>/* FIX GALLERY MODAL BUG */\n.wp-block-gallery {\n display: flex!important;\n gap: 0.5em;\n flex-wrap: wrap;\n align-items: center;\n}\n</code></pre>\n" } ]
2019/05/12
[ "https://wordpress.stackexchange.com/questions/337708", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167857/" ]
i had a wordpress website on xampp let's say in "localhost/listing" and it was working perfectly then i installed another copy of this website on "localhost/mylisting" now the problem is that when i type "localhost/listing/wp-admin" the site redirects itself to "localhost/mylisting/wp-admin" i dont know how to solve this problem. i tried making another directory and copying all contents on listing in it and the problem was same.
> > I realise this is because I need to get the post ID and add the same > ID to the modal code > > > No, that's not true in your case. If you want to use a *single* modal for all the different images — i.e. a different image is displayed in the modal *based on the button/link which triggers the modal* (or simply, the button/link that was clicked), you need JavaScript to achieve that, just as what stated in the [Bootstrap 4's Modal documentation](https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content) — and after all, the modal itself is a JavaScript plugin: > > Varying modal content > --------------------- > > > Have a bunch of buttons that all trigger the same modal with slightly > different contents? Use `event.relatedTarget` and HTML `data-*` > attributes (possibly via jQuery) to vary the contents of the modal > depending on which button was clicked. > > > So based on the example [there](https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content) and your code: **Option 1:** You can simply use this script to replace the modal content with the inner HTML of the button/link which triggers the modal: ```js jQuery( function( $ ){ $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) { var button = $( event.relatedTarget ); // Button/link that triggered the modal var modal = $( this ); // Update the modal's content. modal.find('.modal-body').html( button.html() ); }); }); ``` **Option 2:** Or use the `data-*` attribute for more control such as displaying a larger preview of the post thumbnail. And here I use `data-image` and `large` as the thumbnail size: 1. Add the `data-image`: (wrapped for clarity) ```php <a data-toggle="modal" data-target="#galleryModal" href="<?php echo the_permalink(); ?>" data-image="<?php the_post_thumbnail_url( 'large' ); ?>"> ``` *See the [reference](https://developer.wordpress.org/reference/functions/the_post_thumbnail_url/) if you need help with the `the_post_thumbnail_url()`.* 2. Add the script: (take note of the new `image` variable) ```js jQuery( function( $ ){ $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) { var button = $( event.relatedTarget ); // Button/link that triggered the modal var image = button.data( 'image' ); // Get the image URL from the data-image // attribute of the button/link above. var modal = $( this ); // Update the modal's content. modal.find('.modal-body').html( '<img src="' + image + '" alt="" />' ); }); }); ``` Note that you should place the script in an external JavaScript file (e.g. in `wp-content/themes/your-theme/custom.js`) and load the file via the theme's `functions.php` file. Or wrap the script code with `<script>` and `</script>` tags and then add the script in the `footer.php` or `header.php` file. ( Check [this article](https://www.wpbeginner.com/wp-tutorials/how-to-easily-add-javascript-in-wordpress-pages-or-posts/) if you need help. You can also search on WPSE. :) ) And in the `modal-body` DIV, you don't need the `the_post_thumbnail()`.. or you can change it to `Loading...` or display a "special" image/content which serves similar purposes like a video's poster image. But then, it's just a *suggestion*. =)
337,775
<p>I've currently got some custom theme functions running (custom single product page and java script) although want to exclude a specific category from them. How do I go about this?</p> <p>I currently have implemented a calculator into my single product using the following script;</p> <pre><code>add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); function my_scripts_method(){ wp_enqueue_script( 'calc_fun', '/wp-content/themes/flatsome-child/assets/js/calc.js', array(), '1.6'); wp_enqueue_style( 'calc_css', '/wp-content/themes/flatsome-child/assets/css/calc.css', true , 9.1 ); } </code></pre> <p>This calculator features on the single product page and works out quantity and m2 of products. This calculator is tied in with a custom single product page using the following scripts;</p> <pre><code>add_action( 'woocommerce_before_add_to_cart_button', 'add_content_before_addtocart_button_func' ); add_action( 'woocommerce_before_add_to_cart_button', 'add_content_after_addtocart_button_func' ); add_action('woocommerce_after_add_to_cart_button', 'add_content_after_true_addtocart_button_func'); add_action('woocommerce_shop_loop_item_title', 'add_woo_shop_loop_item_title'); function add_content_before_addtocart_button_func() { // Echo content. get_template_part( 'woo-singlre-product-card', 'template' ); } function add_content_after_addtocart_button_func() { // Echo content. get_template_part( 'woo-singlre-product-card-after', 'template' ); } function add_content_after_true_addtocart_button_func(){ get_template_part( 'woo-after-single-product', 'template'); } function add_woo_shop_loop_item_title() { get_template_part( 'woo-shop-loop-item-title', 'template'); } add_action( 'woocommerce_after_shop_loop_item_title', 'custom_add_product_description'); function custom_add_product_description ($category) { get_template_part( 'woo-shop-loop-card-after', 'template' ); } </code></pre> <p>I want to exclude these scripts from the specific category 'example'.</p>
[ { "answer_id": 337690, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>I realise this is because I need to get the post ID and add the same\n ID to the modal code</p>\n</blockquote>\n\n<p>No, that's not true in your case. If you want to use a <em>single</em> modal for all the different images &mdash; i.e. a different image is displayed in the modal <em>based on the button/link which triggers the modal</em> (or simply, the button/link that was clicked), you need JavaScript to achieve that, just as what stated in the <a href=\"https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content\" rel=\"nofollow noreferrer\">Bootstrap 4's Modal documentation</a> &mdash; and after all, the modal itself is a JavaScript plugin:</p>\n\n<blockquote>\n <h2>Varying modal content</h2>\n \n <p>Have a bunch of buttons that all trigger the same modal with slightly\n different contents? Use <code>event.relatedTarget</code> and HTML <code>data-*</code>\n attributes (possibly via jQuery) to vary the contents of the modal\n depending on which button was clicked.</p>\n</blockquote>\n\n<p>So based on the example <a href=\"https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content\" rel=\"nofollow noreferrer\">there</a> and your code:</p>\n\n<p><strong>Option 1:</strong> You can simply use this script to replace the modal content with the inner HTML of the button/link which triggers the modal:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>jQuery( function( $ ){\n $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) {\n var button = $( event.relatedTarget ); // Button/link that triggered the modal\n var modal = $( this );\n\n // Update the modal's content.\n modal.find('.modal-body').html(\n button.html()\n );\n });\n});\n</code></pre>\n\n<p><strong>Option 2:</strong> Or use the <code>data-*</code> attribute for more control such as displaying a larger preview of the post thumbnail. And here I use <code>data-image</code> and <code>large</code> as the thumbnail size:</p>\n\n<ol>\n<li><p>Add the <code>data-image</code>: (wrapped for clarity)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;a data-toggle=\"modal\" data-target=\"#galleryModal\" href=\"&lt;?php echo the_permalink(); ?&gt;\"\n data-image=\"&lt;?php the_post_thumbnail_url( 'large' ); ?&gt;\"&gt;\n</code></pre>\n\n<p><em>See the <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail_url/\" rel=\"nofollow noreferrer\">reference</a> if you need help with the <code>the_post_thumbnail_url()</code>.</em></p></li>\n<li><p>Add the script: (take note of the new <code>image</code> variable)</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>jQuery( function( $ ){\n $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) {\n var button = $( event.relatedTarget ); // Button/link that triggered the modal\n var image = button.data( 'image' ); // Get the image URL from the data-image\n // attribute of the button/link above.\n var modal = $( this );\n\n // Update the modal's content.\n modal.find('.modal-body').html(\n '&lt;img src=\"' + image + '\" alt=\"\" /&gt;'\n );\n });\n});\n</code></pre></li>\n</ol>\n\n<p>Note that you should place the script in an external JavaScript file (e.g. in <code>wp-content/themes/your-theme/custom.js</code>) and load the file via the theme's <code>functions.php</code> file. Or wrap the script code with <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> tags and then add the script in the <code>footer.php</code> or <code>header.php</code> file. ( Check <a href=\"https://www.wpbeginner.com/wp-tutorials/how-to-easily-add-javascript-in-wordpress-pages-or-posts/\" rel=\"nofollow noreferrer\">this article</a> if you need help. You can also search on WPSE. :) )</p>\n\n<p>And in the <code>modal-body</code> DIV, you don't need the <code>the_post_thumbnail()</code>.. or you can change it to <code>Loading...</code> or display a \"special\" image/content which serves similar purposes like a video's poster image. But then, it's just a <em>suggestion</em>. =)</p>\n" }, { "answer_id": 409899, "author": "Alexandre Rodrigues", "author_id": 226152, "author_profile": "https://wordpress.stackexchange.com/users/226152", "pm_score": 1, "selected": false, "text": "<p>i has trying to create a wordpress buit-in gallery and open a entire page on bostrap modal; When the modal was open the gallery show with issue. All images displayed one below another and i fugred out how fix. just add this css</p>\n<pre><code>/* FIX GALLERY MODAL BUG */\n.wp-block-gallery {\n display: flex!important;\n gap: 0.5em;\n flex-wrap: wrap;\n align-items: center;\n}\n</code></pre>\n" } ]
2019/05/13
[ "https://wordpress.stackexchange.com/questions/337775", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167917/" ]
I've currently got some custom theme functions running (custom single product page and java script) although want to exclude a specific category from them. How do I go about this? I currently have implemented a calculator into my single product using the following script; ``` add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); function my_scripts_method(){ wp_enqueue_script( 'calc_fun', '/wp-content/themes/flatsome-child/assets/js/calc.js', array(), '1.6'); wp_enqueue_style( 'calc_css', '/wp-content/themes/flatsome-child/assets/css/calc.css', true , 9.1 ); } ``` This calculator features on the single product page and works out quantity and m2 of products. This calculator is tied in with a custom single product page using the following scripts; ``` add_action( 'woocommerce_before_add_to_cart_button', 'add_content_before_addtocart_button_func' ); add_action( 'woocommerce_before_add_to_cart_button', 'add_content_after_addtocart_button_func' ); add_action('woocommerce_after_add_to_cart_button', 'add_content_after_true_addtocart_button_func'); add_action('woocommerce_shop_loop_item_title', 'add_woo_shop_loop_item_title'); function add_content_before_addtocart_button_func() { // Echo content. get_template_part( 'woo-singlre-product-card', 'template' ); } function add_content_after_addtocart_button_func() { // Echo content. get_template_part( 'woo-singlre-product-card-after', 'template' ); } function add_content_after_true_addtocart_button_func(){ get_template_part( 'woo-after-single-product', 'template'); } function add_woo_shop_loop_item_title() { get_template_part( 'woo-shop-loop-item-title', 'template'); } add_action( 'woocommerce_after_shop_loop_item_title', 'custom_add_product_description'); function custom_add_product_description ($category) { get_template_part( 'woo-shop-loop-card-after', 'template' ); } ``` I want to exclude these scripts from the specific category 'example'.
> > I realise this is because I need to get the post ID and add the same > ID to the modal code > > > No, that's not true in your case. If you want to use a *single* modal for all the different images — i.e. a different image is displayed in the modal *based on the button/link which triggers the modal* (or simply, the button/link that was clicked), you need JavaScript to achieve that, just as what stated in the [Bootstrap 4's Modal documentation](https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content) — and after all, the modal itself is a JavaScript plugin: > > Varying modal content > --------------------- > > > Have a bunch of buttons that all trigger the same modal with slightly > different contents? Use `event.relatedTarget` and HTML `data-*` > attributes (possibly via jQuery) to vary the contents of the modal > depending on which button was clicked. > > > So based on the example [there](https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content) and your code: **Option 1:** You can simply use this script to replace the modal content with the inner HTML of the button/link which triggers the modal: ```js jQuery( function( $ ){ $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) { var button = $( event.relatedTarget ); // Button/link that triggered the modal var modal = $( this ); // Update the modal's content. modal.find('.modal-body').html( button.html() ); }); }); ``` **Option 2:** Or use the `data-*` attribute for more control such as displaying a larger preview of the post thumbnail. And here I use `data-image` and `large` as the thumbnail size: 1. Add the `data-image`: (wrapped for clarity) ```php <a data-toggle="modal" data-target="#galleryModal" href="<?php echo the_permalink(); ?>" data-image="<?php the_post_thumbnail_url( 'large' ); ?>"> ``` *See the [reference](https://developer.wordpress.org/reference/functions/the_post_thumbnail_url/) if you need help with the `the_post_thumbnail_url()`.* 2. Add the script: (take note of the new `image` variable) ```js jQuery( function( $ ){ $( '#galleryModal' ).on( 'show.bs.modal', function ( event ) { var button = $( event.relatedTarget ); // Button/link that triggered the modal var image = button.data( 'image' ); // Get the image URL from the data-image // attribute of the button/link above. var modal = $( this ); // Update the modal's content. modal.find('.modal-body').html( '<img src="' + image + '" alt="" />' ); }); }); ``` Note that you should place the script in an external JavaScript file (e.g. in `wp-content/themes/your-theme/custom.js`) and load the file via the theme's `functions.php` file. Or wrap the script code with `<script>` and `</script>` tags and then add the script in the `footer.php` or `header.php` file. ( Check [this article](https://www.wpbeginner.com/wp-tutorials/how-to-easily-add-javascript-in-wordpress-pages-or-posts/) if you need help. You can also search on WPSE. :) ) And in the `modal-body` DIV, you don't need the `the_post_thumbnail()`.. or you can change it to `Loading...` or display a "special" image/content which serves similar purposes like a video's poster image. But then, it's just a *suggestion*. =)
337,795
<p>A little long-winded but trying to explain clearly :)</p> <p>I am delving into the code of my new theme and am not familiar with this type of data storing/pulling - can someone help me understand what is going on here please:</p> <p>I am trying to create a page which outputs only the posts which have a 'coupon' attached to it. 'Coupon' is stored as a meta_key against a post.</p> <p>It's <code>meta_value</code> is stored as an array which looks like this (output using <em>print_r</em>):</p> <blockquote> <p>a:7:{s:9:"highlight";s:14:"Test Highlight";s:5:"title";s:12:"50% off food";s:11:"description";s:16:"Test description";s:4:"code";s:7:"1524521";s:11:"popup_image";s:4:"4548";s:17:"popup_description";s:17:"Popup description";s:11:"redirect_to";s:0:"";}</p> </blockquote> <p>I want the custom page to output:</p> <ul> <li>Post title</li> <li>Post content</li> <li>Post image</li> <li>Coupon details</li> </ul> <hr> <p>I can output the first three by running a wp_query:</p> <pre><code>$q = new WP_Query(array( 'post_type' =&gt; 'listing', 'posts_per_page' =&gt; 5, 'meta_key' =&gt; 'wc_coupon', 'meta_value' =&gt; ' ', 'meta_compare' =&gt; '!=' )); </code></pre> <p>However, I cannot find a way to split out the <code>meta_value</code> array to display the individual elements per post.</p> <hr> <p>The theme handles this in a way I don't understand, perhaps someone can explain it to me.</p> <p><code>Coupon.php</code> is a partial file which is used when displaying any single post which looks like this:</p> <pre><code>global $post, $Args; use ListingTools\Framework\Helpers\GetSettings; $aCoupon = GetSettings::getPostMeta($post-&gt;ID, 'coupon'); if ( empty($aCoupon) || ( empty($aCoupon['code']) &amp;&amp; empty($aCoupon['redirect_to']) ) ){ return ''; } ?&gt; &lt;div class="content-box_module__333d9"&gt; &lt;div class="content-box_body__3tSRB"&gt; &lt;?php echo do_shortcode('[get_coupon highlight="'.esc_attr($aCoupon['highlight']).'" title="'.esc_attr($aCoupon['title']).'" description="'.esc_attr($aCoupon['description']).'" code="'.esc_attr($aCoupon['code']).'" redirect_to="'.esc_attr($aCoupon['redirect_to']).'"]'); ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <hr> <p>So I don't understand how the "use" code works at the top in the variables section.</p> <p>I also don't understand how the <code>$aCoupon = GetSettings::getPostMeta($post-&gt;ID, 'coupon');</code> is working, but they can use this to display the individual parts of the coupon array as you can see later in the code:</p> <pre><code>echo do_shortcode('[get_coupon highlight="'.esc_attr($aCoupon['highlight']) </code></pre> <p>Hopefully that was follow-able :)</p> <p>Thanks in advance.</p>
[ { "answer_id": 337802, "author": "Warwick", "author_id": 19554, "author_profile": "https://wordpress.stackexchange.com/users/19554", "pm_score": 2, "selected": true, "text": "<p>The string you are outputting using <code>print_r()</code> is what is known as a serialized string. When WordPress stores an array of values in 1 custom field, it compresses the array into this string using a function called <a href=\"https://www.w3resource.com/php/function-reference/serialize.php\" rel=\"nofollow noreferrer\">serialize()</a></p>\n\n<p>What you want to do is to <code>unserialize</code> the string, and then you can access each \"associated index\" in the array.</p>\n\n<p>Usually <code>get_post_meta()</code> unserializes the string for you, but it looks like the custom function <code>GetSettings::getPostMeta()</code> does not. In this case we can run <code>maybe_unserialize()</code> which will convert it into a usable array if it is able to.</p>\n\n<p>Then we can simply loop through the array, outputting what you need to.</p>\n\n<pre><code>$aCoupon = GetSettings::getPostMeta($post-&gt;ID, 'coupon');\n$aCoupon = maybe_unserialze( $aCoupon );\nif ( empty( $aCoupon ) ){\n foreach ( $aCoupon as $key =&gt; $value ) {\n echo '&lt;div&gt;&lt;span class=\"label\"&gt;' . $key . '&lt;/span&gt; ' . $value . '&lt;/div&gt;';\n }\n}\n</code></pre>\n\n<p>Based on your example, it would output something like this.</p>\n\n<pre><code>&lt;div&gt;&lt;span class=\"label\"&gt;highlight&lt;/span&gt; Test Highlight&lt;/div&gt;\n&lt;div&gt;&lt;span class=\"label\"&gt;title&lt;/span&gt; 50% off food&lt;/div&gt;\n&lt;div&gt;&lt;span class=\"label\"&gt;description&lt;/span&gt; Test description&lt;/div&gt;\n&lt;div&gt;&lt;span class=\"label\"&gt;code&lt;/span&gt; 1524521&lt;/div&gt;\n&lt;div&gt;&lt;span class=\"label\"&gt;popup_image&lt;/span&gt; 4548&lt;/div&gt;\n&lt;div&gt;&lt;span class=\"label\"&gt;popup_description&lt;/span&gt; Popup description&lt;/div&gt;\n&lt;div&gt;&lt;span class=\"label\"&gt;redirect_to&lt;/span&gt; &lt;/div&gt;\n</code></pre>\n\n<p>Or if you want to access 1 value directly.</p>\n\n<pre><code>$aCoupon = GetSettings::getPostMeta($post-&gt;ID, 'coupon');\n$aCoupon = maybe_unserialze( $aCoupon );\nif ( empty( $aCoupon ) ){\n //If the title is set, and is not empty, output it.\n if ( isset( $aCoupon['title'] ) &amp;&amp; '' !== $aCoupon['title'] ) {\n echo '&lt;div&gt;&lt;span class=\"label\"&gt;Title&lt;/span&gt; ' . $aCoupon['title'] . '&lt;/div&gt;';\n }\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT by @Shaun21uk - I got it to work making some minor changes (full code below). For whatever reason the <code>$aCoupon = GetSettings::getPostMeta($coupon_id, 'coupon');</code> was breaking the function - I still would like to know how to tap into the theme's way of handling data.</p>\n\n<p>Your shortcode function should look something like this:</p>\n\n<pre><code>add_shortcode( 'qg_shortcode', 'qg_shortcode' );\nfunction qg_shortcode() {\n\n $q = new WP_Query(array(\n 'post_type' =&gt; 'listing',\n 'posts_per_page' =&gt; 5,\n 'meta_key' =&gt; 'wc_coupon',\n 'meta_value' =&gt; ' ',\n 'meta_compare' =&gt; '!='\n ));\n\n if ( $q-&gt;have_posts() ) :\n while ( $q-&gt;have_posts() ) : $q-&gt;the_post();\n\n echo '&lt;h2 class=\"text-center\"&gt;&lt;a href=\"' . get_permalink() . '\"&gt;';\n the_title();\n echo '&lt;/a&gt;&lt;/h2&gt;';\n\n the_content();\n\n // Get the ID of the attached coupon.\n $coupon_id = get_post_meta( get_the_ID(), 'wc_coupon', true );\n\n // Get the coupon details from the coupon using the coupons ID.\n $aCoupon = maybe_unserialize( $coupon_id );\n\n // This checks if the coupon details are NOT empty, if that is true, then output the info.\n if ( ! empty( $aCoupon ) ) {\n\n // If the title is set, and is not empty, output it.\n if ( isset( $aCoupon['title'] ) &amp;&amp; '' !== $aCoupon['title'] ) {\n echo '&lt;div&gt;&lt;span class=\"label\"&gt;Title&lt;/span&gt; ' . $aCoupon['title'] . '&lt;/div&gt;';\n }\n }\n\n echo'&lt;div class=\"offer-button\"&gt;';\n echo'&lt;a href=\"' . get_permalink() . '\" class=\"offer-button-text\"&gt;Claim this offer!&lt;/a&gt;';\n echo'&lt;/div&gt;';\n endwhile;\n wp_reset_postdata();\n endif;\n}\n</code></pre>\n" }, { "answer_id": 337808, "author": "Shaun21uk", "author_id": 167925, "author_profile": "https://wordpress.stackexchange.com/users/167925", "pm_score": 0, "selected": false, "text": "<p>Warwick, thank you so much for taking the time to go through this.</p>\n\n<p>My full code now looks like this:</p>\n\n<pre><code>add_shortcode( 'qg_shortcode', 'qg_shortcode' );\nfunction qg_shortcode() {\n\n $q = new WP_Query(array(\n 'post_type' =&gt; 'listing',\n 'posts_per_page' =&gt; 5,\n 'meta_key' =&gt; 'wc_coupon',\n 'meta_value' =&gt; ' ',\n 'meta_compare' =&gt; '!='\n ));\n if ( $q-&gt;have_posts() ) :\n while ( $q-&gt;have_posts() ) : $q-&gt;the_post();\n\n echo '&lt;h2 class=\"text-center\"&gt;&lt;a href=\"' . get_permalink() . '\"&gt;';\n the_title();\n echo '&lt;/a&gt;&lt;/h2&gt;';\n\n the_content();\n\n $aCoupon = GetSettings::getPostMeta( get_the_ID(), 'wc_coupon');\n $aCoupon = maybe_unserialze( $aCoupon );\n\n if ( ! empty( $aCoupon ) ){\n //If the title is set, and is not empty, output it.\n if ( isset( $aCoupon['title'] ) &amp;&amp; '' !== $aCoupon['title'] ) {\n echo '&lt;div&gt;&lt;span class=\"label\"&gt;Title&lt;/span&gt; ' . $aCoupon['title'] . '&lt;/div&gt;';\n }\n }\n\n echo'&lt;div class=\"offer-button\"&gt;';\n echo'&lt;a href=\"' . get_permalink() . '\" class=\"offer-button-text\"&gt;Claim this offer!&lt;/a&gt;';\n echo'&lt;/div&gt;';\n endwhile;\n wp_reset_postdata();\n endif;\n}\n</code></pre>\n\n<ul>\n<li>This is now only outputting one post and doesn't seem to be looping. Before I added your code it successfully displayed the title and link for two (all) posts containing a coupon. The one item it is displaying does indeed have a coupon though.</li>\n<li>Your code is still not outputting the $aCoupon['title'], it's just blank.</li>\n<li>It's worth mentioning that the meta_key for some reason is 'wc_coupon' which is why I use it in the wp_query filter, yet in the coupon.php code as shown, they clearly use just 'coupon'.</li>\n</ul>\n\n<p>I really thought you had cracked it here! Perhaps I have the code set up wrong somewhere above as I am pretty new to php but trying to learn :)</p>\n" } ]
2019/05/13
[ "https://wordpress.stackexchange.com/questions/337795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167925/" ]
A little long-winded but trying to explain clearly :) I am delving into the code of my new theme and am not familiar with this type of data storing/pulling - can someone help me understand what is going on here please: I am trying to create a page which outputs only the posts which have a 'coupon' attached to it. 'Coupon' is stored as a meta\_key against a post. It's `meta_value` is stored as an array which looks like this (output using *print\_r*): > > a:7:{s:9:"highlight";s:14:"Test Highlight";s:5:"title";s:12:"50% off food";s:11:"description";s:16:"Test description";s:4:"code";s:7:"1524521";s:11:"popup\_image";s:4:"4548";s:17:"popup\_description";s:17:"Popup description";s:11:"redirect\_to";s:0:"";} > > > I want the custom page to output: * Post title * Post content * Post image * Coupon details --- I can output the first three by running a wp\_query: ``` $q = new WP_Query(array( 'post_type' => 'listing', 'posts_per_page' => 5, 'meta_key' => 'wc_coupon', 'meta_value' => ' ', 'meta_compare' => '!=' )); ``` However, I cannot find a way to split out the `meta_value` array to display the individual elements per post. --- The theme handles this in a way I don't understand, perhaps someone can explain it to me. `Coupon.php` is a partial file which is used when displaying any single post which looks like this: ``` global $post, $Args; use ListingTools\Framework\Helpers\GetSettings; $aCoupon = GetSettings::getPostMeta($post->ID, 'coupon'); if ( empty($aCoupon) || ( empty($aCoupon['code']) && empty($aCoupon['redirect_to']) ) ){ return ''; } ?> <div class="content-box_module__333d9"> <div class="content-box_body__3tSRB"> <?php echo do_shortcode('[get_coupon highlight="'.esc_attr($aCoupon['highlight']).'" title="'.esc_attr($aCoupon['title']).'" description="'.esc_attr($aCoupon['description']).'" code="'.esc_attr($aCoupon['code']).'" redirect_to="'.esc_attr($aCoupon['redirect_to']).'"]'); ?> </div> </div> ``` --- So I don't understand how the "use" code works at the top in the variables section. I also don't understand how the `$aCoupon = GetSettings::getPostMeta($post->ID, 'coupon');` is working, but they can use this to display the individual parts of the coupon array as you can see later in the code: ``` echo do_shortcode('[get_coupon highlight="'.esc_attr($aCoupon['highlight']) ``` Hopefully that was follow-able :) Thanks in advance.
The string you are outputting using `print_r()` is what is known as a serialized string. When WordPress stores an array of values in 1 custom field, it compresses the array into this string using a function called [serialize()](https://www.w3resource.com/php/function-reference/serialize.php) What you want to do is to `unserialize` the string, and then you can access each "associated index" in the array. Usually `get_post_meta()` unserializes the string for you, but it looks like the custom function `GetSettings::getPostMeta()` does not. In this case we can run `maybe_unserialize()` which will convert it into a usable array if it is able to. Then we can simply loop through the array, outputting what you need to. ``` $aCoupon = GetSettings::getPostMeta($post->ID, 'coupon'); $aCoupon = maybe_unserialze( $aCoupon ); if ( empty( $aCoupon ) ){ foreach ( $aCoupon as $key => $value ) { echo '<div><span class="label">' . $key . '</span> ' . $value . '</div>'; } } ``` Based on your example, it would output something like this. ``` <div><span class="label">highlight</span> Test Highlight</div> <div><span class="label">title</span> 50% off food</div> <div><span class="label">description</span> Test description</div> <div><span class="label">code</span> 1524521</div> <div><span class="label">popup_image</span> 4548</div> <div><span class="label">popup_description</span> Popup description</div> <div><span class="label">redirect_to</span> </div> ``` Or if you want to access 1 value directly. ``` $aCoupon = GetSettings::getPostMeta($post->ID, 'coupon'); $aCoupon = maybe_unserialze( $aCoupon ); if ( empty( $aCoupon ) ){ //If the title is set, and is not empty, output it. if ( isset( $aCoupon['title'] ) && '' !== $aCoupon['title'] ) { echo '<div><span class="label">Title</span> ' . $aCoupon['title'] . '</div>'; } } ``` --- EDIT by @Shaun21uk - I got it to work making some minor changes (full code below). For whatever reason the `$aCoupon = GetSettings::getPostMeta($coupon_id, 'coupon');` was breaking the function - I still would like to know how to tap into the theme's way of handling data. Your shortcode function should look something like this: ``` add_shortcode( 'qg_shortcode', 'qg_shortcode' ); function qg_shortcode() { $q = new WP_Query(array( 'post_type' => 'listing', 'posts_per_page' => 5, 'meta_key' => 'wc_coupon', 'meta_value' => ' ', 'meta_compare' => '!=' )); if ( $q->have_posts() ) : while ( $q->have_posts() ) : $q->the_post(); echo '<h2 class="text-center"><a href="' . get_permalink() . '">'; the_title(); echo '</a></h2>'; the_content(); // Get the ID of the attached coupon. $coupon_id = get_post_meta( get_the_ID(), 'wc_coupon', true ); // Get the coupon details from the coupon using the coupons ID. $aCoupon = maybe_unserialize( $coupon_id ); // This checks if the coupon details are NOT empty, if that is true, then output the info. if ( ! empty( $aCoupon ) ) { // If the title is set, and is not empty, output it. if ( isset( $aCoupon['title'] ) && '' !== $aCoupon['title'] ) { echo '<div><span class="label">Title</span> ' . $aCoupon['title'] . '</div>'; } } echo'<div class="offer-button">'; echo'<a href="' . get_permalink() . '" class="offer-button-text">Claim this offer!</a>'; echo'</div>'; endwhile; wp_reset_postdata(); endif; } ```
337,800
<p>I have a WordPress website on a Digital Ocean VPS which I've come back to and tried to log into the admin panel through the 'wp-admin' link. For some reason I can't access it now. The website gets redirected to '<a href="http://%24domain/wp-admin/" rel="nofollow noreferrer">http://%24domain/wp-admin/</a>' which is a broken link.</p> <p>Here are the current things that I have tried but nothing has worked so far:</p> <ul> <li><p>Renaming the plugins directory so they appear deactivated</p></li> <li><p>Adding the following two lines to wp-config.php: define('WP_SITEURL', '<a href="http://example.com" rel="nofollow noreferrer">http://example.com</a>'); define('WP_HOME', '<a href="http://example.com" rel="nofollow noreferrer">http://example.com</a>');</p></li> <li><p>Keeping the theme/plugin files but re-uploading the core WordPress files</p></li> <li><p>Changing some options values (but adding a custom script which requires wp-load.php): update_option('siteurl', '<a href="http://example.com" rel="nofollow noreferrer">http://example.com</a>' ); update_option('home', '<a href="http://example.com" rel="nofollow noreferrer">http://example.com</a>' );</p></li> <li><p>Deleting the .htaccess in the root directory</p></li> </ul> <p>None of these have worked and I have no idea why the admin panel can't be accessed and redirects to that domain.</p> <p>Can someone help me get the admin panel working again? Any help is much appreciated!</p>
[ { "answer_id": 337803, "author": "mh. bitarafan", "author_id": 94233, "author_profile": "https://wordpress.stackexchange.com/users/94233", "pm_score": 1, "selected": false, "text": "<p>first of all you shouldnt delete .htaccess file. create another one in the root directory and add following lines to it:</p>\n\n<pre>\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule>\n# END WordPress\n</pre>\n\n<p>then go to wp-config.php and add these lines:</p>\n\n<pre>\ndefine( 'WP_HOME', 'http://youresite.com' );\ndefine( 'WP_SITEURL', 'http://youresite.com' );\n</pre>\n\n<p>now go to wp-admin and hopefully youre redirect problem will be fixed.\n<br>\ndont forget to remove last code from wp-config after fixing youre issue.</p>\n" }, { "answer_id": 337806, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>The other answer is a good start. Although I prefer to change the two URLs in the wp-options table, which is read first on all page loads (and is indicated as the preferred method in the Codex).</p>\n\n<p>See this entry in the Codex <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL</a> where it says:</p>\n\n<blockquote>\n <p>This is not necessarily the best fix, it's just hardcoding the values\n into the site itself. <strong>You won't be able to edit them on the General\n settings page anymore when using this method</strong> [setting values in wp-config.php, emphasis added].</p>\n</blockquote>\n\n<p>So, although changing the values in wp-config.php will work (and is often stated as an 'answer'), I think that the more correct way is to set the proper URLs in the wp-options table.</p>\n" }, { "answer_id": 382454, "author": "Prasun Kumar", "author_id": 201176, "author_profile": "https://wordpress.stackexchange.com/users/201176", "pm_score": 1, "selected": false, "text": "<p>I fixed this by going to this link in the browser:</p>\n<p><a href=\"http://example.com/wp-admin/install.php\" rel=\"nofollow noreferrer\">http://example.com/wp-admin/install.php</a></p>\n<p>Replace example.com with your website. You will see a login button and then you can enter your credentials to log in to your WordPress dashboard.</p>\n" } ]
2019/05/13
[ "https://wordpress.stackexchange.com/questions/337800", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40956/" ]
I have a WordPress website on a Digital Ocean VPS which I've come back to and tried to log into the admin panel through the 'wp-admin' link. For some reason I can't access it now. The website gets redirected to '<http://%24domain/wp-admin/>' which is a broken link. Here are the current things that I have tried but nothing has worked so far: * Renaming the plugins directory so they appear deactivated * Adding the following two lines to wp-config.php: define('WP\_SITEURL', '<http://example.com>'); define('WP\_HOME', '<http://example.com>'); * Keeping the theme/plugin files but re-uploading the core WordPress files * Changing some options values (but adding a custom script which requires wp-load.php): update\_option('siteurl', '<http://example.com>' ); update\_option('home', '<http://example.com>' ); * Deleting the .htaccess in the root directory None of these have worked and I have no idea why the admin panel can't be accessed and redirects to that domain. Can someone help me get the admin panel working again? Any help is much appreciated!
first of all you shouldnt delete .htaccess file. create another one in the root directory and add following lines to it: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` then go to wp-config.php and add these lines: ``` define( 'WP_HOME', 'http://youresite.com' ); define( 'WP_SITEURL', 'http://youresite.com' ); ``` now go to wp-admin and hopefully youre redirect problem will be fixed. dont forget to remove last code from wp-config after fixing youre issue.
337,804
<p>I'm just getting started with Wordpress, and currently using an XAMPP server to try and get a local installation working. The localhost environment is working fine, and I've successfully <a href="https://codex.wordpress.org/Installing_WordPress#Using_phpMyAdmin" rel="nofollow noreferrer">followed the steps here</a> to create a database and user account for Wordpress using phpMyAdmin.</p> <p>However, when navigating to <code>localhost/wordpress</code> to begin the Wordpress installation and enter my credentials into the relevant fields, I get the error:</p> <blockquote> <h3>Error establishing a database connection</h3> </blockquote> <p>I also discovered through a fluke that when I enter no password at all in the password field, I get a different, more specific error that claims my credentials are correct:</p> <blockquote> <h3>Can’t select database</h3> <p>We were able to connect to the database server (which means your username and password is okay) but not able to select the hashim_wordpress database.</p> <p>Are you sure it exists?</p> <p>Does the user Hashim have permission to use the hashim_wordpress database? On some systems the name of your database is prefixed with your username, so it would be like username_hashim_wordpress. Could that be the problem?</p> </blockquote> <p>However, this can't be the case as that user account definitely has a password set.</p> <p>My database name is <code>hashim_wordpress</code>, my user account is Hashim, and my password is definitely correct. phpMyAdmin lists my server as <code>127.0.0.1</code>, but I've also tried <code>localhost</code>. What could I possibly be doing wrong here?</p>
[ { "answer_id": 337803, "author": "mh. bitarafan", "author_id": 94233, "author_profile": "https://wordpress.stackexchange.com/users/94233", "pm_score": 1, "selected": false, "text": "<p>first of all you shouldnt delete .htaccess file. create another one in the root directory and add following lines to it:</p>\n\n<pre>\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule>\n# END WordPress\n</pre>\n\n<p>then go to wp-config.php and add these lines:</p>\n\n<pre>\ndefine( 'WP_HOME', 'http://youresite.com' );\ndefine( 'WP_SITEURL', 'http://youresite.com' );\n</pre>\n\n<p>now go to wp-admin and hopefully youre redirect problem will be fixed.\n<br>\ndont forget to remove last code from wp-config after fixing youre issue.</p>\n" }, { "answer_id": 337806, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>The other answer is a good start. Although I prefer to change the two URLs in the wp-options table, which is read first on all page loads (and is indicated as the preferred method in the Codex).</p>\n\n<p>See this entry in the Codex <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL</a> where it says:</p>\n\n<blockquote>\n <p>This is not necessarily the best fix, it's just hardcoding the values\n into the site itself. <strong>You won't be able to edit them on the General\n settings page anymore when using this method</strong> [setting values in wp-config.php, emphasis added].</p>\n</blockquote>\n\n<p>So, although changing the values in wp-config.php will work (and is often stated as an 'answer'), I think that the more correct way is to set the proper URLs in the wp-options table.</p>\n" }, { "answer_id": 382454, "author": "Prasun Kumar", "author_id": 201176, "author_profile": "https://wordpress.stackexchange.com/users/201176", "pm_score": 1, "selected": false, "text": "<p>I fixed this by going to this link in the browser:</p>\n<p><a href=\"http://example.com/wp-admin/install.php\" rel=\"nofollow noreferrer\">http://example.com/wp-admin/install.php</a></p>\n<p>Replace example.com with your website. You will see a login button and then you can enter your credentials to log in to your WordPress dashboard.</p>\n" } ]
2019/05/13
[ "https://wordpress.stackexchange.com/questions/337804", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167562/" ]
I'm just getting started with Wordpress, and currently using an XAMPP server to try and get a local installation working. The localhost environment is working fine, and I've successfully [followed the steps here](https://codex.wordpress.org/Installing_WordPress#Using_phpMyAdmin) to create a database and user account for Wordpress using phpMyAdmin. However, when navigating to `localhost/wordpress` to begin the Wordpress installation and enter my credentials into the relevant fields, I get the error: > > ### Error establishing a database connection > > > I also discovered through a fluke that when I enter no password at all in the password field, I get a different, more specific error that claims my credentials are correct: > > ### Can’t select database > > > We were able to connect to the database server (which means your username and password is okay) but not able to select the hashim\_wordpress database. > > > Are you sure it exists? > > > Does the user Hashim have permission to use the hashim\_wordpress database? On some systems the name of your database is prefixed with your username, so it would be like username\_hashim\_wordpress. Could that be the problem? > > > However, this can't be the case as that user account definitely has a password set. My database name is `hashim_wordpress`, my user account is Hashim, and my password is definitely correct. phpMyAdmin lists my server as `127.0.0.1`, but I've also tried `localhost`. What could I possibly be doing wrong here?
first of all you shouldnt delete .htaccess file. create another one in the root directory and add following lines to it: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` then go to wp-config.php and add these lines: ``` define( 'WP_HOME', 'http://youresite.com' ); define( 'WP_SITEURL', 'http://youresite.com' ); ``` now go to wp-admin and hopefully youre redirect problem will be fixed. dont forget to remove last code from wp-config after fixing youre issue.
337,813
<p>I was updating my plugins, after one plug in update went a bit wrong my site was stuck in maintenance mode, the solution I found online was to delete the .maintanence file, which I did. But straight after that I got this message: The site is experiencing technical difficulties. Please check your site admin email inbox for instructions. How do I fix it now?..</p>
[ { "answer_id": 337834, "author": "Ihtisham Zahoor", "author_id": 161650, "author_profile": "https://wordpress.stackexchange.com/users/161650", "pm_score": 1, "selected": false, "text": "<p>Use your cPanel access and rename that specific plugin folder with any name. If you still don't get control back to your site then rename the plugin folder and then activate one plugin at a time to close down on the faulty plugin.</p>\n" }, { "answer_id": 340856, "author": "Ateeq Rafeeq", "author_id": 170243, "author_profile": "https://wordpress.stackexchange.com/users/170243", "pm_score": 2, "selected": false, "text": "<p>You should troubleshoot your website for plugins. </p>\n\n<p>As you are unable to access your WordPress admin area so please try to access your file manager in cPanel or access public_html directory via FTP.</p>\n\n<p>Go to wp-content/ Directory them rename plugins/ directory to pluginsbackup/ now try to load your site. If this works that means you have problem with a plugin.</p>\n\n<p>If problem is with plugin change back the directory name pluginsbackup/ to plugins/ Enter in plugin directory. Now rename each plugins directory by placing backup at end of that directory name.</p>\n\n<p>Once you have changed all plugins directories names, start getting original directory names one by one and make sure you check the website if that’s still working after each plugin start working. As soon as you see which plugin is making problem just delete that plugin.</p>\n\n<p>Source <a href=\"https://www.webfulcreations.com/the-site-is-experiencing-technical-difficulties/\" rel=\"nofollow noreferrer\">The site is experiencing technical difficulties.</a></p>\n\n<p>If you can't figure out what's wrong please turn on the wp debug mode so you can get details of error. Edit your wp-config.php from WordPress root using FTP. And </p>\n\n<pre><code> &gt;&gt; Find\ndefine('WP_DEBUG', false);\n\nAnd replace with \ndefine('WP_DEBUG', true);\n</code></pre>\n\n<p>Once you turn on the wp debug mode you are not able to see the details of issue, weather is related to some missing file or some plugin is producing the FATAL error you can track and apply appropriate fix. Thanks. Once problem is fixed don't forget to turn off the debug mode in wp-config.php</p>\n" } ]
2019/05/14
[ "https://wordpress.stackexchange.com/questions/337813", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167937/" ]
I was updating my plugins, after one plug in update went a bit wrong my site was stuck in maintenance mode, the solution I found online was to delete the .maintanence file, which I did. But straight after that I got this message: The site is experiencing technical difficulties. Please check your site admin email inbox for instructions. How do I fix it now?..
You should troubleshoot your website for plugins. As you are unable to access your WordPress admin area so please try to access your file manager in cPanel or access public\_html directory via FTP. Go to wp-content/ Directory them rename plugins/ directory to pluginsbackup/ now try to load your site. If this works that means you have problem with a plugin. If problem is with plugin change back the directory name pluginsbackup/ to plugins/ Enter in plugin directory. Now rename each plugins directory by placing backup at end of that directory name. Once you have changed all plugins directories names, start getting original directory names one by one and make sure you check the website if that’s still working after each plugin start working. As soon as you see which plugin is making problem just delete that plugin. Source [The site is experiencing technical difficulties.](https://www.webfulcreations.com/the-site-is-experiencing-technical-difficulties/) If you can't figure out what's wrong please turn on the wp debug mode so you can get details of error. Edit your wp-config.php from WordPress root using FTP. And ``` >> Find define('WP_DEBUG', false); And replace with define('WP_DEBUG', true); ``` Once you turn on the wp debug mode you are not able to see the details of issue, weather is related to some missing file or some plugin is producing the FATAL error you can track and apply appropriate fix. Thanks. Once problem is fixed don't forget to turn off the debug mode in wp-config.php
337,814
<p>I learned a solution from <a href="https://stackoverflow.com/questions/36671203/wordpress-publish-date-shortcode">https://stackoverflow.com/questions/36671203/wordpress-publish-date-shortcode</a></p> <p>Although it can show the publish in the title, in the source code, it still shows the shortcode [post_published]. That means the search engine will not understand.</p> <p>For example, assume the title name is "ABC", the result in the front end will show "ABC 2019/05/14", but in the source code it will show "ABC [post_published]", so in the Google search result, the title shows "ABC" only.</p> <p>How can I do that the title will display the correct title name and publish date? Let it became "ABC 2019/05/14" not "ABC [post_published]"?</p> <p>Thanks.</p>
[ { "answer_id": 337817, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 1, "selected": false, "text": "<p>You can use the <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\">the_title</a> hook:</p>\n\n<pre><code>add_filter( 'the_title', function( $title ) {\n return $title . ' ' . get_the_date();\n} );\n</code></pre>\n" }, { "answer_id": 337832, "author": "Vishwa", "author_id": 120712, "author_profile": "https://wordpress.stackexchange.com/users/120712", "pm_score": 1, "selected": true, "text": "<p>if the output you see is <code>ABC [post_published]</code>, then it means your shortcode isn't working as it should. try including following code at the end of inside your theme's <code>functions.php</code> file.</p>\n\n<pre><code>function ppd_shortcode(){\n return get_the_date();\n}\nadd_shortcode('ppdate', 'ppd_shortcode');\n</code></pre>\n\n<p>When you register a shortcode using the add_shortcode function, you pass in the shortcode tag (<strong>$tag</strong>) and the corresponding function (<strong>$func</strong>)/hook that will execute whenever the shortcut is used.</p>\n\n<p><strong>Important:</strong> When naming tags, use lowercase letters only, don't use hyphens, underscores are acceptable.</p>\n\n<p>In this case, the shortcut tag is ppdate and the hook is ppd_shortcode. you can use the shortcode as <code>[ppdate]</code></p>\n\n<ul>\n<li><em>note, if this didn't work, try replacing <code>return the_date();</code> with <code>echo get_the_date();</code></em></li>\n</ul>\n\n<p><strong>Update:</strong> You said that your page title is working but meta title is still displaying wrong. Currently using <em>Rank Math SEO</em>, you can change the necessary page title as follows.</p>\n\n<p>Go to Pages and select the page you want to edit. look for Page title SEO option, plugin has built in variables for you to use.</p>\n" } ]
2019/05/14
[ "https://wordpress.stackexchange.com/questions/337814", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167938/" ]
I learned a solution from <https://stackoverflow.com/questions/36671203/wordpress-publish-date-shortcode> Although it can show the publish in the title, in the source code, it still shows the shortcode [post\_published]. That means the search engine will not understand. For example, assume the title name is "ABC", the result in the front end will show "ABC 2019/05/14", but in the source code it will show "ABC [post\_published]", so in the Google search result, the title shows "ABC" only. How can I do that the title will display the correct title name and publish date? Let it became "ABC 2019/05/14" not "ABC [post\_published]"? Thanks.
if the output you see is `ABC [post_published]`, then it means your shortcode isn't working as it should. try including following code at the end of inside your theme's `functions.php` file. ``` function ppd_shortcode(){ return get_the_date(); } add_shortcode('ppdate', 'ppd_shortcode'); ``` When you register a shortcode using the add\_shortcode function, you pass in the shortcode tag (**$tag**) and the corresponding function (**$func**)/hook that will execute whenever the shortcut is used. **Important:** When naming tags, use lowercase letters only, don't use hyphens, underscores are acceptable. In this case, the shortcut tag is ppdate and the hook is ppd\_shortcode. you can use the shortcode as `[ppdate]` * *note, if this didn't work, try replacing `return the_date();` with `echo get_the_date();`* **Update:** You said that your page title is working but meta title is still displaying wrong. Currently using *Rank Math SEO*, you can change the necessary page title as follows. Go to Pages and select the page you want to edit. look for Page title SEO option, plugin has built in variables for you to use.
337,845
<p>I have read in another SO post that Underscore.js is including in Wordpress by default. I am using it to test if a variable is defined but get this in the browser console:</p> <pre><code>pluginAdminPage.js:32 Uncaught ReferenceError: _ is not defined at pluginAdminPage.js:32 (anonymous) @ pluginAdminPage.js:32 _.VERSION // .VERSION even autofills. So then the browser has the library imported? "1.8.3" </code></pre> <p>The code it refers to:</p> <pre><code>if (_.isUndefined(module) === false) { module.exports.func = func; } </code></pre> <p>Phpstorm lints _ and <code>isUndefined</code> yellow which may suggest a lack of library import.</p> <p>I then tried to explicitly enqueue Underscore but this did not change the browser error messages:</p> <pre><code>function loadAdminScripts() { wp_register_style( 'admin-style', plugins_url('admin-style.css', __FILE__) ); wp_enqueue_style('admin-style'); wp_enqueue_script('jquery'); wp_enqueue_script('underscore'); } add_action('admin_enqueue_scripts', 'loadAdminScripts'); </code></pre> <p>What step(s) am I missing to get Underscore working?</p>
[ { "answer_id": 337849, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 3, "selected": true, "text": "<p>You need to set it as a dependency for your script, this is the best way you can make sure, Underscore.js is loaded <strong>before</strong> your script (which means, the methods will be available).</p>\n\n<pre><code>function loadAdminScripts() {\n wp_register_style(\n 'admin-style',\n plugins_url('admin-style.css', __FILE__)\n );\n wp_register_script(\n 'pluginAdminPage',\n plugins_url('pluginAdminPage.js', __FILE__),\n [\n 'jquery',\n 'underscore',\n ]\n );\n\n wp_enqueue_style('admin-style');\n wp_enqueue_script('pluginAdminPage');\n}\nadd_action('admin_enqueue_scripts', 'loadAdminScripts');\n</code></pre>\n\n<p>Check the <a href=\"https://developer.wordpress.org/reference/functions/wp_register_style/\" rel=\"nofollow noreferrer\">Code Reference on <code>wp_register_style</code></a> for more information.</p>\n" }, { "answer_id": 337904, "author": "Sean D", "author_id": 165037, "author_profile": "https://wordpress.stackexchange.com/users/165037", "pm_score": 0, "selected": false, "text": "<p>Fixed by enqueuing underscore as a dependency of the js file:</p>\n\n<pre><code>function loadAdminScripts() { \n wp_enqueue_script(\n 'pluginAdminPage', \n plugin_dir_url(__FILE__) . 'pluginAdminPage.js',\n ['jquery', 'underscore']\n );\n }\nadd_action('admin_enqueue_scripts', 'loadAdminScripts');\n</code></pre>\n" } ]
2019/05/14
[ "https://wordpress.stackexchange.com/questions/337845", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165037/" ]
I have read in another SO post that Underscore.js is including in Wordpress by default. I am using it to test if a variable is defined but get this in the browser console: ``` pluginAdminPage.js:32 Uncaught ReferenceError: _ is not defined at pluginAdminPage.js:32 (anonymous) @ pluginAdminPage.js:32 _.VERSION // .VERSION even autofills. So then the browser has the library imported? "1.8.3" ``` The code it refers to: ``` if (_.isUndefined(module) === false) { module.exports.func = func; } ``` Phpstorm lints \_ and `isUndefined` yellow which may suggest a lack of library import. I then tried to explicitly enqueue Underscore but this did not change the browser error messages: ``` function loadAdminScripts() { wp_register_style( 'admin-style', plugins_url('admin-style.css', __FILE__) ); wp_enqueue_style('admin-style'); wp_enqueue_script('jquery'); wp_enqueue_script('underscore'); } add_action('admin_enqueue_scripts', 'loadAdminScripts'); ``` What step(s) am I missing to get Underscore working?
You need to set it as a dependency for your script, this is the best way you can make sure, Underscore.js is loaded **before** your script (which means, the methods will be available). ``` function loadAdminScripts() { wp_register_style( 'admin-style', plugins_url('admin-style.css', __FILE__) ); wp_register_script( 'pluginAdminPage', plugins_url('pluginAdminPage.js', __FILE__), [ 'jquery', 'underscore', ] ); wp_enqueue_style('admin-style'); wp_enqueue_script('pluginAdminPage'); } add_action('admin_enqueue_scripts', 'loadAdminScripts'); ``` Check the [Code Reference on `wp_register_style`](https://developer.wordpress.org/reference/functions/wp_register_style/) for more information.
337,852
<p>I'm trying to fetch all my WooCommerce orders where some additional metadata is equal to not empty. </p> <pre><code>$orders = wc_get_orders( array( 'orderby' =&gt; 'date', 'order' =&gt; 'DESC', 'meta_query' =&gt; array( array( 'key' =&gt; 'var_rate', 'compare' =&gt; 'NOT EXISTS', ) ) )); </code></pre> <p>So if the <code>var_rate</code> is empty or doesn't exist then do not return that record. At the moment all orders are returned using those arguments.</p> <p>Example of empty record - </p> <pre><code>object(WC_Meta_Data)#2344 (2) { ["current_data":protected]=&gt; array(3) { ["id"]=&gt; int(6471) ["key"]=&gt; string(15) "var_rate" ["value"]=&gt; NULL } ["data":protected]=&gt; array(3) { ["id"]=&gt; int(6471) ["key"]=&gt; string(15) "var_rate" ["value"]=&gt; NULL } } </code></pre>
[ { "answer_id": 337865, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": false, "text": "<p>Apparently, WooCommerce is ignoring the <code>meta_query</code> parameter, so that's why you're getting all orders.</p>\n\n<p>You can use this code to make the <code>meta_query</code> parameter works with WooCommerce (orders) queries:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'woocommerce_get_wp_query_args', function( $wp_query_args, $query_vars ){\n if ( isset( $query_vars['meta_query'] ) ) {\n $meta_query = isset( $wp_query_args['meta_query'] ) ? $wp_query_args['meta_query'] : [];\n $wp_query_args['meta_query'] = array_merge( $meta_query, $query_vars['meta_query'] );\n }\n return $wp_query_args;\n}, 10, 2 );\n</code></pre>\n\n<p>But as I've pointed in my comment, to query for all orders where the <code>var_rate</code> metadata is <em>not</em> empty, set the <code>compare</code> to <code>!=</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'var_rate',\n 'compare' =&gt; '!=',\n 'value' =&gt; '',\n ),\n),\n</code></pre>\n\n<p>And in your case where you are querying with a <em>single</em> meta query, you could simply use the <code>meta_key</code> parameter along with <code>meta_compare</code> and <code>meta_value</code>, without having to use the <code>meta_query</code> parameter:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'meta_key' =&gt; 'var_rate',\n'meta_compare' =&gt; '!=',\n'meta_value' =&gt; '',\n</code></pre>\n\n<p>That way, you don't have to use the code above which \"enables\" the <code>meta_query</code> parameter.</p>\n\n<h2>UPDATE</h2>\n\n<p><em>I think I wasn't really paying attention to the question's title.. and I thought I should add these:</em></p>\n\n<p>In the question's title, you got \"<em>where meta data does <strong>not exist</em></strong>\", and for that, the <code>'compare' =&gt; 'NOT EXISTS'</code> or <code>'meta_compare' =&gt; 'NOT EXISTS'</code> is what you would need.</p>\n\n<p>But in the question's body, you said \"<em>where some additional metadata is equal to <strong>not empty</em></strong>\" and also \"<em>if the <code>var_rate</code> is empty or doesn't exist then <strong>do not return that record</em></strong>\", and for that, the <code>'compare' =&gt; '!='</code> or <code>'meta_compare' =&gt; '!='</code> is what you would need.</p>\n\n<p>Because when the <code>compare</code> or <code>meta_compare</code> is set to <code>!=</code>, and the <code>value</code> or <code>meta_value</code> is set to <code>''</code> (the default value, if not explicitly specified), then it means, \"find records where the meta exists in the database and the value is not empty (not <code>''</code> or not <code>NULL</code>)\".</p>\n\n<p>I hope that helps. :)</p>\n" }, { "answer_id": 337876, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 5, "selected": true, "text": "<p>The <code>meta_query</code> argument <em>(that you can use in a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"noreferrer\"><code>WP_Query</code></a>)</em> is not enabled by default when using a <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query\" rel=\"noreferrer\"><code>WC_Order_Query</code></a> through <a href=\"https://docs.woocommerce.com/wc-apidocs/function-wc_get_orders.html\" rel=\"noreferrer\"><code>wc_get_orders()</code></a> WooCommerce function. </p>\n\n<p>But for you can use the undocumented <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"noreferrer\">Custom Field Parameters</a> <em>(just like in a <code>WP_Query</code>)</em>:</p>\n\n<ul>\n<li><code>meta_key</code></li>\n<li><code>meta_value</code></li>\n<li><code>meta_value_num</code></li>\n<li><code>meta_compare</code></li>\n</ul>\n\n<p>So in your case you can use the following instead:</p>\n\n<pre><code>$orders = wc_get_orders( array(\n 'limit' =&gt; -1, // Query all orders\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC',\n 'meta_key' =&gt; 'var_rate', // The postmeta key field\n 'meta_compare' =&gt; 'NOT EXISTS', // The comparison argument\n));\n</code></pre>\n\n<p>This time it works nicely (Tested on WooCommerce 3.5.8 and 3.6.2).</p>\n" } ]
2019/05/14
[ "https://wordpress.stackexchange.com/questions/337852", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115473/" ]
I'm trying to fetch all my WooCommerce orders where some additional metadata is equal to not empty. ``` $orders = wc_get_orders( array( 'orderby' => 'date', 'order' => 'DESC', 'meta_query' => array( array( 'key' => 'var_rate', 'compare' => 'NOT EXISTS', ) ) )); ``` So if the `var_rate` is empty or doesn't exist then do not return that record. At the moment all orders are returned using those arguments. Example of empty record - ``` object(WC_Meta_Data)#2344 (2) { ["current_data":protected]=> array(3) { ["id"]=> int(6471) ["key"]=> string(15) "var_rate" ["value"]=> NULL } ["data":protected]=> array(3) { ["id"]=> int(6471) ["key"]=> string(15) "var_rate" ["value"]=> NULL } } ```
The `meta_query` argument *(that you can use in a [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query))* is not enabled by default when using a [`WC_Order_Query`](https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query) through [`wc_get_orders()`](https://docs.woocommerce.com/wc-apidocs/function-wc_get_orders.html) WooCommerce function. But for you can use the undocumented [Custom Field Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters) *(just like in a `WP_Query`)*: * `meta_key` * `meta_value` * `meta_value_num` * `meta_compare` So in your case you can use the following instead: ``` $orders = wc_get_orders( array( 'limit' => -1, // Query all orders 'orderby' => 'date', 'order' => 'DESC', 'meta_key' => 'var_rate', // The postmeta key field 'meta_compare' => 'NOT EXISTS', // The comparison argument )); ``` This time it works nicely (Tested on WooCommerce 3.5.8 and 3.6.2).
337,873
<p>Background of my problem: I'd like to mask external download links as internal links and to be only accessible by logged-in wp users at htaccess level or with PHP script but when redirection happens the visitor outside of wordpress can still access download links by pasting direct url into browser bar.</p> <p>I've tried this code for redirection to external link.</p> <pre><code>Redirect 301 /resources https://external.com/direct-download-link1 </code></pre> <p>Before accessing that direct download link (ourwebsite.com/resources) a script must be like man in the middle and check if the visitor is logged into wordpress.</p> <p>I'd like to change where the redirect goes have it go to a PHP page where you may load WordPress and check the role of the user to make sure they are logged in.</p> <pre><code>require('../wp-load.php'); // modify to reflect where your PHP file is in relation to Wordpress $roles = wp_get_current_user()-&gt;roles; // get current users role if (!in_array('alloweduserrole',$roles)) { // modify to match your roles that are allowed to download header('Location: http://www.ourwebsite.com/'); exit; } // end of if user does not have the proper role </code></pre> <p>The above code can be developed with a simple php checking script. But don't know how to implement and which code to change.</p>
[ { "answer_id": 337865, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": false, "text": "<p>Apparently, WooCommerce is ignoring the <code>meta_query</code> parameter, so that's why you're getting all orders.</p>\n\n<p>You can use this code to make the <code>meta_query</code> parameter works with WooCommerce (orders) queries:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'woocommerce_get_wp_query_args', function( $wp_query_args, $query_vars ){\n if ( isset( $query_vars['meta_query'] ) ) {\n $meta_query = isset( $wp_query_args['meta_query'] ) ? $wp_query_args['meta_query'] : [];\n $wp_query_args['meta_query'] = array_merge( $meta_query, $query_vars['meta_query'] );\n }\n return $wp_query_args;\n}, 10, 2 );\n</code></pre>\n\n<p>But as I've pointed in my comment, to query for all orders where the <code>var_rate</code> metadata is <em>not</em> empty, set the <code>compare</code> to <code>!=</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'var_rate',\n 'compare' =&gt; '!=',\n 'value' =&gt; '',\n ),\n),\n</code></pre>\n\n<p>And in your case where you are querying with a <em>single</em> meta query, you could simply use the <code>meta_key</code> parameter along with <code>meta_compare</code> and <code>meta_value</code>, without having to use the <code>meta_query</code> parameter:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'meta_key' =&gt; 'var_rate',\n'meta_compare' =&gt; '!=',\n'meta_value' =&gt; '',\n</code></pre>\n\n<p>That way, you don't have to use the code above which \"enables\" the <code>meta_query</code> parameter.</p>\n\n<h2>UPDATE</h2>\n\n<p><em>I think I wasn't really paying attention to the question's title.. and I thought I should add these:</em></p>\n\n<p>In the question's title, you got \"<em>where meta data does <strong>not exist</em></strong>\", and for that, the <code>'compare' =&gt; 'NOT EXISTS'</code> or <code>'meta_compare' =&gt; 'NOT EXISTS'</code> is what you would need.</p>\n\n<p>But in the question's body, you said \"<em>where some additional metadata is equal to <strong>not empty</em></strong>\" and also \"<em>if the <code>var_rate</code> is empty or doesn't exist then <strong>do not return that record</em></strong>\", and for that, the <code>'compare' =&gt; '!='</code> or <code>'meta_compare' =&gt; '!='</code> is what you would need.</p>\n\n<p>Because when the <code>compare</code> or <code>meta_compare</code> is set to <code>!=</code>, and the <code>value</code> or <code>meta_value</code> is set to <code>''</code> (the default value, if not explicitly specified), then it means, \"find records where the meta exists in the database and the value is not empty (not <code>''</code> or not <code>NULL</code>)\".</p>\n\n<p>I hope that helps. :)</p>\n" }, { "answer_id": 337876, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 5, "selected": true, "text": "<p>The <code>meta_query</code> argument <em>(that you can use in a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"noreferrer\"><code>WP_Query</code></a>)</em> is not enabled by default when using a <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query\" rel=\"noreferrer\"><code>WC_Order_Query</code></a> through <a href=\"https://docs.woocommerce.com/wc-apidocs/function-wc_get_orders.html\" rel=\"noreferrer\"><code>wc_get_orders()</code></a> WooCommerce function. </p>\n\n<p>But for you can use the undocumented <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"noreferrer\">Custom Field Parameters</a> <em>(just like in a <code>WP_Query</code>)</em>:</p>\n\n<ul>\n<li><code>meta_key</code></li>\n<li><code>meta_value</code></li>\n<li><code>meta_value_num</code></li>\n<li><code>meta_compare</code></li>\n</ul>\n\n<p>So in your case you can use the following instead:</p>\n\n<pre><code>$orders = wc_get_orders( array(\n 'limit' =&gt; -1, // Query all orders\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC',\n 'meta_key' =&gt; 'var_rate', // The postmeta key field\n 'meta_compare' =&gt; 'NOT EXISTS', // The comparison argument\n));\n</code></pre>\n\n<p>This time it works nicely (Tested on WooCommerce 3.5.8 and 3.6.2).</p>\n" } ]
2019/05/14
[ "https://wordpress.stackexchange.com/questions/337873", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167984/" ]
Background of my problem: I'd like to mask external download links as internal links and to be only accessible by logged-in wp users at htaccess level or with PHP script but when redirection happens the visitor outside of wordpress can still access download links by pasting direct url into browser bar. I've tried this code for redirection to external link. ``` Redirect 301 /resources https://external.com/direct-download-link1 ``` Before accessing that direct download link (ourwebsite.com/resources) a script must be like man in the middle and check if the visitor is logged into wordpress. I'd like to change where the redirect goes have it go to a PHP page where you may load WordPress and check the role of the user to make sure they are logged in. ``` require('../wp-load.php'); // modify to reflect where your PHP file is in relation to Wordpress $roles = wp_get_current_user()->roles; // get current users role if (!in_array('alloweduserrole',$roles)) { // modify to match your roles that are allowed to download header('Location: http://www.ourwebsite.com/'); exit; } // end of if user does not have the proper role ``` The above code can be developed with a simple php checking script. But don't know how to implement and which code to change.
The `meta_query` argument *(that you can use in a [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query))* is not enabled by default when using a [`WC_Order_Query`](https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query) through [`wc_get_orders()`](https://docs.woocommerce.com/wc-apidocs/function-wc_get_orders.html) WooCommerce function. But for you can use the undocumented [Custom Field Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters) *(just like in a `WP_Query`)*: * `meta_key` * `meta_value` * `meta_value_num` * `meta_compare` So in your case you can use the following instead: ``` $orders = wc_get_orders( array( 'limit' => -1, // Query all orders 'orderby' => 'date', 'order' => 'DESC', 'meta_key' => 'var_rate', // The postmeta key field 'meta_compare' => 'NOT EXISTS', // The comparison argument )); ``` This time it works nicely (Tested on WooCommerce 3.5.8 and 3.6.2).
337,949
<p>I want to implement a system to insert custom links in my wordpress custom theme. I don't want to hardcode these links inside my theme. These links are for the socials or partners website. So they need to be easily changed from WordPress dashboard. I want to avoid registering a custom post type or using a post. Is this possible with a custom function or a similar solution?</p>
[ { "answer_id": 337865, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": false, "text": "<p>Apparently, WooCommerce is ignoring the <code>meta_query</code> parameter, so that's why you're getting all orders.</p>\n\n<p>You can use this code to make the <code>meta_query</code> parameter works with WooCommerce (orders) queries:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'woocommerce_get_wp_query_args', function( $wp_query_args, $query_vars ){\n if ( isset( $query_vars['meta_query'] ) ) {\n $meta_query = isset( $wp_query_args['meta_query'] ) ? $wp_query_args['meta_query'] : [];\n $wp_query_args['meta_query'] = array_merge( $meta_query, $query_vars['meta_query'] );\n }\n return $wp_query_args;\n}, 10, 2 );\n</code></pre>\n\n<p>But as I've pointed in my comment, to query for all orders where the <code>var_rate</code> metadata is <em>not</em> empty, set the <code>compare</code> to <code>!=</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'var_rate',\n 'compare' =&gt; '!=',\n 'value' =&gt; '',\n ),\n),\n</code></pre>\n\n<p>And in your case where you are querying with a <em>single</em> meta query, you could simply use the <code>meta_key</code> parameter along with <code>meta_compare</code> and <code>meta_value</code>, without having to use the <code>meta_query</code> parameter:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'meta_key' =&gt; 'var_rate',\n'meta_compare' =&gt; '!=',\n'meta_value' =&gt; '',\n</code></pre>\n\n<p>That way, you don't have to use the code above which \"enables\" the <code>meta_query</code> parameter.</p>\n\n<h2>UPDATE</h2>\n\n<p><em>I think I wasn't really paying attention to the question's title.. and I thought I should add these:</em></p>\n\n<p>In the question's title, you got \"<em>where meta data does <strong>not exist</em></strong>\", and for that, the <code>'compare' =&gt; 'NOT EXISTS'</code> or <code>'meta_compare' =&gt; 'NOT EXISTS'</code> is what you would need.</p>\n\n<p>But in the question's body, you said \"<em>where some additional metadata is equal to <strong>not empty</em></strong>\" and also \"<em>if the <code>var_rate</code> is empty or doesn't exist then <strong>do not return that record</em></strong>\", and for that, the <code>'compare' =&gt; '!='</code> or <code>'meta_compare' =&gt; '!='</code> is what you would need.</p>\n\n<p>Because when the <code>compare</code> or <code>meta_compare</code> is set to <code>!=</code>, and the <code>value</code> or <code>meta_value</code> is set to <code>''</code> (the default value, if not explicitly specified), then it means, \"find records where the meta exists in the database and the value is not empty (not <code>''</code> or not <code>NULL</code>)\".</p>\n\n<p>I hope that helps. :)</p>\n" }, { "answer_id": 337876, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 5, "selected": true, "text": "<p>The <code>meta_query</code> argument <em>(that you can use in a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"noreferrer\"><code>WP_Query</code></a>)</em> is not enabled by default when using a <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query\" rel=\"noreferrer\"><code>WC_Order_Query</code></a> through <a href=\"https://docs.woocommerce.com/wc-apidocs/function-wc_get_orders.html\" rel=\"noreferrer\"><code>wc_get_orders()</code></a> WooCommerce function. </p>\n\n<p>But for you can use the undocumented <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"noreferrer\">Custom Field Parameters</a> <em>(just like in a <code>WP_Query</code>)</em>:</p>\n\n<ul>\n<li><code>meta_key</code></li>\n<li><code>meta_value</code></li>\n<li><code>meta_value_num</code></li>\n<li><code>meta_compare</code></li>\n</ul>\n\n<p>So in your case you can use the following instead:</p>\n\n<pre><code>$orders = wc_get_orders( array(\n 'limit' =&gt; -1, // Query all orders\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC',\n 'meta_key' =&gt; 'var_rate', // The postmeta key field\n 'meta_compare' =&gt; 'NOT EXISTS', // The comparison argument\n));\n</code></pre>\n\n<p>This time it works nicely (Tested on WooCommerce 3.5.8 and 3.6.2).</p>\n" } ]
2019/05/15
[ "https://wordpress.stackexchange.com/questions/337949", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168069/" ]
I want to implement a system to insert custom links in my wordpress custom theme. I don't want to hardcode these links inside my theme. These links are for the socials or partners website. So they need to be easily changed from WordPress dashboard. I want to avoid registering a custom post type or using a post. Is this possible with a custom function or a similar solution?
The `meta_query` argument *(that you can use in a [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query))* is not enabled by default when using a [`WC_Order_Query`](https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query) through [`wc_get_orders()`](https://docs.woocommerce.com/wc-apidocs/function-wc_get_orders.html) WooCommerce function. But for you can use the undocumented [Custom Field Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters) *(just like in a `WP_Query`)*: * `meta_key` * `meta_value` * `meta_value_num` * `meta_compare` So in your case you can use the following instead: ``` $orders = wc_get_orders( array( 'limit' => -1, // Query all orders 'orderby' => 'date', 'order' => 'DESC', 'meta_key' => 'var_rate', // The postmeta key field 'meta_compare' => 'NOT EXISTS', // The comparison argument )); ``` This time it works nicely (Tested on WooCommerce 3.5.8 and 3.6.2).
338,042
<p>Is there a way of loading a template file without having a post? I'm loading set of data via an API. Set up my index page but having a brain freeze with single template files as these posts are not in the WP registry/database.</p> <pre><code>// Template files events-index.php events-single.php </code></pre> <p>Events index:</p> <pre><code> &lt;?php $events = $api_data // Data retrieved from API if ( $upcoming_events-&gt;have_posts() ) : while ( $upcoming_events-&gt;have_posts() ) : $upcoming_events-&gt;the_post(); $custom_link = sanitize_title( get_the_title() ); $custom_link = rtrim($custom_link, '/'); $custom_link .= '?' . get_the_ID(); ?&gt; &lt;a href="&lt;?php echo $custom_link; ?&gt;"&gt; // This link to a custom template file &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 338043, "author": "Alexander Holsgrove", "author_id": 48962, "author_profile": "https://wordpress.stackexchange.com/users/48962", "pm_score": 3, "selected": true, "text": "<p>You could setup a custom rewrite rule using <a href=\"https://developer.wordpress.org/reference/functions/add_rewrite_rule/\" rel=\"nofollow noreferrer\">add_rewrite_rule</a> and send these requests to a custom page.</p>\n\n<p>Your URL structure could be <code>/index-page/single-event-slug</code> The rule would point all of the single events to a separate page where you can then set your template <code>events-single.php</code>.</p>\n\n<p>Another option is to pass the events in as a query <code>/index-page?event=single-event-slug</code> or <code>/index-page?event=123</code>. You'd need to register this parameter with <a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\" rel=\"nofollow noreferrer\">add_query_arg</a> and then change your index template to use the event template via the <a href=\"https://developer.wordpress.org/reference/hooks/template_include/\" rel=\"nofollow noreferrer\">template_include</a> hook.</p>\n" }, { "answer_id": 338048, "author": "Abdul Sadik Yalcin", "author_id": 97623, "author_profile": "https://wordpress.stackexchange.com/users/97623", "pm_score": 1, "selected": false, "text": "<pre><code>function prefix_register_query_var( $vars ) {\n $vars[] = 'eid';\n\n return $vars;\n}\nadd_filter( 'query_vars', 'prefix_register_query_var' );\nfunction prefix_rewrite_templates() {\n if ( get_query_var( 'eid' ) ) {\n add_filter( 'template_include', function() {\n return get_template_directory() . '/events-single.php';\n });\n }\n}\nadd_action( 'template_redirect', 'prefix_rewrite_templates' );\n</code></pre>\n\n<p>Add the <code>$var</code> to the URL in the loop:</p>\n\n<pre><code>$url = add_query_arg( array(\n 'eid' =&gt; get_the_ID(),\n) );\n</code></pre>\n" } ]
2019/05/16
[ "https://wordpress.stackexchange.com/questions/338042", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97623/" ]
Is there a way of loading a template file without having a post? I'm loading set of data via an API. Set up my index page but having a brain freeze with single template files as these posts are not in the WP registry/database. ``` // Template files events-index.php events-single.php ``` Events index: ``` <?php $events = $api_data // Data retrieved from API if ( $upcoming_events->have_posts() ) : while ( $upcoming_events->have_posts() ) : $upcoming_events->the_post(); $custom_link = sanitize_title( get_the_title() ); $custom_link = rtrim($custom_link, '/'); $custom_link .= '?' . get_the_ID(); ?> <a href="<?php echo $custom_link; ?>"> // This link to a custom template file <?php } ?> ```
You could setup a custom rewrite rule using [add\_rewrite\_rule](https://developer.wordpress.org/reference/functions/add_rewrite_rule/) and send these requests to a custom page. Your URL structure could be `/index-page/single-event-slug` The rule would point all of the single events to a separate page where you can then set your template `events-single.php`. Another option is to pass the events in as a query `/index-page?event=single-event-slug` or `/index-page?event=123`. You'd need to register this parameter with [add\_query\_arg](https://developer.wordpress.org/reference/functions/add_query_arg/) and then change your index template to use the event template via the [template\_include](https://developer.wordpress.org/reference/hooks/template_include/) hook.
338,050
<p>I work for an architecture company and our project names mostly go like this: <code>house|something</code>, <code>bridge|somewhere</code>, <code>building|whatever</code>.</p> <p>Now, when I want to add a new project named like that, WordPress automatically converts it to <code>housesomething</code>, <code>bridgesomewhere</code> and puts that as the slug. I'd much prefer to keep some kind of separator, e.g. <code>house-something</code>, <code>bridge-somewhere</code> instead.</p> <p>So, how to make WordPress convert <code>|</code> to <code>-</code> and not <code>Empty String</code> (<code>""</code>)? I'm obviously tired of doing that manually all the time.</p> <p>It seems to me that it's very simple to do. It takes just a simple search and replace kind of thing if one knows where to look (in the WP core or wherever), but I haven't the slightest idea where to look, or what code to execute.</p>
[ { "answer_id": 338052, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 1, "selected": false, "text": "<p>If you put spaces in between the words and the separator | the permalink will automatically include dashes between the words. For instance try this as your post title:</p>\n\n<pre><code>house | something, bridge | somewhere\n</code></pre>\n\n<p>That results in the slug:</p>\n\n<pre><code>house-something-bridge-somewhere\n</code></pre>\n" }, { "answer_id": 338054, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 4, "selected": true, "text": "<p>When WordPress <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\">inserts a post</a>, it runs the title through a filter called <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title/\" rel=\"nofollow noreferrer\"><code>sanitize_title</code></a> to get the slug. By default there is a function called <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title_with_dashes/\" rel=\"nofollow noreferrer\"><code>santize_title_with_dashes</code></a> attached to this filter with priority 10. This function simply strips out the <code>|</code>. If it is surrounded by spaces those spaces will be converted to hyphens.</p>\n\n<p>So your task is to run a filter on the same hook before (say, priority 9) the default one and replace the <code>|</code> with <code>-</code> before it gets stripped away. Like this:</p>\n\n<pre><code>add_filter( 'sanitize_title', function ( $title ) {\n return str_replace( '|', '-', $title );\n}, 9 );\n</code></pre>\n" } ]
2019/05/16
[ "https://wordpress.stackexchange.com/questions/338050", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168163/" ]
I work for an architecture company and our project names mostly go like this: `house|something`, `bridge|somewhere`, `building|whatever`. Now, when I want to add a new project named like that, WordPress automatically converts it to `housesomething`, `bridgesomewhere` and puts that as the slug. I'd much prefer to keep some kind of separator, e.g. `house-something`, `bridge-somewhere` instead. So, how to make WordPress convert `|` to `-` and not `Empty String` (`""`)? I'm obviously tired of doing that manually all the time. It seems to me that it's very simple to do. It takes just a simple search and replace kind of thing if one knows where to look (in the WP core or wherever), but I haven't the slightest idea where to look, or what code to execute.
When WordPress [inserts a post](https://developer.wordpress.org/reference/functions/wp_insert_post/), it runs the title through a filter called [`sanitize_title`](https://developer.wordpress.org/reference/functions/sanitize_title/) to get the slug. By default there is a function called [`santize_title_with_dashes`](https://developer.wordpress.org/reference/functions/sanitize_title_with_dashes/) attached to this filter with priority 10. This function simply strips out the `|`. If it is surrounded by spaces those spaces will be converted to hyphens. So your task is to run a filter on the same hook before (say, priority 9) the default one and replace the `|` with `-` before it gets stripped away. Like this: ``` add_filter( 'sanitize_title', function ( $title ) { return str_replace( '|', '-', $title ); }, 9 ); ```
338,090
<p>How can I run a WP function on server cron?</p> <p>Background: I can't run it on wp_cron because the website is not published and will not be, so there will be no visitors. Tested cron job without wp function, it is working properly (like sending email every 30 minutes).</p> <pre><code>//RemoteCoins() and LoadRemoteCoins() that include wp functions like wp_remote_get() function runthe_func() { //some code here } runthe_func(); </code></pre> <p>I kept on getting errors like: "Fatal error: Call to undefined function wp_remote_get() in /home/path/path2/testing.php on line 91"</p> <p>How can I make it run with the server recognizing wp functions?</p>
[ { "answer_id": 338052, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 1, "selected": false, "text": "<p>If you put spaces in between the words and the separator | the permalink will automatically include dashes between the words. For instance try this as your post title:</p>\n\n<pre><code>house | something, bridge | somewhere\n</code></pre>\n\n<p>That results in the slug:</p>\n\n<pre><code>house-something-bridge-somewhere\n</code></pre>\n" }, { "answer_id": 338054, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 4, "selected": true, "text": "<p>When WordPress <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\">inserts a post</a>, it runs the title through a filter called <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title/\" rel=\"nofollow noreferrer\"><code>sanitize_title</code></a> to get the slug. By default there is a function called <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title_with_dashes/\" rel=\"nofollow noreferrer\"><code>santize_title_with_dashes</code></a> attached to this filter with priority 10. This function simply strips out the <code>|</code>. If it is surrounded by spaces those spaces will be converted to hyphens.</p>\n\n<p>So your task is to run a filter on the same hook before (say, priority 9) the default one and replace the <code>|</code> with <code>-</code> before it gets stripped away. Like this:</p>\n\n<pre><code>add_filter( 'sanitize_title', function ( $title ) {\n return str_replace( '|', '-', $title );\n}, 9 );\n</code></pre>\n" } ]
2019/05/17
[ "https://wordpress.stackexchange.com/questions/338090", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167973/" ]
How can I run a WP function on server cron? Background: I can't run it on wp\_cron because the website is not published and will not be, so there will be no visitors. Tested cron job without wp function, it is working properly (like sending email every 30 minutes). ``` //RemoteCoins() and LoadRemoteCoins() that include wp functions like wp_remote_get() function runthe_func() { //some code here } runthe_func(); ``` I kept on getting errors like: "Fatal error: Call to undefined function wp\_remote\_get() in /home/path/path2/testing.php on line 91" How can I make it run with the server recognizing wp functions?
When WordPress [inserts a post](https://developer.wordpress.org/reference/functions/wp_insert_post/), it runs the title through a filter called [`sanitize_title`](https://developer.wordpress.org/reference/functions/sanitize_title/) to get the slug. By default there is a function called [`santize_title_with_dashes`](https://developer.wordpress.org/reference/functions/sanitize_title_with_dashes/) attached to this filter with priority 10. This function simply strips out the `|`. If it is surrounded by spaces those spaces will be converted to hyphens. So your task is to run a filter on the same hook before (say, priority 9) the default one and replace the `|` with `-` before it gets stripped away. Like this: ``` add_filter( 'sanitize_title', function ( $title ) { return str_replace( '|', '-', $title ); }, 9 ); ```
338,108
<p>I’m trying to add HTML wrappers around a block to create a clipping effect, something like the below code. It has been suggested this might be possible with the block save or block edit functions?</p> <p>I have done a fair bit of experimenting with CSS clip-path and SVG clipPath and unfortunately they will not work for what I am trying to achieve as I need cross-browser support.</p> <p>HTML:</p> <pre><code>&lt;div class="transform-containter"&gt; &lt;div class="transform-right"&gt; &lt;div class="transform-left"&gt; &lt;div class="transform-content"&gt; &lt;div class="block-container"&gt; BLOCK CONTENT HERE &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.transform-containter { width: 100%; height: auto; margin-top: 0; overflow-x: hidden; overflow-y: hidden; } .transform-right { position: relative; width: 110%; height: 100%; top: 0; left: -5%; -webkit-transform: rotate(2deg); -moz-transform: rotate(2deg); -ms-transform: rotate(2deg); -o-transform: rotate(2deg); transform: rotate(2deg); overflow: hidden; margin-top:2.5%; } .transform-left { position: relative; width: 110%; height: 100%; left: -5%; -webkit-transform: rotate(-4deg); -moz-transform: rotate(-4deg); -ms-transform: rotate(-4deg); -o-transform: rotate(-4deg); transform: rotate(-4deg); overflow: hidden; margin-top: -4%; margin-bottom: 3.5%; } .transform-content { width: 100%; height: 100%; -webkit-transform: rotate(2deg); -moz-transform: rotate(2deg); -ms-transform: rotate(2deg); -o-transform: rotate(2deg); transform: rotate(2deg); background-color: #cccccc; background-position: center; background-repeat: no-repeat; background-size: cover; margin: 2% 0 -2% 0; padding: 2em 10%; } </code></pre> <p>Here is a codepen of the effect in raw HTML/CSS <a href="https://codepen.io/bearandpear/pen/VObzQZ" rel="nofollow noreferrer">https://codepen.io/bearandpear/pen/VObzQZ</a></p> <p>So essentially just trying to add the extra HTML div elements either side of the block output code.</p> <p>Any help would be greatly appreciated. I’m not a developer, I’m pretty good with HTML, CSS and a little PHP, but completely green when it comes to Javascript/React…</p>
[ { "answer_id": 338123, "author": "moped", "author_id": 160324, "author_profile": "https://wordpress.stackexchange.com/users/160324", "pm_score": 0, "selected": false, "text": "<p>You can create divs inside divs (or different elements) in the Gutenberg edit/save function. Like so: <br /></p>\n\n<pre><code>createElement( \"div\",\n {className: \"transform-containter\"},\n createElement( \"div\",\n {className: \"transform-right\"},\n createElement( \"div\",\n {className: \"transform-left\"},\n [AND SO ON...]\n YOUR BLOCK CONTENT\n )\n )\n)\n</code></pre>\n\n<p>I think you try to write your own block, or am I wrong?</p>\n" }, { "answer_id": 338207, "author": "Alvaro", "author_id": 16533, "author_profile": "https://wordpress.stackexchange.com/users/16533", "pm_score": 3, "selected": true, "text": "<p>When registering a block we indicate: an <strong>edit</strong> property which defines how the block acts/displays in the editor, and a <strong>save</strong> property which is responsible for the final HTML of the block.</p>\n\n<p>To modify these two functions from a block we need to use <a href=\"https://developer.wordpress.org/block-editor/developers/filters/block-filters/\" rel=\"nofollow noreferrer\">filter hooks</a>. These hooks just need to be included inside a script in the editor.</p>\n\n<p>The <a href=\"https://developer.wordpress.org/block-editor/developers/filters/block-filters/#blocks-getsaveelement\" rel=\"nofollow noreferrer\">getSaveElement</a> filter lets us modify the HTML output of the save property of the block. Using JSX:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const modifySaveHtml = (block, props, attributes) =&gt; {\n if (props.name !== \"my-plugin/my-block\") {\n return block;\n }\n\n return (\n &lt;div className=\"transform-container\"&gt;\n &lt;div className=\"transform-right\"&gt;\n &lt;div className=\"transform-left\"&gt;\n &lt;div className=\"transform-content\"&gt;{block}&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n );\n};\nwp.hooks.addFilter(\n \"blocks.getSaveElement\",\n \"my-plugin/modifySaveHtml\",\n modifySaveHtml\n);\n</code></pre>\n\n<p>Using JS (ES5):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var createElement = wp.element.createElement;\n\nvar modifySaveHtml = function(block, props, attributes) {\n if (props.name !== \"my-plugin/my-block\") {\n return block;\n }\n\n return createElement(\n \"div\",\n { className: \"transform-container\" },\n createElement(\n \"div\",\n { className: \"transform-right\" },\n createElement(\n \"div\",\n { className: \"transform-left\" },\n createElement(\"div\", { className: \"transform-content\" }, block)\n )\n )\n );\n};\nwp.hooks.addFilter(\n \"blocks.getSaveElement\",\n \"my-plugin/modifySaveHtml\",\n modifySaveHtml\n);\n</code></pre>\n\n<p>The <a href=\"https://developer.wordpress.org/block-editor/developers/filters/block-filters/#editor-blockedit\" rel=\"nofollow noreferrer\">editor.BlockEdit</a> filter modifies the HTML of the edit property of the block. This might not be necessary if you don't need to modify the HTML in the editor. Using JSX:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const modifyEditHtml = BlockEdit =&gt; {\n return props =&gt; {\n if (props.name !== \"my-plugin/my-block\") {\n return &lt;BlockEdit {...props} /&gt;;\n }\n\n return (\n &lt;div className=\"transform-container\"&gt;\n &lt;div className=\"transform-right\"&gt;\n &lt;div className=\"transform-left\"&gt;\n &lt;div className=\"transform-content\"&gt;\n &lt;BlockEdit {...props} /&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n );\n };\n};\nwp.hooks.addFilter(\n \"editor.BlockEdit\",\n \"my-plugin/modifyEditHtml\",\n modifyEditHtml\n);\n</code></pre>\n\n<p>Using JS (ES5):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var createElement = wp.element.createElement;\n\nvar modifyEditHtml = function(BlockEdit) {\n return function(props) {\n if (props.name !== \"my-plugin/my-block\") {\n return createElement( BlockEdit, props );\n }\n\n return createElement(\n \"div\",\n { className: \"transform-container\" },\n createElement(\n \"div\",\n { className: \"transform-right\" },\n createElement(\n \"div\",\n { className: \"transform-left\" },\n createElement(\n \"div\",\n { className: \"transform-content\" },\n createElement(\n BlockEdit,\n props\n )\n )\n )\n )\n );\n };\n};\nwp.hooks.addFilter(\n \"editor.BlockEdit\",\n \"my-plugin/modifyEditHtml\",\n modifyEditHtml\n);\n</code></pre>\n\n<p>Keep in mind that these filters will be applied to both new instances of the block and old ones. This means that any block which was created previously will show an \"invalid content\" message. This is because the filter modifies the block definition and it now expects the new HTML which is not there, as the block was created/saved before applying the filter.</p>\n\n<p>When enqueuing your script (from PHP), remember to include the used dependencies. In the above code, <code>wp-hooks</code> package is used and <code>wp-element</code> as well in the non-JSX code.</p>\n\n<pre><code>function my_plugin_enqueue_editor() {\n\n wp_enqueue_script(\n 'my-plugin-script', // name\n 'path/to/my-plugin-script.js', // path\n array( // dependencies\n 'wp-element',\n 'wp-hooks',\n ),\n '1.0.0', // my-plugin version number\n true // enqueue in the footer.\n );\n\n}\nadd_action( 'enqueue_block_editor_assets', 'my_plugin_enqueue_editor' );\n</code></pre>\n\n<p>Note: The JS(ES5) code is untested but I think it should work correctly.</p>\n" } ]
2019/05/17
[ "https://wordpress.stackexchange.com/questions/338108", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168211/" ]
I’m trying to add HTML wrappers around a block to create a clipping effect, something like the below code. It has been suggested this might be possible with the block save or block edit functions? I have done a fair bit of experimenting with CSS clip-path and SVG clipPath and unfortunately they will not work for what I am trying to achieve as I need cross-browser support. HTML: ``` <div class="transform-containter"> <div class="transform-right"> <div class="transform-left"> <div class="transform-content"> <div class="block-container"> BLOCK CONTENT HERE </div> </div> </div> </div> </div> ``` CSS: ``` .transform-containter { width: 100%; height: auto; margin-top: 0; overflow-x: hidden; overflow-y: hidden; } .transform-right { position: relative; width: 110%; height: 100%; top: 0; left: -5%; -webkit-transform: rotate(2deg); -moz-transform: rotate(2deg); -ms-transform: rotate(2deg); -o-transform: rotate(2deg); transform: rotate(2deg); overflow: hidden; margin-top:2.5%; } .transform-left { position: relative; width: 110%; height: 100%; left: -5%; -webkit-transform: rotate(-4deg); -moz-transform: rotate(-4deg); -ms-transform: rotate(-4deg); -o-transform: rotate(-4deg); transform: rotate(-4deg); overflow: hidden; margin-top: -4%; margin-bottom: 3.5%; } .transform-content { width: 100%; height: 100%; -webkit-transform: rotate(2deg); -moz-transform: rotate(2deg); -ms-transform: rotate(2deg); -o-transform: rotate(2deg); transform: rotate(2deg); background-color: #cccccc; background-position: center; background-repeat: no-repeat; background-size: cover; margin: 2% 0 -2% 0; padding: 2em 10%; } ``` Here is a codepen of the effect in raw HTML/CSS <https://codepen.io/bearandpear/pen/VObzQZ> So essentially just trying to add the extra HTML div elements either side of the block output code. Any help would be greatly appreciated. I’m not a developer, I’m pretty good with HTML, CSS and a little PHP, but completely green when it comes to Javascript/React…
When registering a block we indicate: an **edit** property which defines how the block acts/displays in the editor, and a **save** property which is responsible for the final HTML of the block. To modify these two functions from a block we need to use [filter hooks](https://developer.wordpress.org/block-editor/developers/filters/block-filters/). These hooks just need to be included inside a script in the editor. The [getSaveElement](https://developer.wordpress.org/block-editor/developers/filters/block-filters/#blocks-getsaveelement) filter lets us modify the HTML output of the save property of the block. Using JSX: ```js const modifySaveHtml = (block, props, attributes) => { if (props.name !== "my-plugin/my-block") { return block; } return ( <div className="transform-container"> <div className="transform-right"> <div className="transform-left"> <div className="transform-content">{block}</div> </div> </div> </div> ); }; wp.hooks.addFilter( "blocks.getSaveElement", "my-plugin/modifySaveHtml", modifySaveHtml ); ``` Using JS (ES5): ```js var createElement = wp.element.createElement; var modifySaveHtml = function(block, props, attributes) { if (props.name !== "my-plugin/my-block") { return block; } return createElement( "div", { className: "transform-container" }, createElement( "div", { className: "transform-right" }, createElement( "div", { className: "transform-left" }, createElement("div", { className: "transform-content" }, block) ) ) ); }; wp.hooks.addFilter( "blocks.getSaveElement", "my-plugin/modifySaveHtml", modifySaveHtml ); ``` The [editor.BlockEdit](https://developer.wordpress.org/block-editor/developers/filters/block-filters/#editor-blockedit) filter modifies the HTML of the edit property of the block. This might not be necessary if you don't need to modify the HTML in the editor. Using JSX: ```js const modifyEditHtml = BlockEdit => { return props => { if (props.name !== "my-plugin/my-block") { return <BlockEdit {...props} />; } return ( <div className="transform-container"> <div className="transform-right"> <div className="transform-left"> <div className="transform-content"> <BlockEdit {...props} /> </div> </div> </div> </div> ); }; }; wp.hooks.addFilter( "editor.BlockEdit", "my-plugin/modifyEditHtml", modifyEditHtml ); ``` Using JS (ES5): ```js var createElement = wp.element.createElement; var modifyEditHtml = function(BlockEdit) { return function(props) { if (props.name !== "my-plugin/my-block") { return createElement( BlockEdit, props ); } return createElement( "div", { className: "transform-container" }, createElement( "div", { className: "transform-right" }, createElement( "div", { className: "transform-left" }, createElement( "div", { className: "transform-content" }, createElement( BlockEdit, props ) ) ) ) ); }; }; wp.hooks.addFilter( "editor.BlockEdit", "my-plugin/modifyEditHtml", modifyEditHtml ); ``` Keep in mind that these filters will be applied to both new instances of the block and old ones. This means that any block which was created previously will show an "invalid content" message. This is because the filter modifies the block definition and it now expects the new HTML which is not there, as the block was created/saved before applying the filter. When enqueuing your script (from PHP), remember to include the used dependencies. In the above code, `wp-hooks` package is used and `wp-element` as well in the non-JSX code. ``` function my_plugin_enqueue_editor() { wp_enqueue_script( 'my-plugin-script', // name 'path/to/my-plugin-script.js', // path array( // dependencies 'wp-element', 'wp-hooks', ), '1.0.0', // my-plugin version number true // enqueue in the footer. ); } add_action( 'enqueue_block_editor_assets', 'my_plugin_enqueue_editor' ); ``` Note: The JS(ES5) code is untested but I think it should work correctly.
338,114
<p>I'm having trouble navigating the WP documentation so forgive me if this is common knowledge.</p> <p>Is it possible to view the documentation of classes and methods from within the shell?</p> <p>That is, is there a command that I can type at the <code>wp-shell</code> prompt that will return the api documentation for a given method/class.</p> <p>Something like:</p> <pre class="lang-php prettyprint-override"><code>doc(get_posts); #=&gt; get_posts( array $args = null ) # Retrieves an array of the latest posts, or posts matching the given criteria. # Parameters # $args # ... </code></pre> <p>For example, <code>pry-doc</code> in Ruby provides something similar.</p>
[ { "answer_id": 338122, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 1, "selected": false, "text": "<p>Skimming the available <a href=\"https://developer.wordpress.org/cli/commands/\" rel=\"nofollow noreferrer\">WP-CLI commands</a> I guess there is not something like that. You may create a feature request in the <a href=\"https://github.com/wp-cli/wp-cli\" rel=\"nofollow noreferrer\">WP-CLI GitHub repo</a> but I doubt that this will gain much attention without you explaining the actual necessity of such command.</p>\n\n<p>Normally when developing, you use your IDE to get hold of those information. A good IDE provides you autocompletion, type hints or shortcuts that let you jump into certain core functions.</p>\n\n<p>Naming <a href=\"https://www.jetbrains.com/phpstorm/\" rel=\"nofollow noreferrer\">PhpStorm</a> as an example which has built-in WordPress support it looks like this when I just start to type <code>wp_</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ei5vD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ei5vD.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 344953, "author": "3gth", "author_id": 130388, "author_profile": "https://wordpress.stackexchange.com/users/130388", "pm_score": 0, "selected": false, "text": "<p>You could try <a href=\"https://github.com/mehrshaddarzi/wp-cli-reference-command\" rel=\"nofollow noreferrer\">WP-CLI Reference Command</a>. This is neither an official command, nor can it be used inside <code>wp shell</code>, but will be helpful to you in getting hook / function information from command line. </p>\n" } ]
2019/05/17
[ "https://wordpress.stackexchange.com/questions/338114", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74293/" ]
I'm having trouble navigating the WP documentation so forgive me if this is common knowledge. Is it possible to view the documentation of classes and methods from within the shell? That is, is there a command that I can type at the `wp-shell` prompt that will return the api documentation for a given method/class. Something like: ```php doc(get_posts); #=> get_posts( array $args = null ) # Retrieves an array of the latest posts, or posts matching the given criteria. # Parameters # $args # ... ``` For example, `pry-doc` in Ruby provides something similar.
Skimming the available [WP-CLI commands](https://developer.wordpress.org/cli/commands/) I guess there is not something like that. You may create a feature request in the [WP-CLI GitHub repo](https://github.com/wp-cli/wp-cli) but I doubt that this will gain much attention without you explaining the actual necessity of such command. Normally when developing, you use your IDE to get hold of those information. A good IDE provides you autocompletion, type hints or shortcuts that let you jump into certain core functions. Naming [PhpStorm](https://www.jetbrains.com/phpstorm/) as an example which has built-in WordPress support it looks like this when I just start to type `wp_`: [![enter image description here](https://i.stack.imgur.com/ei5vD.png)](https://i.stack.imgur.com/ei5vD.png)
338,135
<p>I'm a working on editing a website done with wordpress and I want to change the copyright text in the footer but I can't find out how to do it because I'm a newbie.</p> <p><a href="https://i.stack.imgur.com/oCeUb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oCeUb.png" alt="enter image description here"></a></p> <p>If you have some clues, I would be pleased to get informed.</p>
[ { "answer_id": 338137, "author": "davebrener", "author_id": 133156, "author_profile": "https://wordpress.stackexchange.com/users/133156", "pm_score": 0, "selected": false, "text": "<p>Have you tried looking in the Appearance>Widgets area? In my experience, sometimes the copyright text can live in a footer widget.</p>\n" }, { "answer_id": 338144, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": false, "text": "<p>It all depends on the theme. Some themes require you to modify one of their files (specifically, the footer.php file, usually) to remove the text. If you go this route, you'd want to create/use a Child Theme so that a theme update doesn't overwrite your changes. Copy your theme's footer.php into your Child Theme folder, then modify it for your needs. (Activate your Child Theme.)</p>\n\n<p>If you just want to remove the text, then another, somewhat easier way is to modify the CSS that displays the copyright text. You could use the F12 inspector key in your browser, and then look for a 'class' for the code. Or look in the page source.</p>\n\n<p>Then in the Additional CSS section of the theme customization, add code (this assumes that the class is set to 'copyright')</p>\n\n<pre><code>.copyright {display:none !important;}\n</code></pre>\n\n<p>The 'dot' is important. </p>\n\n<p>And note that some theme authors don't like it if you remove the copyright notice, but (assuming it is an open-source theme), you can still do it. Paid themes may have more restrictive copyrights.</p>\n" } ]
2019/05/17
[ "https://wordpress.stackexchange.com/questions/338135", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168254/" ]
I'm a working on editing a website done with wordpress and I want to change the copyright text in the footer but I can't find out how to do it because I'm a newbie. [![enter image description here](https://i.stack.imgur.com/oCeUb.png)](https://i.stack.imgur.com/oCeUb.png) If you have some clues, I would be pleased to get informed.
It all depends on the theme. Some themes require you to modify one of their files (specifically, the footer.php file, usually) to remove the text. If you go this route, you'd want to create/use a Child Theme so that a theme update doesn't overwrite your changes. Copy your theme's footer.php into your Child Theme folder, then modify it for your needs. (Activate your Child Theme.) If you just want to remove the text, then another, somewhat easier way is to modify the CSS that displays the copyright text. You could use the F12 inspector key in your browser, and then look for a 'class' for the code. Or look in the page source. Then in the Additional CSS section of the theme customization, add code (this assumes that the class is set to 'copyright') ``` .copyright {display:none !important;} ``` The 'dot' is important. And note that some theme authors don't like it if you remove the copyright notice, but (assuming it is an open-source theme), you can still do it. Paid themes may have more restrictive copyrights.
338,152
<p>I am using something like this to query and display future or scheduled posts on my homepage:</p> <pre><code>&lt;?php query_posts('post_status=future&amp;posts_per_page=10&amp;order=ASC'); while ( have_posts() ) : the_post(); ?&gt; //doing stuff &lt;?php endwhile; ?&gt; &lt;?php wp_reset_query(); ?&gt; </code></pre> <p>This is working with great success. Although, these <code>scheduled</code> or <code>future</code> posts don't want to show up in a search or tag search.</p> <p>I would like to get the future posts searchable and the tags contained within them clickable. They (the tags) are currently clickable but throw an error on click. Takes me to the dreaded "Sorry No posts matched your criteria".</p> <p>So, how to enable WP search for and to include future posts and tags from future posts?</p>
[ { "answer_id": 338155, "author": "Brendan Strong", "author_id": 153663, "author_profile": "https://wordpress.stackexchange.com/users/153663", "pm_score": 0, "selected": false, "text": "<p>Future and scheduled posts aren't considered published so you'd need to customize the queries in those templates to include those results.</p>\n\n<p>You'd need to customize the search.php template in your theme. Add a new WP Query similar to what you've done in your example that pulls future and scheduled posts into the template. Then replace the data in that template with the data from your own query.</p>\n\n<p>For the tags you'd need to create a taxonomy template in your theme and do something very similar as with the search template.</p>\n" }, { "answer_id": 338170, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 2, "selected": true, "text": "<p>To achieve the intended result you will have to modify the query by adding the <code>future</code> value to the <code>post_status</code> parameter via the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> filter hook.</p>\n\n<pre><code>add_action( 'pre_get_posts', 'se338152_future_post_tag_and_search' );\nfunction se338152_future_post_tag_and_search( $query )\n{\n // apply changes only for search and tag archive\n if ( ! ( $query-&gt;is_main_query() &amp;&amp; (is_tag() || is_search()) ) )\n return;\n\n $status = $query-&gt;get('post_status');\n if ( empty($status) )\n $status = ['publish'];\n if ( !is_array($status) )\n $status = (array)$status;\n $status[] = 'future';\n\n $query-&gt;set('post_status', $status);\n}\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">Conditional tags</a> <code>is_search()</code> and <code>is_tax()</code> will allow you to modify the query only on the search page or the tag archive.</p>\n" } ]
2019/05/17
[ "https://wordpress.stackexchange.com/questions/338152", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86752/" ]
I am using something like this to query and display future or scheduled posts on my homepage: ``` <?php query_posts('post_status=future&posts_per_page=10&order=ASC'); while ( have_posts() ) : the_post(); ?> //doing stuff <?php endwhile; ?> <?php wp_reset_query(); ?> ``` This is working with great success. Although, these `scheduled` or `future` posts don't want to show up in a search or tag search. I would like to get the future posts searchable and the tags contained within them clickable. They (the tags) are currently clickable but throw an error on click. Takes me to the dreaded "Sorry No posts matched your criteria". So, how to enable WP search for and to include future posts and tags from future posts?
To achieve the intended result you will have to modify the query by adding the `future` value to the `post_status` parameter via the [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) filter hook. ``` add_action( 'pre_get_posts', 'se338152_future_post_tag_and_search' ); function se338152_future_post_tag_and_search( $query ) { // apply changes only for search and tag archive if ( ! ( $query->is_main_query() && (is_tag() || is_search()) ) ) return; $status = $query->get('post_status'); if ( empty($status) ) $status = ['publish']; if ( !is_array($status) ) $status = (array)$status; $status[] = 'future'; $query->set('post_status', $status); } ``` [Conditional tags](https://codex.wordpress.org/Conditional_Tags) `is_search()` and `is_tax()` will allow you to modify the query only on the search page or the tag archive.
338,159
<p>The WP loop goes like this:</p> <pre><code>if ( have_posts() ) { while ( have_posts() ) { the_post(); ... </code></pre> <p>Why is it preferred over the following?</p> <pre><code>foreach( (new WP_Query())-&gt;get_posts() as $post ) { ... } </code></pre> <p>To me, it's more apparent what is going on in the latter. I'm new to PHP and WP and I'm trying to understand why I should be using the former.</p> <p>What do I gain by using the <code>standard loop</code>? Is iterating over <code>get_posts()</code> any less efficient? </p>
[ { "answer_id": 338161, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 5, "selected": true, "text": "<p>Several reasons</p>\n\n<h2>1. Filters and Actions</h2>\n\n<p>By using the standard loop, you execute various filters and actions that plugins rely on.</p>\n\n<p>Additionally, you set up <code>the_post</code> correctly, allowing functions such as <code>the_content</code> etc to work correctly. Some filters can even insert \"posts\" into the loop</p>\n\n<h2>2. Memory Efficiency</h2>\n\n<p>By fetching all the posts as an array, you're forcing <code>WP_Query</code> to take the data it has and create <code>WP_Post</code> objects. With a standard post loop these are created as they're needed</p>\n\n<h2>3. PHP Warnings</h2>\n\n<p>Your loop doesn't check if any posts were actually found, so it's impossible to give a \"No posts available\" style message. It'll also generate PHP warnings at times.</p>\n\n<h2>4. Overriding WP globals</h2>\n\n<p>By using <code>$post</code> you're overriding a global variable, which can have unintended consequences, especially if this loop is nested inside another loop you're unaware of</p>\n\n<h2>5. PHP Efficiency and Correctness</h2>\n\n<p>Creating an object inside a <code>foreach</code> condition is bad practice, as is creating and then using an object without error checking.</p>\n\n<h2>6. Debugging</h2>\n\n<p>A lot of tools and plugins assume you're using a standard loop and have been built to make life easier. By doing this you're throwing all of that away</p>\n\n<h2>7. There are Better Alternatives</h2>\n\n<h3>array_walk</h3>\n\n<p>A <strong>crude</strong> but superior option to your foreach might actually be <code>array_walk</code>:</p>\n\n<pre><code>$q = new WP_Query([ ..args ]);\narray_walk( $q-&gt;get_posts(), function( $post ) {\n //\n});\n</code></pre>\n\n<p>Note that I don't recommend using <code>array_walk</code>.</p>\n\n<h3>PHP Generators</h3>\n\n<p>Now that's not to say you couldn't use a different style loop while still having all the advantages.</p>\n\n<p>For example WP Scholar has an article showing a php generator based loop:</p>\n\n<pre><code>if ( have_posts() ) {\n foreach ( wp_loop() as $post ) {\n echo '&lt;h1&gt;' . esc_html( get_the_title() ) . '&lt;/h1&gt;';\n }\n} else {\n echo '&lt;h1&gt;No posts found!&lt;/h1&gt;';\n}\n</code></pre>\n\n<p>This has the advantage that it still calls all the functions of a standard loop, but they've been abstracted away.</p>\n\n<p><a href=\"https://wpscholar.com/blog/creating-better-wordpress-loop/\" rel=\"noreferrer\">https://wpscholar.com/blog/creating-better-wordpress-loop/</a></p>\n\n<p>I'm sure there are others, but a standard loop is reliable predictable and readable to all</p>\n" }, { "answer_id": 338162, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>I advise you to take a look at the documentation:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/the-loop/\" rel=\"nofollow noreferrer\">The Loop | Theme Developer Handbook | WordPress Developer Resources</a></li>\n</ul>\n\n<p>you'll find more details there. </p>\n\n<p>It follows a short abstract:</p>\n\n<p>The Loop gives you access to: </p>\n\n<p><strong>Template Tags</strong></p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/template-tags/\" rel=\"nofollow noreferrer\">Template Tags | Theme Developer Handbook | WordPress Developer Resources</a> </li>\n<li><a href=\"https://developer.wordpress.org/themes/references/list-of-template-tags/\" rel=\"nofollow noreferrer\">List of Template Tags | Theme Developer Handbook | WordPress Developer Resources</a></li>\n</ul>\n\n<p><strong>Conditional Tags</strong></p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/conditional-tags/\" rel=\"nofollow noreferrer\">Conditional Tags | Theme Developer Handbook | WordPress Developer Resources</a></li>\n</ul>\n\n<p>Not all Template and Conditional Tags are The Loop dependent, for an overview for what to use in The Loop:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/the-loop/#what-the-loop-can-display\" rel=\"nofollow noreferrer\">What the Loop Can Display | The Loop | Theme Developer Handbook | WordPress Developer Resources</a></li>\n</ul>\n\n<p>Additionally, there are hooks that can be used with The Loop, like:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/loop_start/\" rel=\"nofollow noreferrer\">loop_start</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/the_post/\" rel=\"nofollow noreferrer\">the_post</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/loop_end/\" rel=\"nofollow noreferrer\">loop_end</a></li>\n</ul>\n\n<p>Looking at it a bit more broadly you could include something like:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">pre_get_posts</a> </li>\n</ul>\n\n<p>And all the filters listed under:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference#WP_Query_Filters\" rel=\"nofollow noreferrer\">WP_Query Filters | Plugin API/Filter Refernce | WordPress Codex</a></li>\n</ul>\n\n<p>Although the latter two technically do apply to a custom iteration over the <code>$wp_query-&gt;get_posts()</code> array too, but it is part of the system or process. And as a general rule it works better and more reliable if you use it inside the paradigm, so in this case by making use of The Loop.</p>\n\n<p>Even if you need, sometimes it is unavoidable, additional loops, you don't have to do it outside The Loop paradigm:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/the-loop/#multiple-loops\" rel=\"nofollow noreferrer\">Multiple Loops | The Loop | Theme Developer Handbook | WordPress Developer Resources</a></li>\n</ul>\n\n<p>Because:</p>\n\n<ul>\n<li><p><a href=\"https://developer.wordpress.org/themes/basics/the-loop/#using-rewind_posts\" rel=\"nofollow noreferrer\">You can use <code>rewind_posts()</code> to loop through the same query a second time</a>;</p></li>\n<li><p>Or <a href=\"https://developer.wordpress.org/themes/basics/the-loop/#creating-secondary-queries-and-loops\" rel=\"nofollow noreferrer\">create a secondary query and loop</a>, using <a href=\"https://developer.wordpress.org/themes/basics/the-loop/#using-wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a> in the process. </p></li>\n</ul>\n\n<p>Doing it this way gives you the benefits that come with The Loop, it is better integrated into how WordPress intended on doing it, and will create less overhead in the process.</p>\n" } ]
2019/05/17
[ "https://wordpress.stackexchange.com/questions/338159", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74293/" ]
The WP loop goes like this: ``` if ( have_posts() ) { while ( have_posts() ) { the_post(); ... ``` Why is it preferred over the following? ``` foreach( (new WP_Query())->get_posts() as $post ) { ... } ``` To me, it's more apparent what is going on in the latter. I'm new to PHP and WP and I'm trying to understand why I should be using the former. What do I gain by using the `standard loop`? Is iterating over `get_posts()` any less efficient?
Several reasons 1. Filters and Actions ---------------------- By using the standard loop, you execute various filters and actions that plugins rely on. Additionally, you set up `the_post` correctly, allowing functions such as `the_content` etc to work correctly. Some filters can even insert "posts" into the loop 2. Memory Efficiency -------------------- By fetching all the posts as an array, you're forcing `WP_Query` to take the data it has and create `WP_Post` objects. With a standard post loop these are created as they're needed 3. PHP Warnings --------------- Your loop doesn't check if any posts were actually found, so it's impossible to give a "No posts available" style message. It'll also generate PHP warnings at times. 4. Overriding WP globals ------------------------ By using `$post` you're overriding a global variable, which can have unintended consequences, especially if this loop is nested inside another loop you're unaware of 5. PHP Efficiency and Correctness --------------------------------- Creating an object inside a `foreach` condition is bad practice, as is creating and then using an object without error checking. 6. Debugging ------------ A lot of tools and plugins assume you're using a standard loop and have been built to make life easier. By doing this you're throwing all of that away 7. There are Better Alternatives -------------------------------- ### array\_walk A **crude** but superior option to your foreach might actually be `array_walk`: ``` $q = new WP_Query([ ..args ]); array_walk( $q->get_posts(), function( $post ) { // }); ``` Note that I don't recommend using `array_walk`. ### PHP Generators Now that's not to say you couldn't use a different style loop while still having all the advantages. For example WP Scholar has an article showing a php generator based loop: ``` if ( have_posts() ) { foreach ( wp_loop() as $post ) { echo '<h1>' . esc_html( get_the_title() ) . '</h1>'; } } else { echo '<h1>No posts found!</h1>'; } ``` This has the advantage that it still calls all the functions of a standard loop, but they've been abstracted away. <https://wpscholar.com/blog/creating-better-wordpress-loop/> I'm sure there are others, but a standard loop is reliable predictable and readable to all
338,235
<p>How can I get <code>Pages</code> and <code>All Pages</code> ?? My code outputs <code>Pages</code> and <code>Pages</code>. My code is like below</p> <pre><code>add_menu_page( 'Pages', 'Pages', 'manage_options', 'Pages', 'page_callback_function', 'dashicons-media-spreadsheet', 26 ); </code></pre> <p><a href="https://i.stack.imgur.com/RlIv5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RlIv5.png" alt="enter image description here"></a></p>
[ { "answer_id": 338161, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 5, "selected": true, "text": "<p>Several reasons</p>\n\n<h2>1. Filters and Actions</h2>\n\n<p>By using the standard loop, you execute various filters and actions that plugins rely on.</p>\n\n<p>Additionally, you set up <code>the_post</code> correctly, allowing functions such as <code>the_content</code> etc to work correctly. Some filters can even insert \"posts\" into the loop</p>\n\n<h2>2. Memory Efficiency</h2>\n\n<p>By fetching all the posts as an array, you're forcing <code>WP_Query</code> to take the data it has and create <code>WP_Post</code> objects. With a standard post loop these are created as they're needed</p>\n\n<h2>3. PHP Warnings</h2>\n\n<p>Your loop doesn't check if any posts were actually found, so it's impossible to give a \"No posts available\" style message. It'll also generate PHP warnings at times.</p>\n\n<h2>4. Overriding WP globals</h2>\n\n<p>By using <code>$post</code> you're overriding a global variable, which can have unintended consequences, especially if this loop is nested inside another loop you're unaware of</p>\n\n<h2>5. PHP Efficiency and Correctness</h2>\n\n<p>Creating an object inside a <code>foreach</code> condition is bad practice, as is creating and then using an object without error checking.</p>\n\n<h2>6. Debugging</h2>\n\n<p>A lot of tools and plugins assume you're using a standard loop and have been built to make life easier. By doing this you're throwing all of that away</p>\n\n<h2>7. There are Better Alternatives</h2>\n\n<h3>array_walk</h3>\n\n<p>A <strong>crude</strong> but superior option to your foreach might actually be <code>array_walk</code>:</p>\n\n<pre><code>$q = new WP_Query([ ..args ]);\narray_walk( $q-&gt;get_posts(), function( $post ) {\n //\n});\n</code></pre>\n\n<p>Note that I don't recommend using <code>array_walk</code>.</p>\n\n<h3>PHP Generators</h3>\n\n<p>Now that's not to say you couldn't use a different style loop while still having all the advantages.</p>\n\n<p>For example WP Scholar has an article showing a php generator based loop:</p>\n\n<pre><code>if ( have_posts() ) {\n foreach ( wp_loop() as $post ) {\n echo '&lt;h1&gt;' . esc_html( get_the_title() ) . '&lt;/h1&gt;';\n }\n} else {\n echo '&lt;h1&gt;No posts found!&lt;/h1&gt;';\n}\n</code></pre>\n\n<p>This has the advantage that it still calls all the functions of a standard loop, but they've been abstracted away.</p>\n\n<p><a href=\"https://wpscholar.com/blog/creating-better-wordpress-loop/\" rel=\"noreferrer\">https://wpscholar.com/blog/creating-better-wordpress-loop/</a></p>\n\n<p>I'm sure there are others, but a standard loop is reliable predictable and readable to all</p>\n" }, { "answer_id": 338162, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>I advise you to take a look at the documentation:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/the-loop/\" rel=\"nofollow noreferrer\">The Loop | Theme Developer Handbook | WordPress Developer Resources</a></li>\n</ul>\n\n<p>you'll find more details there. </p>\n\n<p>It follows a short abstract:</p>\n\n<p>The Loop gives you access to: </p>\n\n<p><strong>Template Tags</strong></p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/template-tags/\" rel=\"nofollow noreferrer\">Template Tags | Theme Developer Handbook | WordPress Developer Resources</a> </li>\n<li><a href=\"https://developer.wordpress.org/themes/references/list-of-template-tags/\" rel=\"nofollow noreferrer\">List of Template Tags | Theme Developer Handbook | WordPress Developer Resources</a></li>\n</ul>\n\n<p><strong>Conditional Tags</strong></p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/conditional-tags/\" rel=\"nofollow noreferrer\">Conditional Tags | Theme Developer Handbook | WordPress Developer Resources</a></li>\n</ul>\n\n<p>Not all Template and Conditional Tags are The Loop dependent, for an overview for what to use in The Loop:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/the-loop/#what-the-loop-can-display\" rel=\"nofollow noreferrer\">What the Loop Can Display | The Loop | Theme Developer Handbook | WordPress Developer Resources</a></li>\n</ul>\n\n<p>Additionally, there are hooks that can be used with The Loop, like:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/loop_start/\" rel=\"nofollow noreferrer\">loop_start</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/the_post/\" rel=\"nofollow noreferrer\">the_post</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/loop_end/\" rel=\"nofollow noreferrer\">loop_end</a></li>\n</ul>\n\n<p>Looking at it a bit more broadly you could include something like:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">pre_get_posts</a> </li>\n</ul>\n\n<p>And all the filters listed under:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference#WP_Query_Filters\" rel=\"nofollow noreferrer\">WP_Query Filters | Plugin API/Filter Refernce | WordPress Codex</a></li>\n</ul>\n\n<p>Although the latter two technically do apply to a custom iteration over the <code>$wp_query-&gt;get_posts()</code> array too, but it is part of the system or process. And as a general rule it works better and more reliable if you use it inside the paradigm, so in this case by making use of The Loop.</p>\n\n<p>Even if you need, sometimes it is unavoidable, additional loops, you don't have to do it outside The Loop paradigm:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/themes/basics/the-loop/#multiple-loops\" rel=\"nofollow noreferrer\">Multiple Loops | The Loop | Theme Developer Handbook | WordPress Developer Resources</a></li>\n</ul>\n\n<p>Because:</p>\n\n<ul>\n<li><p><a href=\"https://developer.wordpress.org/themes/basics/the-loop/#using-rewind_posts\" rel=\"nofollow noreferrer\">You can use <code>rewind_posts()</code> to loop through the same query a second time</a>;</p></li>\n<li><p>Or <a href=\"https://developer.wordpress.org/themes/basics/the-loop/#creating-secondary-queries-and-loops\" rel=\"nofollow noreferrer\">create a secondary query and loop</a>, using <a href=\"https://developer.wordpress.org/themes/basics/the-loop/#using-wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a> in the process. </p></li>\n</ul>\n\n<p>Doing it this way gives you the benefits that come with The Loop, it is better integrated into how WordPress intended on doing it, and will create less overhead in the process.</p>\n" } ]
2019/05/19
[ "https://wordpress.stackexchange.com/questions/338235", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104698/" ]
How can I get `Pages` and `All Pages` ?? My code outputs `Pages` and `Pages`. My code is like below ``` add_menu_page( 'Pages', 'Pages', 'manage_options', 'Pages', 'page_callback_function', 'dashicons-media-spreadsheet', 26 ); ``` [![enter image description here](https://i.stack.imgur.com/RlIv5.png)](https://i.stack.imgur.com/RlIv5.png)
Several reasons 1. Filters and Actions ---------------------- By using the standard loop, you execute various filters and actions that plugins rely on. Additionally, you set up `the_post` correctly, allowing functions such as `the_content` etc to work correctly. Some filters can even insert "posts" into the loop 2. Memory Efficiency -------------------- By fetching all the posts as an array, you're forcing `WP_Query` to take the data it has and create `WP_Post` objects. With a standard post loop these are created as they're needed 3. PHP Warnings --------------- Your loop doesn't check if any posts were actually found, so it's impossible to give a "No posts available" style message. It'll also generate PHP warnings at times. 4. Overriding WP globals ------------------------ By using `$post` you're overriding a global variable, which can have unintended consequences, especially if this loop is nested inside another loop you're unaware of 5. PHP Efficiency and Correctness --------------------------------- Creating an object inside a `foreach` condition is bad practice, as is creating and then using an object without error checking. 6. Debugging ------------ A lot of tools and plugins assume you're using a standard loop and have been built to make life easier. By doing this you're throwing all of that away 7. There are Better Alternatives -------------------------------- ### array\_walk A **crude** but superior option to your foreach might actually be `array_walk`: ``` $q = new WP_Query([ ..args ]); array_walk( $q->get_posts(), function( $post ) { // }); ``` Note that I don't recommend using `array_walk`. ### PHP Generators Now that's not to say you couldn't use a different style loop while still having all the advantages. For example WP Scholar has an article showing a php generator based loop: ``` if ( have_posts() ) { foreach ( wp_loop() as $post ) { echo '<h1>' . esc_html( get_the_title() ) . '</h1>'; } } else { echo '<h1>No posts found!</h1>'; } ``` This has the advantage that it still calls all the functions of a standard loop, but they've been abstracted away. <https://wpscholar.com/blog/creating-better-wordpress-loop/> I'm sure there are others, but a standard loop is reliable predictable and readable to all
338,249
<p>Working within a Docker container (circleci/php:latest) and I'm struggling with wp-cli a bit. When I attempt to run <code>wp core install</code> I get a silent failure with 255 exit code. I enabled --debug hoping to get some more information but unfortunately all I can see is that it stops after reading wp-config.php.</p> <pre><code>circleci@142b5627c098:~/wordpress$ wp core install --url=example.com --title="Example" --admin_user=admin [email protected] --skip-email --debug Debug (bootstrap): Fallback autoloader paths: phar://wp-cli.phar/vendor/autoload.php (0.01s) Debug (bootstrap): Loading detected autoloader: phar://wp-cli.phar/vendor/autoload.php (0.011s) Debug (commands): Adding command: cache (0.015s) Debug (commands): Adding command: transient (0.017s) Debug (commands): Adding command: comment (0.019s) Debug (commands): Adding command: meta in comment Namespace (0.02s) Debug (commands): Adding command: menu (0.021s) Debug (commands): Adding command: item in menu Namespace (0.022s) Debug (commands): Adding command: location in menu Namespace (0.022s) Debug (commands): Deferring command: network meta (0.023s) Debug (commands): Adding command: option (0.024s) Debug (commands): Adding command: post (0.026s) Debug (commands): Adding command: meta in post Namespace (0.026s) Debug (commands): Adding command: term in post Namespace (0.027s) Debug (commands): Adding command: post-type (0.028s) Debug (commands): Adding command: site (0.03s) Debug (commands): Adding command: meta in site Namespace (0.031s) Debug (commands): Adding command: option in site Namespace (0.032s) Debug (commands): Adding command: taxonomy (0.033s) Debug (commands): Adding command: term (0.034s) Debug (commands): Adding command: meta in term Namespace (0.035s) Debug (commands): Adding command: user (0.037s) Debug (commands): Adding command: meta in user Namespace (0.038s) Debug (commands): Adding command: session in user Namespace (0.039s) Debug (commands): Adding command: term in user Namespace (0.04s) Debug (commands): Adding command: network (0.04s) Debug (hooks): Processing hook "after_add_command:network" with 1 callbacks (0.04s) Debug (hooks): On hook "after_add_command:network": Closure in file phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/class-wp-cli.php at line 634 (0.04s) Debug (commands): Adding command: meta in network Namespace (0.041s) Debug (commands): Adding command: db (0.044s) Debug (commands): Adding command: plugin (0.048s) Debug (commands): Adding command: theme (0.05s) Debug (commands): Adding command: mod in theme Namespace (0.051s) Debug (commands): Adding command: scaffold (0.053s) Debug (commands): Adding command: core (0.053s) Debug (commands): Adding command: verify-checksums in core Namespace (0.054s) Debug (commands): Adding command: verify-checksums in plugin Namespace (0.055s) Debug (commands): Adding command: export (0.056s) Debug (commands): Adding command: config (0.058s) Debug (commands): Adding command: core (0.06s) Debug (commands): Adding command: eval (0.061s) Debug (commands): Adding command: eval-file (0.061s) Debug (commands): Adding command: import (0.062s) Debug (commands): Adding command: media (0.063s) Debug (commands): Adding command: package (0.065s) Debug (commands): Adding command: cron (0.066s) Debug (commands): Adding command: event in cron Namespace (0.067s) Debug (commands): Adding command: schedule in cron Namespace (0.067s) Debug (commands): Adding command: embed (0.068s) Debug (commands): Adding command: fetch in embed Namespace (0.068s) Debug (commands): Adding command: provider in embed Namespace (0.069s) Debug (commands): Adding command: handler in embed Namespace (0.069s) Debug (commands): Adding command: cache in embed Namespace (0.07s) Debug (commands): Adding command: i18n (0.07s) Debug (commands): Adding command: make-pot in i18n Namespace (0.071s) Debug (commands): Adding command: make-json in i18n Namespace (0.072s) Debug (commands): Deferring command: language core (0.073s) Debug (commands): Deferring command: language plugin (0.073s) Debug (commands): Deferring command: language theme (0.074s) Debug (hooks): Immediately invoking on passed hook "after_add_command:site": Closure in file phar:///usr/local/bin/wp/vendor/wp-cli/language-command/language-command.php at line 39 (0.074s) Debug (commands): Adding command: switch-language in site Namespace (0.074s) Debug (commands): Adding command: language (0.074s) Debug (hooks): Processing hook "after_add_command:language" with 3 callbacks (0.074s) Debug (hooks): On hook "after_add_command:language": Closure in file phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/class-wp-cli.php at line 634 (0.074s) Debug (commands): Adding command: core in language Namespace (0.075s) Debug (hooks): On hook "after_add_command:language": Closure in file phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/class-wp-cli.php at line 634 (0.075s) Debug (commands): Adding command: plugin in language Namespace (0.076s) Debug (hooks): On hook "after_add_command:language": Closure in file phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/class-wp-cli.php at line 634 (0.076s) Debug (commands): Adding command: theme in language Namespace (0.076s) Debug (commands): Adding command: maintenance-mode (0.077s) Debug (commands): Adding command: rewrite (0.078s) Debug (commands): Adding command: rewrite (0.078s) Debug (commands): Adding command: cap (0.079s) Debug (commands): Adding command: role (0.08s) Debug (commands): Adding command: search-replace (0.082s) Debug (commands): Adding command: server (0.082s) Debug (commands): Adding command: shell (0.083s) Debug (commands): Adding command: super-admin (0.083s) Debug (commands): Adding command: widget (0.085s) Debug (commands): Adding command: sidebar (0.085s) Debug (bootstrap): Adding framework command: phar://wp-cli.phar/vendor/wp-cli/wp-cli/php/commands/cli.php (0.085s) Debug (commands): Adding command: cli (0.087s) Debug (commands): Adding command: cache in cli Namespace (0.088s) Debug (commands): Adding command: alias in cli Namespace (0.088s) Debug (bootstrap): Adding framework command: phar://wp-cli.phar/vendor/wp-cli/wp-cli/php/commands/help.php (0.088s) Debug (commands): Adding command: help (0.089s) Debug (bootstrap): No readable global config found (0.089s) Debug (bootstrap): No project config found (0.089s) Debug (bootstrap): argv: /usr/local/bin/wp core install --url=example.com --title="Example" --admin_user=admin [email protected] --skip-email --debug (0.09s) Debug (bootstrap): ABSPATH defined: /home/circleci/wordpress/ (0.09s) Debug (bootstrap): Set URL: example.com (0.09s) Debug (bootstrap): Begin WordPress load (0.09s) Debug (bootstrap): wp-config.php path: /home/circleci/wordpress/wp-config.php (0.09s) circleci@142b5627c098:~/wordpress$ </code></pre> <p>I've tried regenerating wp-config using <code>wp config create</code> with just the bare minimum and visually inspected and it seems fine but no change.</p>
[ { "answer_id": 338256, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 0, "selected": false, "text": "<p>Ah! Now I just saw, that you are in a CircleCI container! I heavily rely on CircleCI containers for WordPress development. And I remember I once had the same problem. It's because your host needs to be specified as <code>127.0.0.1</code> with <code>--dbhost</code> like this:</p>\n\n<pre><code>$ wp config create --dbname=circle_test --dbuser=root --dbpass=\"\" --dbhost=127.0.0.1\n</code></pre>\n\n<hr>\n\n<p>I also have a working sample repo live which may help you further: <a href=\"https://github.com/leymannx/wordpress-circleci-behat\" rel=\"nofollow noreferrer\">https://github.com/leymannx/wordpress-circleci-behat</a>. Maybe you can check your <code>.circleci/config.yml</code> against the one from this repo to find the culprit.</p>\n" }, { "answer_id": 338289, "author": "Derek Held", "author_id": 168370, "author_profile": "https://wordpress.stackexchange.com/users/168370", "pm_score": 3, "selected": true, "text": "<p>I was missing some php extensions that wp-cli and/or WordPress needed but there is no error output stating as much. I'm guessing it was specifically the missing mysqli extension.</p>\n\n<p>I used a <a href=\"https://github.com/johnbillion/ext\" rel=\"nofollow noreferrer\">WP-CLI command</a> to test the base container for missing extensions and now I have <code>sudo docker-php-ext-install gd sockets mysqli exif</code> in my config.yml.</p>\n\n<p>Thanks to @leymannx for linking his own repo that got me onto the right track.</p>\n" } ]
2019/05/20
[ "https://wordpress.stackexchange.com/questions/338249", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168370/" ]
Working within a Docker container (circleci/php:latest) and I'm struggling with wp-cli a bit. When I attempt to run `wp core install` I get a silent failure with 255 exit code. I enabled --debug hoping to get some more information but unfortunately all I can see is that it stops after reading wp-config.php. ``` circleci@142b5627c098:~/wordpress$ wp core install --url=example.com --title="Example" --admin_user=admin [email protected] --skip-email --debug Debug (bootstrap): Fallback autoloader paths: phar://wp-cli.phar/vendor/autoload.php (0.01s) Debug (bootstrap): Loading detected autoloader: phar://wp-cli.phar/vendor/autoload.php (0.011s) Debug (commands): Adding command: cache (0.015s) Debug (commands): Adding command: transient (0.017s) Debug (commands): Adding command: comment (0.019s) Debug (commands): Adding command: meta in comment Namespace (0.02s) Debug (commands): Adding command: menu (0.021s) Debug (commands): Adding command: item in menu Namespace (0.022s) Debug (commands): Adding command: location in menu Namespace (0.022s) Debug (commands): Deferring command: network meta (0.023s) Debug (commands): Adding command: option (0.024s) Debug (commands): Adding command: post (0.026s) Debug (commands): Adding command: meta in post Namespace (0.026s) Debug (commands): Adding command: term in post Namespace (0.027s) Debug (commands): Adding command: post-type (0.028s) Debug (commands): Adding command: site (0.03s) Debug (commands): Adding command: meta in site Namespace (0.031s) Debug (commands): Adding command: option in site Namespace (0.032s) Debug (commands): Adding command: taxonomy (0.033s) Debug (commands): Adding command: term (0.034s) Debug (commands): Adding command: meta in term Namespace (0.035s) Debug (commands): Adding command: user (0.037s) Debug (commands): Adding command: meta in user Namespace (0.038s) Debug (commands): Adding command: session in user Namespace (0.039s) Debug (commands): Adding command: term in user Namespace (0.04s) Debug (commands): Adding command: network (0.04s) Debug (hooks): Processing hook "after_add_command:network" with 1 callbacks (0.04s) Debug (hooks): On hook "after_add_command:network": Closure in file phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/class-wp-cli.php at line 634 (0.04s) Debug (commands): Adding command: meta in network Namespace (0.041s) Debug (commands): Adding command: db (0.044s) Debug (commands): Adding command: plugin (0.048s) Debug (commands): Adding command: theme (0.05s) Debug (commands): Adding command: mod in theme Namespace (0.051s) Debug (commands): Adding command: scaffold (0.053s) Debug (commands): Adding command: core (0.053s) Debug (commands): Adding command: verify-checksums in core Namespace (0.054s) Debug (commands): Adding command: verify-checksums in plugin Namespace (0.055s) Debug (commands): Adding command: export (0.056s) Debug (commands): Adding command: config (0.058s) Debug (commands): Adding command: core (0.06s) Debug (commands): Adding command: eval (0.061s) Debug (commands): Adding command: eval-file (0.061s) Debug (commands): Adding command: import (0.062s) Debug (commands): Adding command: media (0.063s) Debug (commands): Adding command: package (0.065s) Debug (commands): Adding command: cron (0.066s) Debug (commands): Adding command: event in cron Namespace (0.067s) Debug (commands): Adding command: schedule in cron Namespace (0.067s) Debug (commands): Adding command: embed (0.068s) Debug (commands): Adding command: fetch in embed Namespace (0.068s) Debug (commands): Adding command: provider in embed Namespace (0.069s) Debug (commands): Adding command: handler in embed Namespace (0.069s) Debug (commands): Adding command: cache in embed Namespace (0.07s) Debug (commands): Adding command: i18n (0.07s) Debug (commands): Adding command: make-pot in i18n Namespace (0.071s) Debug (commands): Adding command: make-json in i18n Namespace (0.072s) Debug (commands): Deferring command: language core (0.073s) Debug (commands): Deferring command: language plugin (0.073s) Debug (commands): Deferring command: language theme (0.074s) Debug (hooks): Immediately invoking on passed hook "after_add_command:site": Closure in file phar:///usr/local/bin/wp/vendor/wp-cli/language-command/language-command.php at line 39 (0.074s) Debug (commands): Adding command: switch-language in site Namespace (0.074s) Debug (commands): Adding command: language (0.074s) Debug (hooks): Processing hook "after_add_command:language" with 3 callbacks (0.074s) Debug (hooks): On hook "after_add_command:language": Closure in file phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/class-wp-cli.php at line 634 (0.074s) Debug (commands): Adding command: core in language Namespace (0.075s) Debug (hooks): On hook "after_add_command:language": Closure in file phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/class-wp-cli.php at line 634 (0.075s) Debug (commands): Adding command: plugin in language Namespace (0.076s) Debug (hooks): On hook "after_add_command:language": Closure in file phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/class-wp-cli.php at line 634 (0.076s) Debug (commands): Adding command: theme in language Namespace (0.076s) Debug (commands): Adding command: maintenance-mode (0.077s) Debug (commands): Adding command: rewrite (0.078s) Debug (commands): Adding command: rewrite (0.078s) Debug (commands): Adding command: cap (0.079s) Debug (commands): Adding command: role (0.08s) Debug (commands): Adding command: search-replace (0.082s) Debug (commands): Adding command: server (0.082s) Debug (commands): Adding command: shell (0.083s) Debug (commands): Adding command: super-admin (0.083s) Debug (commands): Adding command: widget (0.085s) Debug (commands): Adding command: sidebar (0.085s) Debug (bootstrap): Adding framework command: phar://wp-cli.phar/vendor/wp-cli/wp-cli/php/commands/cli.php (0.085s) Debug (commands): Adding command: cli (0.087s) Debug (commands): Adding command: cache in cli Namespace (0.088s) Debug (commands): Adding command: alias in cli Namespace (0.088s) Debug (bootstrap): Adding framework command: phar://wp-cli.phar/vendor/wp-cli/wp-cli/php/commands/help.php (0.088s) Debug (commands): Adding command: help (0.089s) Debug (bootstrap): No readable global config found (0.089s) Debug (bootstrap): No project config found (0.089s) Debug (bootstrap): argv: /usr/local/bin/wp core install --url=example.com --title="Example" --admin_user=admin [email protected] --skip-email --debug (0.09s) Debug (bootstrap): ABSPATH defined: /home/circleci/wordpress/ (0.09s) Debug (bootstrap): Set URL: example.com (0.09s) Debug (bootstrap): Begin WordPress load (0.09s) Debug (bootstrap): wp-config.php path: /home/circleci/wordpress/wp-config.php (0.09s) circleci@142b5627c098:~/wordpress$ ``` I've tried regenerating wp-config using `wp config create` with just the bare minimum and visually inspected and it seems fine but no change.
I was missing some php extensions that wp-cli and/or WordPress needed but there is no error output stating as much. I'm guessing it was specifically the missing mysqli extension. I used a [WP-CLI command](https://github.com/johnbillion/ext) to test the base container for missing extensions and now I have `sudo docker-php-ext-install gd sockets mysqli exif` in my config.yml. Thanks to @leymannx for linking his own repo that got me onto the right track.
338,250
<p>I got it to work with this:</p> <pre><code>$url = home_url( add_query_arg( array(), $wp-&gt;request ) ); </code></pre> <p>However, if the permalink is plain, all I'm getting is the homepage url (instead of the post url).</p> <p>So what's the best way to get the current post or page address link?</p>
[ { "answer_id": 338251, "author": "Derek Held", "author_id": 168370, "author_profile": "https://wordpress.stackexchange.com/users/168370", "pm_score": 1, "selected": false, "text": "<p>Is there a reason why <a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"nofollow noreferrer\">get_permalink()</a> doesn't work for you? I'm unclear why you are trying to construct it manually.</p>\n" }, { "answer_id": 338258, "author": "mlimon", "author_id": 64458, "author_profile": "https://wordpress.stackexchange.com/users/64458", "pm_score": -1, "selected": false, "text": "<p>Yeap, this should't work with plain format. and also just <code>get_permalink()</code> also not going to solved your issue here. To solved your issue you need to first correct Page/Post id and WordPress default doesn't offer us any function to do that. So you need to make one to grab the correct id. example</p>\n\n<pre><code>/**\n * Get correct page or post id\n *\n * @return int\n */\nif ( !function_exists( 'get_the_real_ID' ) ) {\n function get_the_real_ID() {\n $post_id = 0;\n if (in_the_loop()) {\n $post_id = get_the_ID();\n } else {\n if ( is_front_page() &amp;&amp; !is_home() ) {\n $frontpage_id = get_option( 'page_on_front' );\n $post_id = $frontpage_id;\n } elseif ( !is_front_page() &amp;&amp; is_home() ) {\n $page_for_posts = get_option( 'page_for_posts' );\n $post_id = $page_for_posts;\n } else {\n global $wp_query;\n $page_object = $wp_query-&gt;get_queried_object();\n\n if ( is_page() || is_singular() ) {\n $post_id = $wp_query-&gt;get_queried_object_id();\n } else {\n $post_id = 0;\n }\n }\n }\n return $post_id;\n }\n} \n</code></pre>\n\n<p>Now just use this ID to grab your page/post url like this.</p>\n\n<pre><code>$id = get_the_real_ID();\n$current_url = (empty($id)) ? home_url() : get_permalink($id);\n</code></pre>\n\n<p>I'm not sure that this is the best or perfect solution for your case or not but it should at-least will be work as you expected. I assume that you might change the permalink format or want to grab the proper url whatever format used? and uppon that I share this method. try and let me know.</p>\n" }, { "answer_id": 338955, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>Don't use <code>get_permalink()</code>. That function is intended for use inside the loop, and only works for getting the link to posts. It will not work for taxonomy archives, date archives, search results, or the latest posts page.</p>\n\n<p>Normally you can get the URL to the current page with <code>home_url()</code> combined with <code>$wp-&gt;request</code>:</p>\n\n<pre><code>global $wp;\necho home_url( $wp-&gt;request );\n</code></pre>\n\n<p>This is because <code>home_url()</code> gets your site URL from the database, while <code>$wp-&gt;request</code> holds the path for the current request, which will be the slug for pages, date for archives, etc.</p>\n\n<p>The problem with plain permalinks is that they don't use the request path, because this requires the standard .htaccess setup. Instead WordPress uses the query string to determine what to load.</p>\n\n<p>So what you need to do is get the current query vars and append <em>those</em> to the URL. Thankfully those are also available in <code>$wp</code>, specifically as <code>$wp-&gt;query_vars</code>. This is an array of vars and values, so you can pass it directly to <code>add_query_arg();</code>:</p>\n\n<pre><code>global $wp;\necho add_query_arg( $wp-&gt;query_vars, home_url() );\n</code></pre>\n" } ]
2019/05/20
[ "https://wordpress.stackexchange.com/questions/338250", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131331/" ]
I got it to work with this: ``` $url = home_url( add_query_arg( array(), $wp->request ) ); ``` However, if the permalink is plain, all I'm getting is the homepage url (instead of the post url). So what's the best way to get the current post or page address link?
Is there a reason why [get\_permalink()](https://developer.wordpress.org/reference/functions/get_permalink/) doesn't work for you? I'm unclear why you are trying to construct it manually.
338,280
<p>I'm trying to get rid of the function where users can hover over the main product image and zoom into the product. I tried using this code, which has been confirmed by others to work, but nothing changed.</p> <pre><code>function remove_image_zoom_support() { remove_theme_support( 'wc-product-gallery-zoom' ); } add_action( 'wp', 'remove_image_zoom_support', 100 ); </code></pre> <p>Is this because some other function I'm using is interfering with it?</p> <p>Here is my functions file:</p> <pre><code>&lt;?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()-&gt;get('Version') ); wp_enqueue_style( 'my-google-fonts', 'http://fonts.googleapis.com/css?family=Lekton', false ); } //* Redirect archive pages to the home page function redirect_to_home( $query ){ if(is_archive() ) { wp_redirect( home_url() ); exit; } } add_action( 'parse_query', 'redirect_to_home' ); //* Add CPT taxonomy terms to body class function add_taxonomy_to_single( $classes ) { if ( is_single() ) { global $post; $my_terms = get_the_terms( $post-&gt;ID, 'skill' ); if ( $my_terms &amp;&amp; ! is_wp_error( $my_terms ) ) { foreach ($my_terms as $term) { $classes[] = $term-&gt;slug; } } } return $classes; } add_filter( 'body_class', 'add_taxonomy_to_single' ); //* Add page slug body class function add_slug_body_class( $classes ) { global $post; if ( isset( $post ) ) { $classes[] = $post-&gt;post_type . '-' . $post-&gt;post_name; } return $classes; } add_filter( 'body_class', 'add_slug_body_class' ); //* Unload Gutenberg Block Editor add_action( 'wp_print_styles', 'wps_deregister_styles', 100 ); function wps_deregister_styles() { wp_dequeue_style( 'wp-block-library' ); } //* Use Google's jQuery add_action('init', 'use_jquery_from_google'); function use_jquery_from_google () { if (is_admin()) { return; } global $wp_scripts; if (isset($wp_scripts-&gt;registered['jquery']-&gt;ver)) { $ver = $wp_scripts-&gt;registered['jquery']-&gt;ver; } else { $ver = '3.4.0'; } wp_deregister_script('jquery'); wp_register_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver); } //* Remove Testimonials post type add_action( 'init', 'remove_testimonial_cpt', 1000 ); function remove_testimonial_cpt() { unregister_post_type( 'testimonial' ); } //* Remove WYSIWYG editor from products add_action('init', 'init_remove_support',100); function init_remove_support(){ $post_type = 'product'; remove_post_type_support( $post_type, 'editor'); } //* Change gallery thumbnail sizes add_filter( 'woocommerce_get_image_size_gallery_thumbnail', function( $size ) { return array( 'width' =&gt; 132, 'height' =&gt; 162, 'crop' =&gt; 0, ); }); //* Remove Proceed to Checkout button on Cart page remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20); //* Remove thumbnails from Cart page add_filter( 'woocommerce_cart_item_thumbnail', '__return_false' ); //* Remove results count and dropdown on main shop page remove_action( 'woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 30 ); remove_action( 'woocommerce_before_shop_loop', 'woocommerce_result_count', 20 ); //* Remove additional information tab on single shop page add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 ); function woo_remove_product_tabs( $tabs ) { unset( $tabs['additional_information'] ); return $tabs; } //* Add gallery captions for shop items function gcw_insert_captions( $html, $attachment_id ) { $captions = ''; $title = get_post_field( 'post_title', $attachment_id ); if( !empty( $title ) ) { $captions .= '&lt;h3&gt;' . esc_html( $title ) . '&lt;/h3&gt;'; } if( !empty( $captions ) ) { $captions = '&lt;div class="gcw-caption"&gt;' . $captions . '&lt;/div&gt;'; $html = preg_replace('~&lt;\/div&gt;$~', $captions . '&lt;/div&gt;', $html ); } return $html; } add_filter( 'woocommerce_single_product_image_thumbnail_html', 'gcw_insert_captions', 10, 2 ); //* Remove hover zoom function remove_image_zoom_support() { remove_theme_support( 'wc-product-gallery-zoom' ); } add_action( 'wp', 'remove_image_zoom_support', 100 ); ?&gt; </code></pre> <p>If not, what could be causing this issue?</p>
[ { "answer_id": 338287, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 4, "selected": true, "text": "<p>This is possible using <code>woocommerce_single_product_zoom_enabled</code> dedicated filter hook:</p>\n\n<pre><code>add_filter( 'woocommerce_single_product_zoom_enabled', '__return_false' );\n</code></pre>\n\n<p>Code goes in functions.php file of your active child theme (or active theme). Tested and work.</p>\n\n<hr>\n\n<p>It is possible using <code>woocommerce_single_product_zoom_enabled</code> dedicated filter hook.</p>\n\n<blockquote>\n <p>The hook <strong>undocumented available parameters</strong> in the options array are:</p>\n\n<pre><code>$zoom_options = array (\n 'url' =&gt; false,\n 'callback' =&gt; false,\n 'target' =&gt; false,\n 'duration' =&gt; 120, // Transition in milli seconds (default is 120)\n 'on' =&gt; 'mouseover', // other options: grab, click, toggle (default is mouseover)\n 'touch' =&gt; true, // enables a touch fallback\n 'onZoomIn' =&gt; false,\n 'onZoomOut' =&gt; false,\n 'magnify' =&gt; 1, // Zoom magnification: (default is 1 | float number between 0 and 1)\n);\n</code></pre>\n</blockquote>\n\n<p>Usage with <code>woocommerce_single_product_zoom_options</code> filter hook:</p>\n\n<p>1) <strong>Disable the zoom</strong>:</p>\n\n<pre><code>add_filter( 'woocommerce_single_product_zoom_options', 'custom_single_product_zoom_options', 10, 3 );\nfunction custom_single_product_zoom_options( $zoom_options ) {\n // Disable zoom magnify:\n $zoom_options['magnify'] = 0;\n\n return $zoom_options;\n}\n</code></pre>\n\n<p>2) <strong>Change zoom event option</strong>:</p>\n\n<pre><code>add_filter( 'woocommerce_single_product_zoom_options', 'custom_single_product_zoom_options', 10, 3 );\nfunction custom_single_product_zoom_options( $zoom_options ) {\n // Changing the zoom event option:\n $zoom_options['on'] = 'click';\n\n return $zoom_options;\n}\n</code></pre>\n\n<p>Code goes in functions.php file of your active child theme (or active theme). Tested and work.</p>\n\n<p>Related: <a href=\"https://stackoverflow.com/questions/53584936/adjusting-product-images-zoom-magnification-factor-in-woocommerce-3/53585353#53585353\">Adjusting product image's Zoom magnification factor in woocommerce 3</a></p>\n" }, { "answer_id": 387057, "author": "jod.z", "author_id": 205334, "author_profile": "https://wordpress.stackexchange.com/users/205334", "pm_score": 0, "selected": false, "text": "<p>I wanted to disable the zoom and also have the featured image trigger the lightbox. Someone gave me this code and it worked.</p>\n<pre><code>add_action( 'after_setup_theme', 'add_wc_gallery_lightbox', 100 );\nfunction add_wc_gallery_lightbox() { \n remove_theme_support( 'wc-product-gallery-zoom' );\n}\n</code></pre>\n" }, { "answer_id": 388163, "author": "artnikpro", "author_id": 77747, "author_profile": "https://wordpress.stackexchange.com/users/77747", "pm_score": 0, "selected": false, "text": "<p>Disable gallery zoom and prevent loading <code>jquery.zoom.js</code> lib</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('woocommerce_single_product_zoom_enabled', '__return_false');\nadd_action('after_setup_theme', function () {\n global $_wp_theme_features;\n unset($_wp_theme_features['wc-product-gallery-zoom']);\n});\n</code></pre>\n" } ]
2019/05/20
[ "https://wordpress.stackexchange.com/questions/338280", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18320/" ]
I'm trying to get rid of the function where users can hover over the main product image and zoom into the product. I tried using this code, which has been confirmed by others to work, but nothing changed. ``` function remove_image_zoom_support() { remove_theme_support( 'wc-product-gallery-zoom' ); } add_action( 'wp', 'remove_image_zoom_support', 100 ); ``` Is this because some other function I'm using is interfering with it? Here is my functions file: ``` <?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); wp_enqueue_style( 'my-google-fonts', 'http://fonts.googleapis.com/css?family=Lekton', false ); } //* Redirect archive pages to the home page function redirect_to_home( $query ){ if(is_archive() ) { wp_redirect( home_url() ); exit; } } add_action( 'parse_query', 'redirect_to_home' ); //* Add CPT taxonomy terms to body class function add_taxonomy_to_single( $classes ) { if ( is_single() ) { global $post; $my_terms = get_the_terms( $post->ID, 'skill' ); if ( $my_terms && ! is_wp_error( $my_terms ) ) { foreach ($my_terms as $term) { $classes[] = $term->slug; } } } return $classes; } add_filter( 'body_class', 'add_taxonomy_to_single' ); //* Add page slug body class function add_slug_body_class( $classes ) { global $post; if ( isset( $post ) ) { $classes[] = $post->post_type . '-' . $post->post_name; } return $classes; } add_filter( 'body_class', 'add_slug_body_class' ); //* Unload Gutenberg Block Editor add_action( 'wp_print_styles', 'wps_deregister_styles', 100 ); function wps_deregister_styles() { wp_dequeue_style( 'wp-block-library' ); } //* Use Google's jQuery add_action('init', 'use_jquery_from_google'); function use_jquery_from_google () { if (is_admin()) { return; } global $wp_scripts; if (isset($wp_scripts->registered['jquery']->ver)) { $ver = $wp_scripts->registered['jquery']->ver; } else { $ver = '3.4.0'; } wp_deregister_script('jquery'); wp_register_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver); } //* Remove Testimonials post type add_action( 'init', 'remove_testimonial_cpt', 1000 ); function remove_testimonial_cpt() { unregister_post_type( 'testimonial' ); } //* Remove WYSIWYG editor from products add_action('init', 'init_remove_support',100); function init_remove_support(){ $post_type = 'product'; remove_post_type_support( $post_type, 'editor'); } //* Change gallery thumbnail sizes add_filter( 'woocommerce_get_image_size_gallery_thumbnail', function( $size ) { return array( 'width' => 132, 'height' => 162, 'crop' => 0, ); }); //* Remove Proceed to Checkout button on Cart page remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20); //* Remove thumbnails from Cart page add_filter( 'woocommerce_cart_item_thumbnail', '__return_false' ); //* Remove results count and dropdown on main shop page remove_action( 'woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 30 ); remove_action( 'woocommerce_before_shop_loop', 'woocommerce_result_count', 20 ); //* Remove additional information tab on single shop page add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 ); function woo_remove_product_tabs( $tabs ) { unset( $tabs['additional_information'] ); return $tabs; } //* Add gallery captions for shop items function gcw_insert_captions( $html, $attachment_id ) { $captions = ''; $title = get_post_field( 'post_title', $attachment_id ); if( !empty( $title ) ) { $captions .= '<h3>' . esc_html( $title ) . '</h3>'; } if( !empty( $captions ) ) { $captions = '<div class="gcw-caption">' . $captions . '</div>'; $html = preg_replace('~<\/div>$~', $captions . '</div>', $html ); } return $html; } add_filter( 'woocommerce_single_product_image_thumbnail_html', 'gcw_insert_captions', 10, 2 ); //* Remove hover zoom function remove_image_zoom_support() { remove_theme_support( 'wc-product-gallery-zoom' ); } add_action( 'wp', 'remove_image_zoom_support', 100 ); ?> ``` If not, what could be causing this issue?
This is possible using `woocommerce_single_product_zoom_enabled` dedicated filter hook: ``` add_filter( 'woocommerce_single_product_zoom_enabled', '__return_false' ); ``` Code goes in functions.php file of your active child theme (or active theme). Tested and work. --- It is possible using `woocommerce_single_product_zoom_enabled` dedicated filter hook. > > The hook **undocumented available parameters** in the options array are: > > > > ``` > $zoom_options = array ( > 'url' => false, > 'callback' => false, > 'target' => false, > 'duration' => 120, // Transition in milli seconds (default is 120) > 'on' => 'mouseover', // other options: grab, click, toggle (default is mouseover) > 'touch' => true, // enables a touch fallback > 'onZoomIn' => false, > 'onZoomOut' => false, > 'magnify' => 1, // Zoom magnification: (default is 1 | float number between 0 and 1) > ); > > ``` > > Usage with `woocommerce_single_product_zoom_options` filter hook: 1) **Disable the zoom**: ``` add_filter( 'woocommerce_single_product_zoom_options', 'custom_single_product_zoom_options', 10, 3 ); function custom_single_product_zoom_options( $zoom_options ) { // Disable zoom magnify: $zoom_options['magnify'] = 0; return $zoom_options; } ``` 2) **Change zoom event option**: ``` add_filter( 'woocommerce_single_product_zoom_options', 'custom_single_product_zoom_options', 10, 3 ); function custom_single_product_zoom_options( $zoom_options ) { // Changing the zoom event option: $zoom_options['on'] = 'click'; return $zoom_options; } ``` Code goes in functions.php file of your active child theme (or active theme). Tested and work. Related: [Adjusting product image's Zoom magnification factor in woocommerce 3](https://stackoverflow.com/questions/53584936/adjusting-product-images-zoom-magnification-factor-in-woocommerce-3/53585353#53585353)
338,281
<p>I think i'm probably doing something daft here. Every time i try to include this as a mu-plugin it takes down the test site though. </p> <pre><code>&lt;?php if( is_plugin_active( '/public_html/wp-content/plugins/wordfence.php' ) ) { require_once('wp-load.php'); $to = ‘[email protected]’; $subject = ‘Wordfence is down’; $message = ‘Wordfence is not active’; $headers = array('Content-Type: text/html; charset=UTF-8'); wp_mail( $to, $subject, $message, $headers ); } </code></pre> <p>Any ideas where i'm going wrong would be very much appreciated :)</p>
[ { "answer_id": 338282, "author": "MikeNGarrett", "author_id": 1670, "author_profile": "https://wordpress.stackexchange.com/users/1670", "pm_score": 2, "selected": false, "text": "<p>It's best to turn on <code>WP_DEBUG</code> to see exactly what problem you're facing. The code above includes fancy quotes like <code>‘</code> and <code>’</code> and doesn't include the full path to <code>wp-load.php</code>. </p>\n" }, { "answer_id": 338284, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 2, "selected": true, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/is_plugin_active\" rel=\"nofollow noreferrer\"><code>is_plugin_active</code></a> isn't available for mu-plugins to use. The codex says:</p>\n\n<blockquote>\n <p>NOTE: defined in wp-admin/includes/plugin.php, so this is only available from within the admin pages, and any references to this function must be hooked to admin_init or a later action. If you want to use this function from within a template or a must-use plugin, you will need to manually require plugin.php, an example is below.</p>\n</blockquote>\n\n<p>And I think there must be better ways to solve this anyway: your code will try and send you an email for every non-static HTTP request to the site, and you probably meant <code>!is_plugin_active</code> or <code>is_plugin_inactive</code>, and in any case these accept relative paths to the plugin files not absolute paths.</p>\n" } ]
2019/05/20
[ "https://wordpress.stackexchange.com/questions/338281", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168399/" ]
I think i'm probably doing something daft here. Every time i try to include this as a mu-plugin it takes down the test site though. ``` <?php if( is_plugin_active( '/public_html/wp-content/plugins/wordfence.php' ) ) { require_once('wp-load.php'); $to = ‘[email protected]’; $subject = ‘Wordfence is down’; $message = ‘Wordfence is not active’; $headers = array('Content-Type: text/html; charset=UTF-8'); wp_mail( $to, $subject, $message, $headers ); } ``` Any ideas where i'm going wrong would be very much appreciated :)
[`is_plugin_active`](https://codex.wordpress.org/Function_Reference/is_plugin_active) isn't available for mu-plugins to use. The codex says: > > NOTE: defined in wp-admin/includes/plugin.php, so this is only available from within the admin pages, and any references to this function must be hooked to admin\_init or a later action. If you want to use this function from within a template or a must-use plugin, you will need to manually require plugin.php, an example is below. > > > And I think there must be better ways to solve this anyway: your code will try and send you an email for every non-static HTTP request to the site, and you probably meant `!is_plugin_active` or `is_plugin_inactive`, and in any case these accept relative paths to the plugin files not absolute paths.
338,288
<p>I have SSL certificate activated on my website. I did change the settings:</p> <pre><code>setting &gt; general </code></pre> <p>and edit <code>wp-config.php</code> to force HTTPS:</p> <pre><code>define( 'FORCE_SSL_ADMIN', true ); </code></pre> <p>The problem is, the redirect doesn't work and both versions of the site, HTTP and HTTPS, are accessible.</p> <p>I checked my <code>.htaccess</code> file. It seems everything is correct:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteCond %{HTTPS} on [OR] RewriteCond %{SERVER_PORT} ^443$ [OR] RewriteCond %{HTTP:X-Forwarded-Proto} https RewriteRule .* - [E=WPR_SSL:-https] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteRule .* - [E=WPR_ENC:_gzip] RewriteCond %{REQUEST_METHOD} GET RewriteCond %{QUERY_STRING} ="" RewriteCond %{HTTP:Cookie} !(wordpress_logged_in_.+|wp-postpass_|wptouch_switch_toggle|comment_author_|comment_author_email_) [NC] RewriteCond %{REQUEST_URI} !^(/(.+/)?feed/?|/(?:.+/)?embed/|/checkout/(.*)|/cart/|/my-account/(.*)|/wc-api/v(.*)|/(index\.php/)?wp\-json(/.*|$))$ [NC] RewriteCond %{HTTP_USER_AGENT} !^(facebookexternalhit).* [NC] RewriteCond "%{DOCUMENT_ROOT}/wp-content/cache/wp-rocket/%{HTTP_HOST}%{REQUEST_URI}/index%{ENV:WPR_SSL}.html%{ENV:WPR_ENC}" -f RewriteRule .* "/wp-content/cache/wp-rocket/%{HTTP_HOST}%{REQUEST_URI}/index%{ENV:WPR_SSL}.html%{ENV:WPR_ENC}" [L] &lt;/IfModule&gt; </code></pre> <p><strong>UPDATE</strong></p> <p>I have <strong>WP-ROCKET</strong> plugin and I think this is the main source of the problem because whenever I clear the cache and refresh the site from HTTP address it redirects correctly but just one time</p>
[ { "answer_id": 338290, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 1, "selected": false, "text": "<p>Your rewrite conditions, line 4 to 6 in your code, apply when https is active, so you are redirecting from https to https. Consquently you should change the conditions to check, if https is not active, ergo <code>!on</code> and <code>!^443$</code> and <code>!https</code>. Additionally I'm not sure about the rule <code>RewriteRule .* - [E=WPR_SSL:-https]</code>, probably something WP Rocket specific and out of scope here, which is why I suggest to possibly replace it with <code>RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]</code>.</p>\n\n<p>In conclusion, I'd say, replace line 4 to 7 of your <code>.htaccess</code> with:</p>\n\n<pre><code>RewriteCond %{HTTPS} off\nRewriteCond %{SERVER_PORT} !^443$\nRewriteCond %{HTTP:X-Forwarded-Proto} !https\nRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n" }, { "answer_id": 338629, "author": "Kamran Asgari", "author_id": 163748, "author_profile": "https://wordpress.stackexchange.com/users/163748", "pm_score": 1, "selected": true, "text": "<p>with adding this simple rules to your <code>.htacces</code>s file\nyou can override any possible conflict with plugins and redirect issues</p>\n\n<p>don't forget to add these lines to the beginning of <code>.htaccess</code></p>\n\n<pre><code>RewriteCond %{HTTP:CF-Visitor} '\"scheme\":\"http\"'\nRewriteRule ^(.*)$ https://www.example.com/$1 [L]\n</code></pre>\n" } ]
2019/05/20
[ "https://wordpress.stackexchange.com/questions/338288", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/163748/" ]
I have SSL certificate activated on my website. I did change the settings: ``` setting > general ``` and edit `wp-config.php` to force HTTPS: ``` define( 'FORCE_SSL_ADMIN', true ); ``` The problem is, the redirect doesn't work and both versions of the site, HTTP and HTTPS, are accessible. I checked my `.htaccess` file. It seems everything is correct: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{HTTPS} on [OR] RewriteCond %{SERVER_PORT} ^443$ [OR] RewriteCond %{HTTP:X-Forwarded-Proto} https RewriteRule .* - [E=WPR_SSL:-https] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteRule .* - [E=WPR_ENC:_gzip] RewriteCond %{REQUEST_METHOD} GET RewriteCond %{QUERY_STRING} ="" RewriteCond %{HTTP:Cookie} !(wordpress_logged_in_.+|wp-postpass_|wptouch_switch_toggle|comment_author_|comment_author_email_) [NC] RewriteCond %{REQUEST_URI} !^(/(.+/)?feed/?|/(?:.+/)?embed/|/checkout/(.*)|/cart/|/my-account/(.*)|/wc-api/v(.*)|/(index\.php/)?wp\-json(/.*|$))$ [NC] RewriteCond %{HTTP_USER_AGENT} !^(facebookexternalhit).* [NC] RewriteCond "%{DOCUMENT_ROOT}/wp-content/cache/wp-rocket/%{HTTP_HOST}%{REQUEST_URI}/index%{ENV:WPR_SSL}.html%{ENV:WPR_ENC}" -f RewriteRule .* "/wp-content/cache/wp-rocket/%{HTTP_HOST}%{REQUEST_URI}/index%{ENV:WPR_SSL}.html%{ENV:WPR_ENC}" [L] </IfModule> ``` **UPDATE** I have **WP-ROCKET** plugin and I think this is the main source of the problem because whenever I clear the cache and refresh the site from HTTP address it redirects correctly but just one time
with adding this simple rules to your `.htacces`s file you can override any possible conflict with plugins and redirect issues don't forget to add these lines to the beginning of `.htaccess` ``` RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' RewriteRule ^(.*)$ https://www.example.com/$1 [L] ```
338,301
<p>Just installed the new 2019 theme. The customizer offers "default" and "custom" color options. When you select "custom", it shows a slider to pick the color, not the normal color-picker.</p> <p>Unfortunately, using that slider is pretty hit and miss and the customizer does not offer a way to enter a precise color (hue).</p> <p>Where do I need to go and what do I need to do to enter a precise color for this theme?</p> <p>Note: I am NOT looking for a way to enter HEX color values. The slider seems to be focused on hue (as @leymannx answer confirms), but simply a way to be more precise than the slider allows me to be.</p> <p>PS: I am no rooky with databases and code, so okay to send me there.</p>
[ { "answer_id": 338318, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 3, "selected": true, "text": "<p>That's indeed an interesting question. Looking at the following issues - both closed as won't fix - I'd reason that replacing this color slider with a color picker is not recommended:</p>\n\n<ul>\n<li><a href=\"https://github.com/WordPress/twentynineteen/issues/613\" rel=\"nofollow noreferrer\">https://github.com/WordPress/twentynineteen/issues/613</a></li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/45619\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/45619</a></li>\n</ul>\n\n<p>Thing is, that Twenty Nineteen calculates the colors that will be displayed in the frontend from hue, saturation and lightness (<a href=\"https://en.wikipedia.org/wiki/HSL_and_HSV\" rel=\"nofollow noreferrer\">HSL</a>). And it does that for maximum accessibility. Letting users pick their own Hex values led to very inaccessible color combinations in places where different nuances of a color are used for example for hover and select states or for overlays.</p>\n\n<p>So actually, your best bet is to either disable the color slider in your child theme and completely customize the CSS from your child theme's styles sheets:</p>\n\n<pre><code>function wpse_338301_customize_register( $wp_customize ) {\n $wp_customize-&gt;remove_section( 'colors' );\n}\nadd_action( 'customize_register', 'wpse_338301_customizer' );\n</code></pre>\n\n<p>Or – and that's not recommended – disable the color slider from your child theme as shown above and override the default values by converting your Hex color to HSL and adjust all the different color nuances by adding filters for all the different values you'd need to adjust. Taking your question's ID as Hex value <code>#338301</code> for example in HSL that would be <code>hsl(97, 98%, 26%)</code>. I used a random free online Hex to HSL color converter.</p>\n\n<p><a href=\"https://i.stack.imgur.com/r7GPz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/r7GPz.png\" alt=\"enter image description here\"></a></p>\n\n<p>First set the hue value:</p>\n\n<pre><code>function wpse_338301_init() {\n set_theme_mod( 'primary_color', 'custom' );\n set_theme_mod( 'primary_color_hue', 97 );\n}\nadd_action( 'init', 'wpse_338301_init' );\n</code></pre>\n\n<p>Next set all saturation values:</p>\n\n<pre><code>function wpse_338301_saturation() {\n return 98;\n}\nadd_filter( 'twentynineteen_custom_colors_saturation', 'wpse_338301_saturation' );\nadd_filter( 'twentynineteen_custom_colors_saturation_selection', 'wpse_338301_saturation' );\n</code></pre>\n\n<p>And finally all lightness values:</p>\n\n<pre><code>function wpse_338301_lightness() {\n return 26;\n}\nadd_filter( 'twentynineteen_custom_colors_lightness', 'wpse_338301_lightness' );\nadd_filter( 'twentynineteen_custom_colors_lightness_hover', 'wpse_338301_lightness' );\nadd_filter( 'twentynineteen_custom_colors_lightness_selection', 'wpse_338301_lightness' );\n</code></pre>\n\n<p>For more info see Twenty Nineteen's <a href=\"https://github.com/WordPress/twentynineteen/blob/master/inc/color-patterns.php\" rel=\"nofollow noreferrer\"><code>inc/color-patterns.php</code></a>.</p>\n" }, { "answer_id": 376593, "author": "SuperAtic", "author_id": 74492, "author_profile": "https://wordpress.stackexchange.com/users/74492", "pm_score": 0, "selected": false, "text": "<p>Another option can be overwriteing the default CSS rules with new ones in your theme style.css as shown below. This also allow to have different colors for different elements (if needed).</p>\n<pre><code>/* ---------------- */\n/* 3. 2020 Theme Primary colors\n/* ---------------- */\n.primary-menu a,\n/*Arrows in Desktop*/\n.primary-menu span.icon,\n/*Categories in Single Posts*/\n.entry-categories a,\n/*The Menus*/\n.expanded-menu a,\n.mobile-menu a,\n.footer-menu a,\n/*Widgets*/\n.widget-content a,\n/*The Drop Cap*/\n.has-drop-cap:not(:focus)::first-letter,\n/*Latest Posts Block*/\n.wp-block-latest-posts a,\n/*Archives Block*/\n.wp-block-archives a,\n/*Categories Block*/\n.wp-block-categories a,\n/*Latest Comments Block*/\n.wp-block-latest-comments a,\n/*Calendar Block*/\n.wp-block-calendar a,\n/*File Block*/\n.wp-block-file a,\n/*Archive Page Title &quot;Span&quot;*/\n.archive-title .color-accent,\n/*Links in Single Posts; If we don't use P it will affect the buttons*/\n.entry-content p a,\n/*Pagination in Single Posts*/\n.pagination-single a {\n color:#CD2653;\n}\n\n/*Social Menu*/\n.social-menu a,\n/*Groups with accent bg*/\n:root .has-accent-background-color,\n/*Button Block*/\n.wp-block-button__link,\n/*Reply Comments*/\n.comment-reply-link,\n/*Input buttons such us &quot;Post Comment&quot;*/\ninput#submit,\ninput.search-submit {\n background-color:#CD2653;\n}\n\n/*File Block Button*/\n.wp-block-file__button {\n background-color:#CD2653!important;\n}\n\n/*Quotes*/\nblockquote {\n border-color:#CD2653;\n}\n</code></pre>\n<p>... and replace the default colour #CD2653 with your preferred one</p>\n" } ]
2019/05/20
[ "https://wordpress.stackexchange.com/questions/338301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/341/" ]
Just installed the new 2019 theme. The customizer offers "default" and "custom" color options. When you select "custom", it shows a slider to pick the color, not the normal color-picker. Unfortunately, using that slider is pretty hit and miss and the customizer does not offer a way to enter a precise color (hue). Where do I need to go and what do I need to do to enter a precise color for this theme? Note: I am NOT looking for a way to enter HEX color values. The slider seems to be focused on hue (as @leymannx answer confirms), but simply a way to be more precise than the slider allows me to be. PS: I am no rooky with databases and code, so okay to send me there.
That's indeed an interesting question. Looking at the following issues - both closed as won't fix - I'd reason that replacing this color slider with a color picker is not recommended: * <https://github.com/WordPress/twentynineteen/issues/613> * <https://core.trac.wordpress.org/ticket/45619> Thing is, that Twenty Nineteen calculates the colors that will be displayed in the frontend from hue, saturation and lightness ([HSL](https://en.wikipedia.org/wiki/HSL_and_HSV)). And it does that for maximum accessibility. Letting users pick their own Hex values led to very inaccessible color combinations in places where different nuances of a color are used for example for hover and select states or for overlays. So actually, your best bet is to either disable the color slider in your child theme and completely customize the CSS from your child theme's styles sheets: ``` function wpse_338301_customize_register( $wp_customize ) { $wp_customize->remove_section( 'colors' ); } add_action( 'customize_register', 'wpse_338301_customizer' ); ``` Or – and that's not recommended – disable the color slider from your child theme as shown above and override the default values by converting your Hex color to HSL and adjust all the different color nuances by adding filters for all the different values you'd need to adjust. Taking your question's ID as Hex value `#338301` for example in HSL that would be `hsl(97, 98%, 26%)`. I used a random free online Hex to HSL color converter. [![enter image description here](https://i.stack.imgur.com/r7GPz.png)](https://i.stack.imgur.com/r7GPz.png) First set the hue value: ``` function wpse_338301_init() { set_theme_mod( 'primary_color', 'custom' ); set_theme_mod( 'primary_color_hue', 97 ); } add_action( 'init', 'wpse_338301_init' ); ``` Next set all saturation values: ``` function wpse_338301_saturation() { return 98; } add_filter( 'twentynineteen_custom_colors_saturation', 'wpse_338301_saturation' ); add_filter( 'twentynineteen_custom_colors_saturation_selection', 'wpse_338301_saturation' ); ``` And finally all lightness values: ``` function wpse_338301_lightness() { return 26; } add_filter( 'twentynineteen_custom_colors_lightness', 'wpse_338301_lightness' ); add_filter( 'twentynineteen_custom_colors_lightness_hover', 'wpse_338301_lightness' ); add_filter( 'twentynineteen_custom_colors_lightness_selection', 'wpse_338301_lightness' ); ``` For more info see Twenty Nineteen's [`inc/color-patterns.php`](https://github.com/WordPress/twentynineteen/blob/master/inc/color-patterns.php).
338,306
<p>I am wanting to download themes from my localhost install of Wordpress. My issue is that anytime I click download, I get a pop-up asking me for Connection Information. </p> <p>I tried to input localhost and my Wordpress username and password, but it will not download. What step have I missed here?</p> <p><strong>edit</strong><br> And I am running localhost on a Ubuntu laptop with LAMP installed.</p> <p><strong>edit 2</strong><br> This is an image of the request screen that I get, where I input localhost and my valid username and password <a href="https://i.stack.imgur.com/nB5qo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nB5qo.png" alt="Image1"></a></p> <p>And this is an image of the error I receive when I try those reds <a href="https://i.stack.imgur.com/uX48X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uX48X.png" alt="Image 2"></a></p>
[ { "answer_id": 338325, "author": "Ted Stresen-Reuter", "author_id": 112766, "author_profile": "https://wordpress.stackexchange.com/users/112766", "pm_score": 0, "selected": false, "text": "<p>Try entering your system username and password. It sounds like you don't have permissions set correctly (or rather, in LAMP they are but not for what you are trying to do with WordPress). Also, you might have a look at the <a href=\"https://codex.wordpress.org/Editing_wp-config.php#WordPress_Upgrade_Constants\" rel=\"nofollow noreferrer\">FS_METHOD constant</a> and try setting it in to <code>ftpext</code> (along with the other required settings) in wp-config.php.</p>\n\n<p>If these things don't work, consider editing your question to include a screen shot of the username and password window you are seeing so that we know exactly which screen is blocking you.</p>\n" }, { "answer_id": 339218, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": true, "text": "<p>Probably your local FTP service is not running. You can verify this by trying to connect to the local FTP server at the command prompt:</p>\n\n<pre><code>ftp localserver\n</code></pre>\n\n<p>and it will ask for your credentials.</p>\n\n<p>Also possible is that 'localserver' is not being resolved locally. You can check that with a command</p>\n\n<pre><code>nslookup localserver\n</code></pre>\n\n<p>And seeing if it gives you your servers' IP address.</p>\n\n<p>But this is not a WP Development question. Ask the googles/bings/ducks for help with enabling/starting your local FTP service.</p>\n" } ]
2019/05/20
[ "https://wordpress.stackexchange.com/questions/338306", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102400/" ]
I am wanting to download themes from my localhost install of Wordpress. My issue is that anytime I click download, I get a pop-up asking me for Connection Information. I tried to input localhost and my Wordpress username and password, but it will not download. What step have I missed here? **edit** And I am running localhost on a Ubuntu laptop with LAMP installed. **edit 2** This is an image of the request screen that I get, where I input localhost and my valid username and password [![Image1](https://i.stack.imgur.com/nB5qo.png)](https://i.stack.imgur.com/nB5qo.png) And this is an image of the error I receive when I try those reds [![Image 2](https://i.stack.imgur.com/uX48X.png)](https://i.stack.imgur.com/uX48X.png)
Probably your local FTP service is not running. You can verify this by trying to connect to the local FTP server at the command prompt: ``` ftp localserver ``` and it will ask for your credentials. Also possible is that 'localserver' is not being resolved locally. You can check that with a command ``` nslookup localserver ``` And seeing if it gives you your servers' IP address. But this is not a WP Development question. Ask the googles/bings/ducks for help with enabling/starting your local FTP service.
338,336
<p>I have an html form in which I conditionally hide a field with javascript if an option is selected in the dropdown. The javascript condition works fine but when the page is reloaded the condition is lost even though the right option is still selected.</p> <p>Steps to recreate:</p> <ol> <li><p>I have a js code to store user input in session storage because my users might sometimes have to go to another page and come back to the form later.</p></li> <li><p>I have a js code to conditionally hide a field named <code>price_input_div</code> when the third option is selected in select field.</p></li> </ol> <p>The problem:</p> <p>When I click on the third option, the <code>price_input_div</code> field is hidden but when the page is reloaded, the field appears again even though the third option is still selected (the third option is still selected because I am saving the value in session storage).</p> <p>After the page is reloaded, when I select another option then select the third option again, the <code>price_input_div</code> field becomes hidden once again.</p> <p>The HTML form:</p> <pre><code>&lt;p class="form-row form-row-wide"&gt; &lt;label for="select_price_option"&gt;Price option&lt;span class="required"&gt; *&lt;/span&gt;&lt;/label&gt; &lt;select name="select_price_option" id="select_price_option" /&gt; &lt;option disabled selected value&gt; Please select one&lt;/option&gt; &lt;option&gt;Total fee&lt;/option&gt; &lt;option&gt;Starting fee&lt;/option&gt; &lt;option&gt;I need more information&lt;/option&gt; &lt;/select&gt; &lt;/p&gt; &lt;p class="form-row form-row-wide" id="price_input_div"&gt; &lt;label for="quote_price_input"&gt;Enter your price&lt;/label&gt; &lt;input type="text" name="quote_price_input" id="quote_price_input" class="input-text"/&gt; &lt;/p&gt; &lt;p class="form-row form-row-wide"&gt; &lt;label for="message_to_customer"&gt;Enter your message&lt;span class="required"&gt; *&lt;/span&gt;&lt;/label&gt; &lt;textarea name="message_to_customer" id="message_to_customer" minlength="30" class="input-text"&gt;&lt;/textarea&gt; &lt;/p&gt; </code></pre> <p>The Js code to save and get field value in session storage:</p> <pre><code>// Save custom checkout fields to session storage (function ($) { // Run on page load window.onload = function() { var quote_price_input = sessionStorage.getItem("quote_price_input"); var message_to_customer = sessionStorage.getItem("message_to_customer"); var select_price_option = sessionStorage.getItem("select_price_option"); if(quote_price_input !== null) { document.getElementById('quote_price_input').value = quote_price_input; } else document.getElementById('quote_price_input').value = ""; if(select_price_option !== null) { var sel = document.getElementById('select_price_option'); var opts = sel.options; for (var opt, j = 0; opt = opts[j]; j++) { console.log(opt.innerHTML); if (opt.innerHTML == select_price_option) { sel.selectedIndex = j; break; } } } if(message_to_customer !== null) { document.getElementById('message_to_customer').innerHTML = message_to_customer; } else document.getElementById('message_to_customer').innerHTML = ""; }; // Before refreshing the page, save the form data to sessionStorage window.onbeforeunload = function() { var quote_price_input = document.getElementById('quote_price_input'); var message_to_customer = document.getElementById('message_to_customer'); var select_price_option = document.getElementById('select_price_option'); if(quote_price_input !== null) { sessionStorage.setItem('quote_price_input', $('#quote_price_input').val()); } if(select_price_option !== null) { sessionStorage.setItem('select_price_option', $('#select_price_option').val()); } if(message_to_customer !== null) { sessionStorage.setItem('message_to_customer', $('#message_to_customer').val()); } }; })(jQuery); </code></pre> <p>The js code to conditionally hide <code>price_input_div</code> field:</p> <pre><code>(function ($) { $("#select_price_option").change(function() { if ($(this).val() == "I need more information") { $('#price_input_div').hide(); } else { $('#price_input_div').show(); } }); $("#select_price_option").trigger("change"); })(jQuery); </code></pre> <p>I want the <code>price_input_div</code> field to remain hidden even after page reload since <code>I need more information</code> is still selected.</p> <p>I tried the below code as well but no luck:</p> <pre><code>// Conditionally show price (function ($) { window.onload = function() { $("#select_price_option").change(function() { if ($(this).val() == "I need more information") { $('#price_input_div').hide(); } else { $('#price_input_div').show(); } }); $("#select_price_option").trigger("change"); }})(jQuery); </code></pre> <p>Any help will be greatly appreciated.</p>
[ { "answer_id": 338366, "author": "Bhupen", "author_id": 128529, "author_profile": "https://wordpress.stackexchange.com/users/128529", "pm_score": 1, "selected": false, "text": "<p>Try this code:</p>\n\n<pre><code>// Conditionally show price\n(function ($) {\n window.onload = function() {\n\n if ($(\"#select_price_option\").val() == \"I need more information\") {\n $('#price_input_div').hide();\n }\n\n$(\"#select_price_option\").change(function() {\n if ($(this).val() == \"I need more information\") {\n $('#price_input_div').hide();\n } else {\n $('#price_input_div').show();\n }\n });\n }})(jQuery);\n</code></pre>\n" }, { "answer_id": 363101, "author": "Tony Djukic", "author_id": 60844, "author_profile": "https://wordpress.stackexchange.com/users/60844", "pm_score": 0, "selected": false, "text": "<p>To expand on my comment, your select options don't have any values, but your condition in jQuery checks their value...</p>\n\n<pre><code>&lt;select name=\"select_price_option\" id=\"select_price_option\" /&gt;\n&lt;option disabled selected&gt; Please select one&lt;/option&gt;\n&lt;option value=\"Total fee\"&gt;Total fee&lt;/option&gt;\n&lt;option value=\"Starting fee\"&gt;Starting fee&lt;/option&gt;\n&lt;option value=\"I need more information\"&gt;I need more information&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>Then, when your jQuery runs the conditional check, like @Bhupen recommended, this condition will work:</p>\n\n<p><code>if ($(\"#select_price_option\").val() == \"I need more information\") {</code></p>\n\n<p>As will the one lower down:</p>\n\n<p><code>if ($(this).val() == \"I need more information\") {</code></p>\n" } ]
2019/05/21
[ "https://wordpress.stackexchange.com/questions/338336", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/163105/" ]
I have an html form in which I conditionally hide a field with javascript if an option is selected in the dropdown. The javascript condition works fine but when the page is reloaded the condition is lost even though the right option is still selected. Steps to recreate: 1. I have a js code to store user input in session storage because my users might sometimes have to go to another page and come back to the form later. 2. I have a js code to conditionally hide a field named `price_input_div` when the third option is selected in select field. The problem: When I click on the third option, the `price_input_div` field is hidden but when the page is reloaded, the field appears again even though the third option is still selected (the third option is still selected because I am saving the value in session storage). After the page is reloaded, when I select another option then select the third option again, the `price_input_div` field becomes hidden once again. The HTML form: ``` <p class="form-row form-row-wide"> <label for="select_price_option">Price option<span class="required"> *</span></label> <select name="select_price_option" id="select_price_option" /> <option disabled selected value> Please select one</option> <option>Total fee</option> <option>Starting fee</option> <option>I need more information</option> </select> </p> <p class="form-row form-row-wide" id="price_input_div"> <label for="quote_price_input">Enter your price</label> <input type="text" name="quote_price_input" id="quote_price_input" class="input-text"/> </p> <p class="form-row form-row-wide"> <label for="message_to_customer">Enter your message<span class="required"> *</span></label> <textarea name="message_to_customer" id="message_to_customer" minlength="30" class="input-text"></textarea> </p> ``` The Js code to save and get field value in session storage: ``` // Save custom checkout fields to session storage (function ($) { // Run on page load window.onload = function() { var quote_price_input = sessionStorage.getItem("quote_price_input"); var message_to_customer = sessionStorage.getItem("message_to_customer"); var select_price_option = sessionStorage.getItem("select_price_option"); if(quote_price_input !== null) { document.getElementById('quote_price_input').value = quote_price_input; } else document.getElementById('quote_price_input').value = ""; if(select_price_option !== null) { var sel = document.getElementById('select_price_option'); var opts = sel.options; for (var opt, j = 0; opt = opts[j]; j++) { console.log(opt.innerHTML); if (opt.innerHTML == select_price_option) { sel.selectedIndex = j; break; } } } if(message_to_customer !== null) { document.getElementById('message_to_customer').innerHTML = message_to_customer; } else document.getElementById('message_to_customer').innerHTML = ""; }; // Before refreshing the page, save the form data to sessionStorage window.onbeforeunload = function() { var quote_price_input = document.getElementById('quote_price_input'); var message_to_customer = document.getElementById('message_to_customer'); var select_price_option = document.getElementById('select_price_option'); if(quote_price_input !== null) { sessionStorage.setItem('quote_price_input', $('#quote_price_input').val()); } if(select_price_option !== null) { sessionStorage.setItem('select_price_option', $('#select_price_option').val()); } if(message_to_customer !== null) { sessionStorage.setItem('message_to_customer', $('#message_to_customer').val()); } }; })(jQuery); ``` The js code to conditionally hide `price_input_div` field: ``` (function ($) { $("#select_price_option").change(function() { if ($(this).val() == "I need more information") { $('#price_input_div').hide(); } else { $('#price_input_div').show(); } }); $("#select_price_option").trigger("change"); })(jQuery); ``` I want the `price_input_div` field to remain hidden even after page reload since `I need more information` is still selected. I tried the below code as well but no luck: ``` // Conditionally show price (function ($) { window.onload = function() { $("#select_price_option").change(function() { if ($(this).val() == "I need more information") { $('#price_input_div').hide(); } else { $('#price_input_div').show(); } }); $("#select_price_option").trigger("change"); }})(jQuery); ``` Any help will be greatly appreciated.
Try this code: ``` // Conditionally show price (function ($) { window.onload = function() { if ($("#select_price_option").val() == "I need more information") { $('#price_input_div').hide(); } $("#select_price_option").change(function() { if ($(this).val() == "I need more information") { $('#price_input_div').hide(); } else { $('#price_input_div').show(); } }); }})(jQuery); ```
338,369
<p>I have defined <code>quote</code> post format for the theme:</p> <pre><code>// Add post-formats for theme add_theme_support( 'post-formats', array( 'quote', ) ); </code></pre> <p>After it, I want to display quote from the content. For that, I want to use <code>preg_match_all</code> function to search for <code>&lt;blockquote&gt;Hello World.&lt;/blockquote&gt;</code></p> <pre><code>if( $format == 'quote' ) { $content = apply_filters( 'the_content', get_the_content() ); preg_match( '/&lt;blockquote.*?&gt;/', $content, $matches ); } </code></pre> <p>But it is not working. I want to find blockquote tag and display content inside this tag.</p>
[ { "answer_id": 338366, "author": "Bhupen", "author_id": 128529, "author_profile": "https://wordpress.stackexchange.com/users/128529", "pm_score": 1, "selected": false, "text": "<p>Try this code:</p>\n\n<pre><code>// Conditionally show price\n(function ($) {\n window.onload = function() {\n\n if ($(\"#select_price_option\").val() == \"I need more information\") {\n $('#price_input_div').hide();\n }\n\n$(\"#select_price_option\").change(function() {\n if ($(this).val() == \"I need more information\") {\n $('#price_input_div').hide();\n } else {\n $('#price_input_div').show();\n }\n });\n }})(jQuery);\n</code></pre>\n" }, { "answer_id": 363101, "author": "Tony Djukic", "author_id": 60844, "author_profile": "https://wordpress.stackexchange.com/users/60844", "pm_score": 0, "selected": false, "text": "<p>To expand on my comment, your select options don't have any values, but your condition in jQuery checks their value...</p>\n\n<pre><code>&lt;select name=\"select_price_option\" id=\"select_price_option\" /&gt;\n&lt;option disabled selected&gt; Please select one&lt;/option&gt;\n&lt;option value=\"Total fee\"&gt;Total fee&lt;/option&gt;\n&lt;option value=\"Starting fee\"&gt;Starting fee&lt;/option&gt;\n&lt;option value=\"I need more information\"&gt;I need more information&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>Then, when your jQuery runs the conditional check, like @Bhupen recommended, this condition will work:</p>\n\n<p><code>if ($(\"#select_price_option\").val() == \"I need more information\") {</code></p>\n\n<p>As will the one lower down:</p>\n\n<p><code>if ($(this).val() == \"I need more information\") {</code></p>\n" } ]
2019/05/21
[ "https://wordpress.stackexchange.com/questions/338369", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138428/" ]
I have defined `quote` post format for the theme: ``` // Add post-formats for theme add_theme_support( 'post-formats', array( 'quote', ) ); ``` After it, I want to display quote from the content. For that, I want to use `preg_match_all` function to search for `<blockquote>Hello World.</blockquote>` ``` if( $format == 'quote' ) { $content = apply_filters( 'the_content', get_the_content() ); preg_match( '/<blockquote.*?>/', $content, $matches ); } ``` But it is not working. I want to find blockquote tag and display content inside this tag.
Try this code: ``` // Conditionally show price (function ($) { window.onload = function() { if ($("#select_price_option").val() == "I need more information") { $('#price_input_div').hide(); } $("#select_price_option").change(function() { if ($(this).val() == "I need more information") { $('#price_input_div').hide(); } else { $('#price_input_div').show(); } }); }})(jQuery); ```
338,383
<p>I'd like to disable access to posts in the back-end/Admin from a user that doesn't have the privilege to view those posts. This will function similar to the Author role however this "privilege" is controlled by an <a href="https://advancedcustomfields.com" rel="nofollow noreferrer">ACF</a> User relationship field and not by a WP Core role or privilege.</p> <p>One level of complexity deeper, the User relationship field is actually pointing to a parent/grouping custom post type that is then tied to the children post elements I'm attempting to filter. So rather than show just the posts that user has authored, it's also showing posts that others have authored but that they have been granted permission to manage. Let me explain this below... </p> <p>Custom Post Type: <strong>Shoes [<code>shoe</code>]</strong><br/> Custom Post Type: <strong>Brands [<code>brand</code>]</strong></p> <ul> <li>Let's say you have a "shoe" called "Air Jordans" and you have a "brand" called "Nike". </li> <li>So you create an <a href="https://www.advancedcustomfields.com/resources/bidirectional-relationships/" rel="nofollow noreferrer">ACF bidirectional relationship</a> between "Air Jordan" and "Nike". </li> <li>Now let's say you create a user on your site that you want to be able to edit all "Nike" shoes. </li> <li>So you create an ACF User relationship field type in the "brand" post type, and you can assign multiple users to admin that brand. </li> <li>So, when that user logs into the back-end and views all shoes, I want just Nikes shoes to show up and they will have the ability to edit all Nike shoes. </li> </ul> <p>I've built out the logic to handle this on the front-end and it works perfect, and now I'd like to duplicate this on the back-end for filtering there as well. Here's what I built out on the front-end for reference:</p> <pre><code>$current_user = wp_get_current_user(); /* Get All Brands the Current User can Administer */ $brands_admin_args = array( 'post_type' =&gt; 'brand', 'meta_query' =&gt; array( array( 'key' =&gt; 'admins', // This is my ACF User field that tracks brand admins. 'value' =&gt; '"' . $current_user-&gt;ID . '"', 'compare' =&gt; 'LIKE' ), ), ); $brands_admin = get_posts($brands_admin_args); /* Get All Shoes The User Can Administer Based On Each Brand They Can Administer*/ $approved_shoes_args = array( 'post_type' =&gt; 'shoe', 'meta_query' =&gt; array( 'relation' =&gt; 'OR' ), ); foreach ($brands_admin as $ba) { array_push($approved_shoes_args['meta_query'], array( 'key' =&gt; 'shoe_brands', // This is my ACF Relationship field between Shoes and Brands 'value' =&gt; '"' . $ba-&gt;ID . '"', 'compare' =&gt; 'LIKE' )); } $approved_shoes = new WP_Query($approved_shoes_args); </code></pre>
[ { "answer_id": 338387, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 1, "selected": false, "text": "<p>Your best bet is to use the <code>pre_get_posts</code> hook to adjust the query on the admin side.</p>\n\n<p>Your logic is pretty complicated so I won't try to give you a working example but the snippet below will get you started. Basically, you want to be sure your in the admin and managing the main query.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">Codex link</a></p>\n\n<pre><code>add_action( 'pre_get_posts', 'customize_admin_query' );\n\nfunction customize_admin_query( $wp_query ) {\n if ( $wp_query-&gt;is_admin() &amp;&amp; $wp_query-&gt;is_main_query() ) {\n // do your customizations in here.\n }\n}\n</code></pre>\n" }, { "answer_id": 338439, "author": "Mike B.", "author_id": 2080, "author_profile": "https://wordpress.stackexchange.com/users/2080", "pm_score": 0, "selected": false, "text": "<p>Taking @Welcher's suggestion of using <code>pre_get_posts</code>, I took my existing code and compiled the following to filter edit.php page for my custom post based on an ACF field granting the current user's access rights:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'customize_products_for_admins' );\nfunction customize_products_for_admins( $wp_query ) {\n\n if ( is_admin() &amp;&amp; $wp_query-&gt;is_main_query() &amp;&amp; current_user_can('editor') ) { // I know I need more conditional statements here\n\n $current_user = wp_get_current_user();\n\n /* Get All Brands the Current User can Administer */\n $brands_admin_args = array(\n 'post_type' =&gt; \"brand\",\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; \"admins\",\n 'value' =&gt; '\"' . $current_user-&gt;ID . '\"',\n 'compare' =&gt; \"LIKE\"\n ),\n ),\n );\n $brands_admin = get_posts($brands_admin_args);\n\n /* Get All Shoes The User Can Administer Based On Each Brand They Can Administer */\n $approved_shoes_args = array(\n 'meta_query' =&gt; array(\n 'relation' =&gt; \"OR\"\n ),\n );\n\n foreach ($brands_admin as $ba) {\n array_push($approved_shoes_args['meta_query'], array(\n 'key' =&gt; \"shoe_brands\", // This is my ACF Relationship field between Shoes and Brands\n 'value' =&gt; '\"' . $ba-&gt;ID . '\"',\n 'compare' =&gt; \"LIKE\"\n ));\n }\n $wp_query-&gt;set('meta_query', $approved_shoes_args);\n }\n}\n</code></pre>\n" } ]
2019/05/21
[ "https://wordpress.stackexchange.com/questions/338383", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2080/" ]
I'd like to disable access to posts in the back-end/Admin from a user that doesn't have the privilege to view those posts. This will function similar to the Author role however this "privilege" is controlled by an [ACF](https://advancedcustomfields.com) User relationship field and not by a WP Core role or privilege. One level of complexity deeper, the User relationship field is actually pointing to a parent/grouping custom post type that is then tied to the children post elements I'm attempting to filter. So rather than show just the posts that user has authored, it's also showing posts that others have authored but that they have been granted permission to manage. Let me explain this below... Custom Post Type: **Shoes [`shoe`]** Custom Post Type: **Brands [`brand`]** * Let's say you have a "shoe" called "Air Jordans" and you have a "brand" called "Nike". * So you create an [ACF bidirectional relationship](https://www.advancedcustomfields.com/resources/bidirectional-relationships/) between "Air Jordan" and "Nike". * Now let's say you create a user on your site that you want to be able to edit all "Nike" shoes. * So you create an ACF User relationship field type in the "brand" post type, and you can assign multiple users to admin that brand. * So, when that user logs into the back-end and views all shoes, I want just Nikes shoes to show up and they will have the ability to edit all Nike shoes. I've built out the logic to handle this on the front-end and it works perfect, and now I'd like to duplicate this on the back-end for filtering there as well. Here's what I built out on the front-end for reference: ``` $current_user = wp_get_current_user(); /* Get All Brands the Current User can Administer */ $brands_admin_args = array( 'post_type' => 'brand', 'meta_query' => array( array( 'key' => 'admins', // This is my ACF User field that tracks brand admins. 'value' => '"' . $current_user->ID . '"', 'compare' => 'LIKE' ), ), ); $brands_admin = get_posts($brands_admin_args); /* Get All Shoes The User Can Administer Based On Each Brand They Can Administer*/ $approved_shoes_args = array( 'post_type' => 'shoe', 'meta_query' => array( 'relation' => 'OR' ), ); foreach ($brands_admin as $ba) { array_push($approved_shoes_args['meta_query'], array( 'key' => 'shoe_brands', // This is my ACF Relationship field between Shoes and Brands 'value' => '"' . $ba->ID . '"', 'compare' => 'LIKE' )); } $approved_shoes = new WP_Query($approved_shoes_args); ```
Your best bet is to use the `pre_get_posts` hook to adjust the query on the admin side. Your logic is pretty complicated so I won't try to give you a working example but the snippet below will get you started. Basically, you want to be sure your in the admin and managing the main query. [Codex link](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) ``` add_action( 'pre_get_posts', 'customize_admin_query' ); function customize_admin_query( $wp_query ) { if ( $wp_query->is_admin() && $wp_query->is_main_query() ) { // do your customizations in here. } } ```
338,390
<p>What happen when a post (product) didnt have a guid,because it has the same image with another product ? </p> <p>For example:</p> <p>Query1: </p> <pre><code>select guid from wp_posts where post_type='attachment' and post_parent=num </code></pre> <p>Returns nothing.</p> <p>Query2: </p> <pre><code>select guid from wp_posts where ID=num </code></pre> <p>Returns the url of product.</p> <p>In this case how should i find the image url of that product?</p>
[ { "answer_id": 338397, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": false, "text": "<p>Firstly, the GUID is not the URL. It is a \"globally unique identifier\". WordPress uses the URL for this purpose, but accessing it is not a reliable way to get the URL for anything (this was a bad idea, but is kept this way for backwards compatibility).</p>\n\n<p>It's not possible to query the image URL from the database directly. The full URL is not stored there. But if you have the ID for a product and want to get the URL for its image you can do this:</p>\n\n<pre><code>$product = wc_get_product( $product_id );\n$image_id = $product-&gt;get_image_id();\n$image_url = wp_get_attachment_image_url( $image_id, 'full' );\n</code></pre>\n" }, { "answer_id": 350677, "author": "Akshay Prabhakar", "author_id": 129156, "author_profile": "https://wordpress.stackexchange.com/users/129156", "pm_score": 1, "selected": false, "text": "<p>For your reference just run this query in database :</p>\n\n<pre><code> SELECT * FROM `wp_postmeta` WHERE meta_key IN ('_wp_attached_file', '_wp_attachment_backup_sizes', '_wp_attachment_metadata', '_thumbnail_id')\n</code></pre>\n\n<p>And if you run the above query with \"_wp_attached_file\" only you will get the path from upload directory. </p>\n\n<p>Hope it helps..</p>\n" }, { "answer_id": 355444, "author": "Amit Joshi", "author_id": 174350, "author_profile": "https://wordpress.stackexchange.com/users/174350", "pm_score": 2, "selected": false, "text": "<p>i have seen some ware a query to fetch products image from database.<br>\nmay be it will help you.<br>\njust set required parameters as per your requirement. </p>\n\n<pre><code>SELECT p.ID,am.meta_value FROM wp_posts p LEFT JOIN wp_postmeta pm ON pm.post_id = p.ID AND pm.meta_key = '_thumbnail_id' LEFT JOIN wp_postmeta am ON am.post_id = pm.meta_value AND am.meta_key = '_wp_attached_file' WHERE p.post_type = 'product' AND p.post_status = 'publish';\n</code></pre>\n" } ]
2019/05/21
[ "https://wordpress.stackexchange.com/questions/338390", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168479/" ]
What happen when a post (product) didnt have a guid,because it has the same image with another product ? For example: Query1: ``` select guid from wp_posts where post_type='attachment' and post_parent=num ``` Returns nothing. Query2: ``` select guid from wp_posts where ID=num ``` Returns the url of product. In this case how should i find the image url of that product?
Firstly, the GUID is not the URL. It is a "globally unique identifier". WordPress uses the URL for this purpose, but accessing it is not a reliable way to get the URL for anything (this was a bad idea, but is kept this way for backwards compatibility). It's not possible to query the image URL from the database directly. The full URL is not stored there. But if you have the ID for a product and want to get the URL for its image you can do this: ``` $product = wc_get_product( $product_id ); $image_id = $product->get_image_id(); $image_url = wp_get_attachment_image_url( $image_id, 'full' ); ```
338,394
<p>I want to remove the editor and set up only the excerpt to a custom product type (WooCommerce) in my theme, is this possible?</p> <p>This is how i add my custom product type to the WooCommerce product type selector</p> <pre><code>&lt;?php defined('ABSPATH') || exit; class Custom_Product_Type(){ public function __construct() { add_filter('product_type_selector', array($this, 'product_type_selector')); } function product_type_selector($types) { $types['custom_product_type'] = 'Custom product type'; return $types; } } new Custom_Product_Type(); </code></pre>
[ { "answer_id": 338396, "author": "Deepak Singh", "author_id": 138263, "author_profile": "https://wordpress.stackexchange.com/users/138263", "pm_score": 1, "selected": false, "text": "<p>Yes, You can disable the default editor by removing <strong>'editor'</strong> from the supports attribute array for register_post_type( 'product', $args )</p>\n\n<pre><code>'supports' =&gt; array( 'title', 'editor', 'thumbnail', 'comments', 'custom-fields' ),\n</code></pre>\n\n<p>Change this to somthing like this</p>\n\n<pre><code>'supports' =&gt; array( 'title', 'thumbnail', 'comments', 'custom-fields' ),\n</code></pre>\n\n<p>You can read wordpress function reference for <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">register_post_type</a> to learn more about custom post type arguments. </p>\n\n<p><strong>Update:</strong> </p>\n\n<p><strong>Method 1:</strong></p>\n\n<p>To change register_post_type args via \"<strong>register_post_type_args</strong>\" filter hook.</p>\n\n<pre><code>add_filter( 'register_post_type_args', 'product_support_args', 10, 2 );\nfunction product_support_args( $args, $post_type ){\n\n $post_ids_array = array(2119, 2050); // Add Your Allowed Post IDs Here\n\n if ( 'product' === $post_type &amp;&amp; is_admin()){\n\n $post_id = $_GET['post']; // Get Post ID from URL\n\n // Check if the post ID is whitelisted\n if(in_array($post_id, $post_ids_array)){\n $args['supports'] = array( 'title', 'thumbnail', 'comments', 'custom-fields' ); // Remove Editor from supports args array\n } \n\n }\n\n return $args;\n\n}\n</code></pre>\n\n<p><strong>Method 2:</strong></p>\n\n<p>By using <strong>remove_post_type_support()</strong> function. You can pass allowed post ids array in the same way we did above if required.</p>\n\n<pre><code>add_action( 'current_screen', 'remove_editor_support' );\nfunction remove_editor_support() {\n\n $get_screen = get_current_screen();\n $current_screen = $get_screen-&gt;post_type;\n $post_type = 'product'; // change post type here\n\n if ($current_screen == $post_type ) { \n remove_post_type_support( $current_screen, 'editor' ); // remove editor from support argument\n } \n\n}\n</code></pre>\n" }, { "answer_id": 338419, "author": "Rodrigo Butzke", "author_id": 130208, "author_profile": "https://wordpress.stackexchange.com/users/130208", "pm_score": 1, "selected": true, "text": "<p>I've figured how to hide the editor only when the product type is selected because if i remove the support:</p>\n\n<p>1) The product type is the hidden and then change the product type to another the editor doesn't appear back</p>\n\n<p>2) The product type is not the hidden and then change the product type to hidden the editor dont dissappear</p>\n\n<pre><code>function admin_footer() {\n if ( 'product' !== get_post_type() ) :\n return;\n endif;\n ?&gt;&lt;script type='text/javascript'&gt;\n jQuery( document ).ready( function() {\n $(\"#postdivrich\").addClass('hide_if_custom_product_type');\n $(\"#product-type\").trigger('change');\n });\n &lt;/script&gt;&lt;?php\n}\nadd_action( 'admin_footer', array($this, 'admin_footer'));\n</code></pre>\n\n<p>This way, every time it selects or deselects the product type, it will hide or show using WooCommerce methods</p>\n" } ]
2019/05/21
[ "https://wordpress.stackexchange.com/questions/338394", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130208/" ]
I want to remove the editor and set up only the excerpt to a custom product type (WooCommerce) in my theme, is this possible? This is how i add my custom product type to the WooCommerce product type selector ``` <?php defined('ABSPATH') || exit; class Custom_Product_Type(){ public function __construct() { add_filter('product_type_selector', array($this, 'product_type_selector')); } function product_type_selector($types) { $types['custom_product_type'] = 'Custom product type'; return $types; } } new Custom_Product_Type(); ```
I've figured how to hide the editor only when the product type is selected because if i remove the support: 1) The product type is the hidden and then change the product type to another the editor doesn't appear back 2) The product type is not the hidden and then change the product type to hidden the editor dont dissappear ``` function admin_footer() { if ( 'product' !== get_post_type() ) : return; endif; ?><script type='text/javascript'> jQuery( document ).ready( function() { $("#postdivrich").addClass('hide_if_custom_product_type'); $("#product-type").trigger('change'); }); </script><?php } add_action( 'admin_footer', array($this, 'admin_footer')); ``` This way, every time it selects or deselects the product type, it will hide or show using WooCommerce methods
338,398
<p>I made some research and found a way how to create custom pages using content (post) types. However, I do not want to create a new post type, I just want to create a page having a certain URL (<code>/form</code>) with a form on it. I was not able to find how to do it without custom post types. Can someone show me the correct direction? Thanks a lot.</p>
[ { "answer_id": 338403, "author": "bjornredemption", "author_id": 64380, "author_profile": "https://wordpress.stackexchange.com/users/64380", "pm_score": 0, "selected": false, "text": "<p>Install a form plugin. Contact form 7 is a good one :\n <a href=\"https://en-au.wordpress.org/plugins/contact-form-7/\" rel=\"nofollow noreferrer\">https://en-au.wordpress.org/plugins/contact-form-7/</a></p>\n\n<p>Create a form using the plugin.</p>\n\n<p>Create a normal WP page and add your form to it by pasting the contact-form-7 shortcode into the page.</p>\n" }, { "answer_id": 338406, "author": "Deepak Singh", "author_id": 138263, "author_profile": "https://wordpress.stackexchange.com/users/138263", "pm_score": 3, "selected": true, "text": "<p>You can use <strong>wp_insert_post()</strong> function with '<strong>after_theme_setup</strong>' action hook to programatically create pages. Here is a short example,</p>\n\n<pre><code>add_action( 'after_setup_theme', 'create_form_page' );\nfunction create_form_page(){\n\n $title = 'Form';\n $slug = 'form';\n $page_content = ''; // your page content here\n $post_type = 'page';\n\n $page_args = array(\n 'post_type' =&gt; $post_type,\n 'post_title' =&gt; $title,\n 'post_content' =&gt; $page_content,\n 'post_status' =&gt; 'publish',\n 'post_author' =&gt; 1,\n 'post_slug' =&gt; $slug\n );\n\n if(post_exists($title) === 0){\n $page_id = wp_insert_post($page_args);\n }\n\n} \n</code></pre>\n" } ]
2019/05/21
[ "https://wordpress.stackexchange.com/questions/338398", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168483/" ]
I made some research and found a way how to create custom pages using content (post) types. However, I do not want to create a new post type, I just want to create a page having a certain URL (`/form`) with a form on it. I was not able to find how to do it without custom post types. Can someone show me the correct direction? Thanks a lot.
You can use **wp\_insert\_post()** function with '**after\_theme\_setup**' action hook to programatically create pages. Here is a short example, ``` add_action( 'after_setup_theme', 'create_form_page' ); function create_form_page(){ $title = 'Form'; $slug = 'form'; $page_content = ''; // your page content here $post_type = 'page'; $page_args = array( 'post_type' => $post_type, 'post_title' => $title, 'post_content' => $page_content, 'post_status' => 'publish', 'post_author' => 1, 'post_slug' => $slug ); if(post_exists($title) === 0){ $page_id = wp_insert_post($page_args); } } ```
338,427
<p>I want to make a dynamic select where the user will put state, there will appear the cities of this state, then will put city and will appear the universities of this city for him to choose, how can I do this? I've done this in php, but the code I used in php does not work inside the function to add in the field of woocommerce </p> <pre><code> function novo_campo_woocommerce( $checkout ) { echo '&lt;select id="estados" class="form-control" name="estados"&gt; &lt;option selected disabled&gt;Escolha seu estado&lt;/option&gt;'; $conexao = new PDO('mysql:host=localhost;dbname=teste', 'user', 'password'); $sql = ('SELECT * FROM tb_estado ORDER BY nome ASC'); $sql = $conexao-&gt;prepare($sql); $sql-&gt;execute(); $lista = $sql-&gt;fetchAll(); for ($i=0; $i &lt; count($lista); $i++) { $uf = $lista[$i]['uf']; $nome = $lista[$i]['nome']; echo "&lt;option value='$uf'&gt;$nome&lt;/option&gt;"; } echo '&lt;/select&gt;'; echo '&lt;select class="form-control" name="cidades" id="cidades" required&gt; &lt;option value="" selected disabled&gt;Selecione o estado primeiro&lt;/option&gt; &lt;/select&gt;'; echo '&lt;select class="form-control" name="universidades" id="universidades" required&gt; &lt;option value="" selected disabled&gt;Selecione a cidade primeiro&lt;/option&gt; &lt;/select&gt;'; ?&gt; &lt;script&gt; $(function(){ $("#estados").change(function(){ var uf = $(this).val(); $.ajax({ type: "POST", url: "func/exibe_cidade.php?uf="+uf, dataType:"text", success: function(res){ $("#cidades").children(".cidades").remove(); $("#universidades").children(".universidades").remove(); $("#cidades").append(res); console.log(res); } }); }); $("#cidades").change(function(){ var id = $(this).val(); $.ajax({ type: "POST", url: "func/exibe_universidade.php?id="+id, dataType:"text", success: function(res){ $("#universidades").children(".universidades").remove(); $("#palestras").children(".palestras").remove(); } }); }); }); &lt;/script&gt; &lt;?php } </code></pre> <p>exibe_cidade.php</p> <pre><code>&lt;?php require_once "conn.php"; $uf = $_GET['uf']; $sql = 'SELECT * FROM tb_cidade WHERE uf = ? ORDER BY nome'; $stm = $conexao-&gt;prepare($sql); $stm-&gt;bindValue(1, $uf); $stm-&gt;execute(); $lista = $stm-&gt;fetchAll(); for($i=0;$i&lt;count($lista);$i++){ $id = $lista[$i]['id']; $nome = $lista[$i]['nome']; echo '&lt;option value="'.$id.'" class="cidades"&gt;'.$nome.'&lt;/option&gt;'; } ?&gt; </code></pre>
[ { "answer_id": 338404, "author": "Ted Stresen-Reuter", "author_id": 112766, "author_profile": "https://wordpress.stackexchange.com/users/112766", "pm_score": 0, "selected": false, "text": "<p>The native WordPress commenting system, without checks of any kind, is very likely a bad idea. However, the system does include the ability to require users to sign up for an account before being able to comment. That combined with a registered version of the Akismet plugin and WordFence (or some other security plugin) will keep public spam to a minimum.</p>\n" }, { "answer_id": 338405, "author": "MikeNGarrett", "author_id": 1670, "author_profile": "https://wordpress.stackexchange.com/users/1670", "pm_score": 1, "selected": false, "text": "<p>WordPress default settings are to allow anyone to comment as long as they leave a name and email. Emails aren't verified, so you could use someone else's email and gravatar and the comment would be published. </p>\n\n<p>Best practice is to verify the email address of the user making the comment. In WordPress core functionality, this requires users register for an account in order to comment. </p>\n" }, { "answer_id": 338408, "author": "Deepak Singh", "author_id": 138263, "author_profile": "https://wordpress.stackexchange.com/users/138263", "pm_score": 1, "selected": false, "text": "<p>Absolutely Not, that's why either allow only registered users to leave comments or you can build your custom function using <strong>wp_set_comment_status()</strong> and <strong>wp_mail()</strong>, to show comments only after verification via email. </p>\n\n<p><strong>Update:</strong> </p>\n\n<p>In case, I have disabled both the options in \"<strong>Before a comment appears</strong>\" settings, which in most of the cases may be required.</p>\n\n<p>In this case, when an unauthenticated or non-logged in commentator leave a comment using Name and Email fields, the commentator can use any email, as there is no additional verification available for this until we do it manually or use any third-party solution. </p>\n\n<p>The commentator may use Name and Email of any popular blogger/person, \nand if the same email is registered with gravatar then it will fetch the gravatar profile image, this may mislead to other users, and anyone can steal the gravatar identity of anyone.</p>\n" } ]
2019/05/21
[ "https://wordpress.stackexchange.com/questions/338427", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168493/" ]
I want to make a dynamic select where the user will put state, there will appear the cities of this state, then will put city and will appear the universities of this city for him to choose, how can I do this? I've done this in php, but the code I used in php does not work inside the function to add in the field of woocommerce ``` function novo_campo_woocommerce( $checkout ) { echo '<select id="estados" class="form-control" name="estados"> <option selected disabled>Escolha seu estado</option>'; $conexao = new PDO('mysql:host=localhost;dbname=teste', 'user', 'password'); $sql = ('SELECT * FROM tb_estado ORDER BY nome ASC'); $sql = $conexao->prepare($sql); $sql->execute(); $lista = $sql->fetchAll(); for ($i=0; $i < count($lista); $i++) { $uf = $lista[$i]['uf']; $nome = $lista[$i]['nome']; echo "<option value='$uf'>$nome</option>"; } echo '</select>'; echo '<select class="form-control" name="cidades" id="cidades" required> <option value="" selected disabled>Selecione o estado primeiro</option> </select>'; echo '<select class="form-control" name="universidades" id="universidades" required> <option value="" selected disabled>Selecione a cidade primeiro</option> </select>'; ?> <script> $(function(){ $("#estados").change(function(){ var uf = $(this).val(); $.ajax({ type: "POST", url: "func/exibe_cidade.php?uf="+uf, dataType:"text", success: function(res){ $("#cidades").children(".cidades").remove(); $("#universidades").children(".universidades").remove(); $("#cidades").append(res); console.log(res); } }); }); $("#cidades").change(function(){ var id = $(this).val(); $.ajax({ type: "POST", url: "func/exibe_universidade.php?id="+id, dataType:"text", success: function(res){ $("#universidades").children(".universidades").remove(); $("#palestras").children(".palestras").remove(); } }); }); }); </script> <?php } ``` exibe\_cidade.php ``` <?php require_once "conn.php"; $uf = $_GET['uf']; $sql = 'SELECT * FROM tb_cidade WHERE uf = ? ORDER BY nome'; $stm = $conexao->prepare($sql); $stm->bindValue(1, $uf); $stm->execute(); $lista = $stm->fetchAll(); for($i=0;$i<count($lista);$i++){ $id = $lista[$i]['id']; $nome = $lista[$i]['nome']; echo '<option value="'.$id.'" class="cidades">'.$nome.'</option>'; } ?> ```
WordPress default settings are to allow anyone to comment as long as they leave a name and email. Emails aren't verified, so you could use someone else's email and gravatar and the comment would be published. Best practice is to verify the email address of the user making the comment. In WordPress core functionality, this requires users register for an account in order to comment.
338,429
<p>I wanna remove the functionality of when you click on a order row in Orders in Admin, you will be sent to the edit page for that order. </p> <p>I know it's added with jQuery in a js-file in the WooCommerce plugin. I have located the actual code:</p> <pre><code>/** * Click a row. */ WCOrdersTable.prototype.onRowClick = function( e ) { if ( $( e.target ).filter( 'a, a *, .no-link, .no-link *, button, button *' ).length ) { return true; } if ( window.getSelection &amp;&amp; window.getSelection().toString().length ) { return true; } var $row = $( this ).closest( 'tr' ), href = $row.find( 'a.order-view' ).attr( 'href' ); if ( href &amp;&amp; href.length ) { e.preventDefault(); if ( e.metaKey || e.ctrlKey ) { window.open( href, '_blank' ); } else { window.location = href; } } }; </code></pre> <p>But I don't wanna change any code in the plugin. And there aren't js hooks or any php hook that can control that part of code.</p> <p>So I guess the option is to add the <code>no-link</code> class to the columns in the list? How do I do that? I can't find anything about how to do that.</p>
[ { "answer_id": 338514, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>Based on <a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/admin/list-tables/class-wc-admin-list-table-orders.php\" rel=\"nofollow noreferrer\"><code>class-wc-admin-list-table-orders.php</code></a> (<a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/admin/list-tables/class-wc-admin-list-table-orders.php#L173\" rel=\"nofollow noreferrer\">order column on line 173</a>) there doesn't seem to be a filter to change the markup. </p>\n\n<p>To circumvent this, perhaps you could add a js/jQuery script, to <code>admin_footer</code> or with <code>admin_enqueue_scripts</code>, which either adds the necessary class(es), removes href or changes it to #, or with some <a href=\"https://stackoverflow.com/questions/17352104/multiple-js-event-handlers-on-single-element\">event delegation wizardry</a> have your own <code>click</code> event fire first and prevent the <code>WCOrdersTable window.location</code> from happening.</p>\n" }, { "answer_id": 349374, "author": "Bhautik", "author_id": 127648, "author_profile": "https://wordpress.stackexchange.com/users/127648", "pm_score": 0, "selected": false, "text": "<p>You can check here how to add no-link class into woocommerce order list row</p>\n\n<p>orginal issue asked here <a href=\"https://github.com/woocommerce/woocommerce/issues/18704\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/issues/18704</a></p>\n\n<p>orginal issue asked answer here <a href=\"https://github.com/woocommerce/woocommerce/pull/18708\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/pull/18708</a></p>\n" } ]
2019/05/21
[ "https://wordpress.stackexchange.com/questions/338429", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3216/" ]
I wanna remove the functionality of when you click on a order row in Orders in Admin, you will be sent to the edit page for that order. I know it's added with jQuery in a js-file in the WooCommerce plugin. I have located the actual code: ``` /** * Click a row. */ WCOrdersTable.prototype.onRowClick = function( e ) { if ( $( e.target ).filter( 'a, a *, .no-link, .no-link *, button, button *' ).length ) { return true; } if ( window.getSelection && window.getSelection().toString().length ) { return true; } var $row = $( this ).closest( 'tr' ), href = $row.find( 'a.order-view' ).attr( 'href' ); if ( href && href.length ) { e.preventDefault(); if ( e.metaKey || e.ctrlKey ) { window.open( href, '_blank' ); } else { window.location = href; } } }; ``` But I don't wanna change any code in the plugin. And there aren't js hooks or any php hook that can control that part of code. So I guess the option is to add the `no-link` class to the columns in the list? How do I do that? I can't find anything about how to do that.
Based on [`class-wc-admin-list-table-orders.php`](https://github.com/woocommerce/woocommerce/blob/master/includes/admin/list-tables/class-wc-admin-list-table-orders.php) ([order column on line 173](https://github.com/woocommerce/woocommerce/blob/master/includes/admin/list-tables/class-wc-admin-list-table-orders.php#L173)) there doesn't seem to be a filter to change the markup. To circumvent this, perhaps you could add a js/jQuery script, to `admin_footer` or with `admin_enqueue_scripts`, which either adds the necessary class(es), removes href or changes it to #, or with some [event delegation wizardry](https://stackoverflow.com/questions/17352104/multiple-js-event-handlers-on-single-element) have your own `click` event fire first and prevent the `WCOrdersTable window.location` from happening.
338,492
<p>I created a custom login page and everything is OK but there is an issue. I want to redirect users to different pages based on their roles after login. My code is below but I do not know why it is not working:</p> <pre><code> if (!$has_error) { $info = array(); $info['user_login'] = $user_login; $info['user_password'] = $password; $info['emember'] = $remember; $user_signon = wp_signon($info,false); if(is_wp_error($user_signon)){ $has_error = true; $message[] = "an error"; }else{ $currentuser = wp_get_current_user(); $currentuserroles = $currentuser -&gt; roles; if( in_array( 'author', $currentuserroles ) ){ $redirect = site_url().'/dashboard-teacher'; }elseif( in_array( 'subscriber', $currentuserroles ) ){ $redirect = site_url().'/dashboardwwp-student'; }else{ $redirect = site_url(); } wp_redirect( $redirect ); exit; } } </code></pre>
[ { "answer_id": 338497, "author": "Rafiq", "author_id": 141331, "author_profile": "https://wordpress.stackexchange.com/users/141331", "pm_score": 2, "selected": false, "text": "<p>Try this. It works for me.</p>\n\n<pre><code>add_filter( 'login_redirect', 'redirect_non_admin_to_dashboard'), 10, 3 );\nfunction redirect_non_admin_to_dashboard($redirect_to, $requested_redirect_to, $user ) {\n global $user;\n if( ! isset( $user-&gt;ID ) ) {\n return $redirect_to;\n }\n\n if ( ! in_array( 'author', (array) $user-&gt;roles ) ) {\n $redirect_to = site_url().'/dashboard-teacher';\n }elseif( in_array( 'subscriber',(array) $user-&gt;roles ) ){\n $redirect_to = site_url().'/dashboardwwp-student';\n\n }else{\n $redirect_to = site_url();\n\n }\n return wp_validate_redirect( $redirect_to, home_url() ); // return a safe redirect url between the site.\n}\n</code></pre>\n" }, { "answer_id": 338508, "author": "Ted Stresen-Reuter", "author_id": 112766, "author_profile": "https://wordpress.stackexchange.com/users/112766", "pm_score": 0, "selected": false, "text": "<ol>\n<li>You have a typo in your code: <code>$info['emember'] = $remember;</code> should be <code>$info['remember'] = $remember;</code> (\"remember\" is misspelled) but I don't think this is the source of the problem.</li>\n<li><code>wp_get_current_user();</code> returns either a WP_Error object or a WP_User object (the former if an error, the latter if an authenticated user exists). Rather than calling <code>wp_get_current_user()</code>, just use the WP_User object that was returned: <code>$user_signon-&gt;roles</code>. The less code, the less chance for error (although I don't think this is the error either).</li>\n<li><code>site_url()</code> is technically a template tag. Although it seems to return the site URL, it might not work if it is not \"in the loop\". Instead of using site_url, try swapping it out for <code>get_site_url()</code>. Also, both <code>site_url()</code> and <code>get_site_url()</code> accept two, optional parameters: 1) a path to append to the site URL and 2) the scheme to use. Instead of appending the path with the string concatenation operator (.), just put the path as the first parameter of the function: <code>$redirect = get_site_url('/dashboard-teacher')</code>. And again, I don't think either of these are the problem you are having.</li>\n<li>Redirection can be tricky in general, especially with WordPress. If any amount of data is output to the browser prior to calling redirect (e.g.: you use <code>wp_redirect()</code> in a template rather than in a hook called in functions.php), then redirection is not guaranteed even though these days both WordPress and browsers have some flexibility and can often handle this issue correctly.</li>\n</ol>\n\n<p>Other than the items I've mentioned above, your code looks fine and should work. So long as you are executing the login code before the <code>template_redirect</code> hook, it should work. Once you've addressed the issues above, if it continues to fail, then I would need to see the rest of the code you are using to process the form (what hook you are using) and probably I would need to see all the info regarding permissions and to verify the destination URLs before I could make any recommendations.</p>\n\n<p>HTH</p>\n" }, { "answer_id": 338555, "author": "Sh.Dehnavi", "author_id": 157522, "author_profile": "https://wordpress.stackexchange.com/users/157522", "pm_score": 2, "selected": true, "text": "<p>i found the answer myself. i used <code>wp_get_current_user()</code> while <code>wp_get_current_user()</code> may not be set at this step then i tried the <code>user_can</code> with <code>$user_signon</code> that i defined before for user login. so the new codes:<br>\n\n\n<pre><code> if( user_can($user_signon, 'author') ){\n\n $redirect = site_url().'/pishkhan-teacher';\n\n }elseif( user_can($user_signon, 'subscriber') ){\n\n $redirect = site_url('/pishkhan-student');\n\n }elseif( user_can($user_signon, 'wpas_user') ){\n\n $redirect = site_url('/pishkhan-student');\n\n }else{\n\n $redirect = site_url();\n\n }\n wp_redirect( $redirect );\n exit;\n</code></pre>\n" } ]
2019/05/22
[ "https://wordpress.stackexchange.com/questions/338492", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/157522/" ]
I created a custom login page and everything is OK but there is an issue. I want to redirect users to different pages based on their roles after login. My code is below but I do not know why it is not working: ``` if (!$has_error) { $info = array(); $info['user_login'] = $user_login; $info['user_password'] = $password; $info['emember'] = $remember; $user_signon = wp_signon($info,false); if(is_wp_error($user_signon)){ $has_error = true; $message[] = "an error"; }else{ $currentuser = wp_get_current_user(); $currentuserroles = $currentuser -> roles; if( in_array( 'author', $currentuserroles ) ){ $redirect = site_url().'/dashboard-teacher'; }elseif( in_array( 'subscriber', $currentuserroles ) ){ $redirect = site_url().'/dashboardwwp-student'; }else{ $redirect = site_url(); } wp_redirect( $redirect ); exit; } } ```
i found the answer myself. i used `wp_get_current_user()` while `wp_get_current_user()` may not be set at this step then i tried the `user_can` with `$user_signon` that i defined before for user login. so the new codes: ``` if( user_can($user_signon, 'author') ){ $redirect = site_url().'/pishkhan-teacher'; }elseif( user_can($user_signon, 'subscriber') ){ $redirect = site_url('/pishkhan-student'); }elseif( user_can($user_signon, 'wpas_user') ){ $redirect = site_url('/pishkhan-student'); }else{ $redirect = site_url(); } wp_redirect( $redirect ); exit; ```
338,526
<p>I have a server (server 1) which send requests to another server (server 2) where WordPress is installed and I am using their (server 2) WP REST API. </p> <p>The problem is that I can't create/send <code>wp-nonce</code> from server 1 to server 2, and I am getting the following response:</p> <pre><code>{ "code": "rest_not_logged_in", "message": "You are not currently logged in.", "data": { "status": 401 } } </code></pre> <p>I know that is not easy to disable nonce for REST API, but what is the proper way to send requests from another server to the WP REST API ?</p>
[ { "answer_id": 338532, "author": "John Swaringen", "author_id": 723, "author_profile": "https://wordpress.stackexchange.com/users/723", "pm_score": 1, "selected": false, "text": "<p>Try adding the following to your theme's functions.php file at the top. This will allow you to use Cross Domain calls from your functions.php.</p>\n\n<pre><code>function add_cors_http_header(){\n header(\"Access-Control-Allow-Origin: *\");\n}\nadd_action('init','add_cors_http_header');\n</code></pre>\n" }, { "answer_id": 338540, "author": "Derek Held", "author_id": 168370, "author_profile": "https://wordpress.stackexchange.com/users/168370", "pm_score": 2, "selected": false, "text": "<p>Since your specific scenario is a remote application making a request to WordPress you'll need to explore <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#authentication-plugins\" rel=\"nofollow noreferrer\">additional authentication methods available via plugins</a> for the REST API. I won't make any specific recommendations since I don't know your use case in detail but I'm sure you will find one that works well.</p>\n" } ]
2019/05/22
[ "https://wordpress.stackexchange.com/questions/338526", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152132/" ]
I have a server (server 1) which send requests to another server (server 2) where WordPress is installed and I am using their (server 2) WP REST API. The problem is that I can't create/send `wp-nonce` from server 1 to server 2, and I am getting the following response: ``` { "code": "rest_not_logged_in", "message": "You are not currently logged in.", "data": { "status": 401 } } ``` I know that is not easy to disable nonce for REST API, but what is the proper way to send requests from another server to the WP REST API ?
Since your specific scenario is a remote application making a request to WordPress you'll need to explore [additional authentication methods available via plugins](https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#authentication-plugins) for the REST API. I won't make any specific recommendations since I don't know your use case in detail but I'm sure you will find one that works well.
338,531
<p>I am trying to upload base 64 encoded images to my website media library via API. API returns with image ID but these images are displaying as blank images in my media library. Here is my code </p> <pre><code>add_action('rest_api_init', function () { register_rest_route( 'api/v1', 'upload_image/',array( 'methods' =&gt; 'POST', 'callback' =&gt; 'accept_image' )); }); function accept_image($request){ $parameters = $request-&gt;get_query_params(); $parameters = $parameters['image']; $decoded = base64_decode(str_replace('data:image/png;base64,','',$parameters)); $upload_dir = wp_upload_dir(); $upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR; $filename = 'my_image.png'; $hashed_filename = md5( $filename . microtime() ) . '_' . $filename; $image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded ); //HANDLE UPLOADED FILE if( !function_exists( 'wp_handle_sideload' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } // Without that I'm getting a debug error!? if( !function_exists( 'wp_get_current_user' ) ) { require_once( ABSPATH . 'wp-includes/pluggable.php' ); } // @new $file = array(); $file['error'] = ''; $file['tmp_name'] = $upload_path . $hashed_filename; $file['name'] = $hashed_filename; $file['type'] = 'image/png'; $file['size'] = filesize( $upload_path . $hashed_filename ); // upload file to server // @new use $file instead of $image_upload $file_return = wp_handle_sideload( $file, array( 'test_form' =&gt; false ) ); $filename = $file_return['file']; $attachment = array( 'post_mime_type' =&gt; $file_return['type'], 'post_title' =&gt; preg_replace('/\.[^.]+$/', '', basename($filename)), 'post_content' =&gt; '', 'post_status' =&gt; 'inherit', 'guid' =&gt; $wp_upload_dir['url'] . '/' . basename($filename) ); $attach_id = wp_insert_attachment( $attachment, $filename ); return $attach_id; } </code></pre> <p>I want to know where I have issue and how I can fix this. I will really appreciate your help. </p>
[ { "answer_id": 338606, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<p>You should generate the attachment metadata such as width and height &mdash; and file path, and also thumbnails, after you created the attachment:</p>\n\n<ul>\n<li>Using <a href=\"https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/\" rel=\"nofollow noreferrer\"><code>wp_generate_attachment_metadata()</code></a>:</li>\n</ul>\n\n<pre class=\"lang-php prettyprint-override\"><code>$attach_id = wp_insert_attachment( $attachment, $filename );\n\nif ( $attach_id ) {\n require_once ABSPATH . 'wp-admin/includes/image.php';\n $metadata = wp_generate_attachment_metadata( $attach_id, $filename );\n wp_update_attachment_metadata( $attach_id, $metadata );\n}\n</code></pre>\n\n<ul>\n<li>Using <a href=\"https://developer.wordpress.org/reference/functions/wp_maybe_generate_attachment_metadata/\" rel=\"nofollow noreferrer\"><code>wp_maybe_generate_attachment_metadata()</code></a>:</li>\n</ul>\n\n<pre class=\"lang-php prettyprint-override\"><code>$attach_id = wp_insert_attachment( $attachment, $filename );\n\nif ( $attachment = get_post( $attach_id ) ) {\n require_once ABSPATH . 'wp-admin/includes/image.php';\n wp_maybe_generate_attachment_metadata( $attachment );\n}\n</code></pre>\n\n<p><em>Or</em> you could simply use <a href=\"https://developer.wordpress.org/reference/functions/media_handle_sideload/\" rel=\"nofollow noreferrer\"><code>media_handle_sideload()</code></a> instead of <code>wp_handle_sideload()</code> to create the attachment (and its metadata). So you'd use this in place of what you currently have in between the <code>// upload file to server</code> and <code>return $attach_id;</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// upload file to server\nrequire_once ABSPATH . 'wp-admin/includes/media.php';\nrequire_once ABSPATH . 'wp-admin/includes/image.php';\n$attach_id = media_handle_sideload( $file, 0 );\n\nreturn $attach_id;\n</code></pre>\n" }, { "answer_id": 340508, "author": "wplearner", "author_id": 120693, "author_profile": "https://wordpress.stackexchange.com/users/120693", "pm_score": 1, "selected": true, "text": "<p>This function worked for me finally. </p>\n\n<pre><code>function accept_image($request){\nerror_reporting(E_ALL); \n//Image should be set as the body of the POST request, as a base-64 encoded string. \n//It should NOT include decorations such as data:image/png;base64, at the beginning. It should only be the encoded file itself.\n//Everything else should be sent via the header\n\n$is_valid = false;\nheader('Content-Type: application/json', true);\n$response = array('success'=&gt; $is_valid, 'message' =&gt; '');\n\n\n\n\n$image = $request-&gt;get_body();\n$decoded_file = base64_decode($image, true);\nif(strlen($image) == 0 || $decoded_file === false){\n return api_msg(false, 'An error occurred during base64_decode().');\n}\n\n\n$content_type = $request-&gt;get_header(\"Content-Type\");\n$ext = '';\nswitch($content_type){\n case \"image/jpg\":\n case \"image/jpeg\":\n $ext = \"jpg\";\n break;\n case \"image/png\";\n $ext = \"png\";\n break;\n default:\n return api_msg(false, \"Invalid Content-Type in request header. Acceptable formats are 'image/jpg' or 'image/png'.\");\n break;\n}\n\n\n\n\n\n$upload_dir = wp_upload_dir();\n$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;\n\n$rand = md5( rand(3,10) . microtime() );\n$hashed_filename = \"api_upload_{$rand}.{$ext}\";\n$image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded_file );\n\nif($image_upload === false)\nreturn api_msg(false, \"An error occurred during file_put_contents().\");\n\n$url_path = $upload_dir['url'] . '/' . $hashed_filename;\n$abs_path = $upload_path . $hashed_filename;\n\n\n$attachment = array(\n'post_mime_type' =&gt; $content_type,\n'post_title' =&gt; \"API Upload - \" . date('y-m-d H:i:s', time()),\n'post_content' =&gt; '',\n'post_status' =&gt; 'inherit',\n'guid' =&gt; $url_path,\n);\n$attach_id = wp_insert_attachment( $attachment, $abs_path );\n\n// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.\nrequire_once( ABSPATH . 'wp-admin/includes/image.php' );\n\n// Generate the metadata for the attachment, and update the database record.\n$attach_data = wp_generate_attachment_metadata( $attach_id, $abs_path );\n\nwp_update_attachment_metadata( $attach_id, $attach_data );\n\nreturn api_msg(true, \"Image Saved\", $attach_id, $url_path);\n\n}\n\nfunction api_msg($is_valid, $message, $id = null, $url = null){\n$resp = array(\n 'success' =&gt; $is_valid,\n 'message' =&gt; $message\n);\nif(!empty($id))\n $resp['id'] = $id;\nif(!empty($url))\n $resp['url'] = $url;\n\nreturn $resp;\n}\n</code></pre>\n" } ]
2019/05/22
[ "https://wordpress.stackexchange.com/questions/338531", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120693/" ]
I am trying to upload base 64 encoded images to my website media library via API. API returns with image ID but these images are displaying as blank images in my media library. Here is my code ``` add_action('rest_api_init', function () { register_rest_route( 'api/v1', 'upload_image/',array( 'methods' => 'POST', 'callback' => 'accept_image' )); }); function accept_image($request){ $parameters = $request->get_query_params(); $parameters = $parameters['image']; $decoded = base64_decode(str_replace('data:image/png;base64,','',$parameters)); $upload_dir = wp_upload_dir(); $upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR; $filename = 'my_image.png'; $hashed_filename = md5( $filename . microtime() ) . '_' . $filename; $image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded ); //HANDLE UPLOADED FILE if( !function_exists( 'wp_handle_sideload' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } // Without that I'm getting a debug error!? if( !function_exists( 'wp_get_current_user' ) ) { require_once( ABSPATH . 'wp-includes/pluggable.php' ); } // @new $file = array(); $file['error'] = ''; $file['tmp_name'] = $upload_path . $hashed_filename; $file['name'] = $hashed_filename; $file['type'] = 'image/png'; $file['size'] = filesize( $upload_path . $hashed_filename ); // upload file to server // @new use $file instead of $image_upload $file_return = wp_handle_sideload( $file, array( 'test_form' => false ) ); $filename = $file_return['file']; $attachment = array( 'post_mime_type' => $file_return['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit', 'guid' => $wp_upload_dir['url'] . '/' . basename($filename) ); $attach_id = wp_insert_attachment( $attachment, $filename ); return $attach_id; } ``` I want to know where I have issue and how I can fix this. I will really appreciate your help.
This function worked for me finally. ``` function accept_image($request){ error_reporting(E_ALL); //Image should be set as the body of the POST request, as a base-64 encoded string. //It should NOT include decorations such as data:image/png;base64, at the beginning. It should only be the encoded file itself. //Everything else should be sent via the header $is_valid = false; header('Content-Type: application/json', true); $response = array('success'=> $is_valid, 'message' => ''); $image = $request->get_body(); $decoded_file = base64_decode($image, true); if(strlen($image) == 0 || $decoded_file === false){ return api_msg(false, 'An error occurred during base64_decode().'); } $content_type = $request->get_header("Content-Type"); $ext = ''; switch($content_type){ case "image/jpg": case "image/jpeg": $ext = "jpg"; break; case "image/png"; $ext = "png"; break; default: return api_msg(false, "Invalid Content-Type in request header. Acceptable formats are 'image/jpg' or 'image/png'."); break; } $upload_dir = wp_upload_dir(); $upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR; $rand = md5( rand(3,10) . microtime() ); $hashed_filename = "api_upload_{$rand}.{$ext}"; $image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded_file ); if($image_upload === false) return api_msg(false, "An error occurred during file_put_contents()."); $url_path = $upload_dir['url'] . '/' . $hashed_filename; $abs_path = $upload_path . $hashed_filename; $attachment = array( 'post_mime_type' => $content_type, 'post_title' => "API Upload - " . date('y-m-d H:i:s', time()), 'post_content' => '', 'post_status' => 'inherit', 'guid' => $url_path, ); $attach_id = wp_insert_attachment( $attachment, $abs_path ); // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once( ABSPATH . 'wp-admin/includes/image.php' ); // Generate the metadata for the attachment, and update the database record. $attach_data = wp_generate_attachment_metadata( $attach_id, $abs_path ); wp_update_attachment_metadata( $attach_id, $attach_data ); return api_msg(true, "Image Saved", $attach_id, $url_path); } function api_msg($is_valid, $message, $id = null, $url = null){ $resp = array( 'success' => $is_valid, 'message' => $message ); if(!empty($id)) $resp['id'] = $id; if(!empty($url)) $resp['url'] = $url; return $resp; } ```