qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
296,440 | <p>I want to build a plugin to remove all posts by specific users from rest json output.
How can I add a <strong>filter</strong> or <strong>hook</strong> to do that?</p>
| [
{
"answer_id": 296444,
"author": "Alex Sancho",
"author_id": 2536,
"author_profile": "https://wordpress.stackexchange.com/users/2536",
"pm_score": 3,
"selected": true,
"text": "<p>If you're using WP 4.7+ you can filter the query using the <a href=\"https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/\" rel=\"nofollow noreferrer\"><code>rest_{$this->post_type}_query</code></a> hook <code>wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php:L267</code></p>\n<p>This is a working example that filters current query by given terms</p>\n<pre><code> $types = [\n 'post',\n 'page',\n ];\n\n foreach ( $types as $type ) {\n add_filter( 'rest_' . $type . '_query', 'filter_rest_query_by_zone', 10, 2 );\n }\n\n function filter_rest_query_by_zone( $args, $request ) {\n $zones = [ 'term1', 'term2', 'term3' ];\n\n $args['tax_query'] = array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'zones',\n 'field' => 'term_id',\n 'terms' => $zones\n )\n );\n\n return $args;\n }\n</code></pre>\n"
},
{
"answer_id": 296456,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Starting to feel like a parrot, but here it goes again :(... If you need results which are different than those returned by the API by default, just create your own end point. The more core will move into utilizing those APIs for admin, the more risky it will get to modify them in any way.</p>\n"
},
{
"answer_id": 370461,
"author": "Amal Ajith",
"author_id": 191133,
"author_profile": "https://wordpress.stackexchange.com/users/191133",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Filtering posts based on multiple custom taxonomy terms based on logical "AND", "OR" condition in wordpress rest api.</strong></p>\n<p>Here is what you need to do in the newer versions of Wordpress (v5 and above)</p>\n<p>Lets say you have two custom taxonomies: sector and offerings.</p>\n<p>Getting all posts that are tagged with taxonomy ID 51 "OR" 52 beloning to the taxonmy term "sector" "OR" Getting all posts that are tagged with taxonomy ID 57 "AND" 58 beloning to the taxonomy term "offering"</p>\n<pre><code>https://mywordpressbackend.com/wp-json/wp/v2/posts?sector=51+52&offering=57,58&tax_relation=OR\n</code></pre>\n<p>Getting all posts that are tagged with taxonomy ID 51 "OR" 52 beloning to the taxonmy term "sector" "AND" Getting all posts that are tagged with taxonomy ID 57 "AND" 58 beloning to the taxonomy term "offering"</p>\n<pre><code>https://mywordpressbackend.com/wp-json/wp/v2/posts?sector=51+52&offering=57,58&tax_relation=AN\n</code></pre>\n"
}
]
| 2018/03/11 | [
"https://wordpress.stackexchange.com/questions/296440",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45010/"
]
| I want to build a plugin to remove all posts by specific users from rest json output.
How can I add a **filter** or **hook** to do that? | If you're using WP 4.7+ you can filter the query using the [`rest_{$this->post_type}_query`](https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/) hook `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php:L267`
This is a working example that filters current query by given terms
```
$types = [
'post',
'page',
];
foreach ( $types as $type ) {
add_filter( 'rest_' . $type . '_query', 'filter_rest_query_by_zone', 10, 2 );
}
function filter_rest_query_by_zone( $args, $request ) {
$zones = [ 'term1', 'term2', 'term3' ];
$args['tax_query'] = array(
'relation' => 'AND',
array(
'taxonomy' => 'zones',
'field' => 'term_id',
'terms' => $zones
)
);
return $args;
}
``` |
296,442 | <p>We use SASS when building custom themes, and sometimes clients need a quick change made which is easier to do on the server rather than locally and pushing new changes. To that end, we've installed SASS on our server to watch for file changes. The problem is, if we use the WordPress Appearance Editor to edit SASS files, it defaults to tabs instead of spaces and we use spaces in the office. So SASS compiler (transpiler?) throws an error.</p>
<p>Is there any way to force the WordPress Appearance Editor to use Spaces instead of Tabs? I tried a quick search but everything seemed to be related to the WYSIWYG editor in pages/posts.</p>
| [
{
"answer_id": 296449,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>The WordPress theme/plugin (file) editor uses <a href=\"http://codemirror.net/\" rel=\"nofollow noreferrer\">CodeMirror</a> for syntax highlighting, and with the hook <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_code_editor/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_code_editor</code></a> (which is available starting from WordPress version 4.9.0), you can filter the default CodeMirror settings, as in the following example:</p>\n\n<pre><code>add_filter( 'wp_code_editor_settings', function( $settings ) {\n $settings['codemirror']['indentUnit'] = 2;\n $settings['codemirror']['indentWithTabs'] = false;\n return $settings;\n} );\n</code></pre>\n\n<p>See <a href=\"http://codemirror.net/doc/manual.html#config\" rel=\"nofollow noreferrer\">http://codemirror.net/doc/manual.html#config</a> if you'd like to change other CodeMirror settings.</p>\n\n<p>PS: You'd add the code above to the theme's <em>functions.php</em> file.</p>\n"
},
{
"answer_id": 296451,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": -1,
"selected": false,
"text": "<p>The wordpress editor should not be used, end of story. In addition to forcing a security hole, how do you git the changes, how do you test them before applying to production??</p>\n\n<p>The proper solution is to teach your clients the way of the GIT (command line in general), failing that, if all that is needed is CSS changes, they can do it in the customizer, which still violates \"best practice\" but at least you can test it properly before applying it to the live setup.</p>\n"
}
]
| 2018/03/11 | [
"https://wordpress.stackexchange.com/questions/296442",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90498/"
]
| We use SASS when building custom themes, and sometimes clients need a quick change made which is easier to do on the server rather than locally and pushing new changes. To that end, we've installed SASS on our server to watch for file changes. The problem is, if we use the WordPress Appearance Editor to edit SASS files, it defaults to tabs instead of spaces and we use spaces in the office. So SASS compiler (transpiler?) throws an error.
Is there any way to force the WordPress Appearance Editor to use Spaces instead of Tabs? I tried a quick search but everything seemed to be related to the WYSIWYG editor in pages/posts. | The WordPress theme/plugin (file) editor uses [CodeMirror](http://codemirror.net/) for syntax highlighting, and with the hook [`wp_enqueue_code_editor`](https://developer.wordpress.org/reference/functions/wp_enqueue_code_editor/) (which is available starting from WordPress version 4.9.0), you can filter the default CodeMirror settings, as in the following example:
```
add_filter( 'wp_code_editor_settings', function( $settings ) {
$settings['codemirror']['indentUnit'] = 2;
$settings['codemirror']['indentWithTabs'] = false;
return $settings;
} );
```
See <http://codemirror.net/doc/manual.html#config> if you'd like to change other CodeMirror settings.
PS: You'd add the code above to the theme's *functions.php* file. |
296,490 | <p>I made profile page. And i am getting values directly from inputs with $_POST method. Users update their profile in this page. I wonder is this security method? And i am using this in wp_list_table too.</p>
| [
{
"answer_id": 296492,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 3,
"selected": true,
"text": "<p>You have to sanitize or escape the data based on type and application of the data. Like below-</p>\n\n<pre><code>$title = sanitize_text_field( $_POST['title'] );\nupdate_post_meta( $post->ID, 'title', $title );\n</code></pre>\n\n<p>It's a quite huge topic. You better read this <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">Validating Sanitizing and Escaping User Data</a>.</p>\n"
},
{
"answer_id": 296494,
"author": "Levi Dulstein",
"author_id": 101988,
"author_profile": "https://wordpress.stackexchange.com/users/101988",
"pm_score": 0,
"selected": false,
"text": "<p>Apart from the WordPress functions that the_dramatist mentioned above by linking to <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">WordPress Codex</a>, there is also a very useful native PHP function that allows you to sanitize all data from $_POST super global at once: <code>filter_input_array</code>. See <a href=\"http://php.net/manual/en/function.filter-input-array.php\" rel=\"nofollow noreferrer\">php docs</a>. Example:</p>\n\n<pre><code>// let's say I'm expecting to get data like this:\n$_POST = [\n 'myString' => 'Hello World',\n 'myInteger' => 42,\n 'myArrayOfStrings' => [\n 'hello',\n 'world',\n ],\n];\n\n// sanitizing $_POST super global:\n\n$data = filter_input_array( INPUT_POST, [\n 'myString' => FILTER_SANITIZE_STRING,\n 'myInteger' => FILTER_VALIDATE_INT,\n 'myArrayOfStrings' => [\n 'filter' => FILTER_SANITIZE_STRING,\n 'flags' => FILTER_REQUIRE_ARRAY,\n ],\n] );\n\n// now $data contains array of sanitized values\n</code></pre>\n"
}
]
| 2018/03/12 | [
"https://wordpress.stackexchange.com/questions/296490",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133897/"
]
| I made profile page. And i am getting values directly from inputs with $\_POST method. Users update their profile in this page. I wonder is this security method? And i am using this in wp\_list\_table too. | You have to sanitize or escape the data based on type and application of the data. Like below-
```
$title = sanitize_text_field( $_POST['title'] );
update_post_meta( $post->ID, 'title', $title );
```
It's a quite huge topic. You better read this [Validating Sanitizing and Escaping User Data](https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data). |
296,512 | <p>Currently, I have a meta box that all Editors of my site can see. I want all contributers to see this meta box. </p>
<p>I've used a user-role plugin and it looks like the meta box is linked to post settings. As when I enable any user to publish post they can see this meta box. </p>
<p>Is there a way to make this meta-box viewable by all users but still make it so contributors cant publish posts. </p>
<p>I'm using Tagdiv-newspaper theme and trying to get the post settings meta box to show. </p>
<p>I believe the meta box id is: td_post_theme_settings_metabox</p>
<p>Thanks</p>
| [
{
"answer_id": 296492,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 3,
"selected": true,
"text": "<p>You have to sanitize or escape the data based on type and application of the data. Like below-</p>\n\n<pre><code>$title = sanitize_text_field( $_POST['title'] );\nupdate_post_meta( $post->ID, 'title', $title );\n</code></pre>\n\n<p>It's a quite huge topic. You better read this <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">Validating Sanitizing and Escaping User Data</a>.</p>\n"
},
{
"answer_id": 296494,
"author": "Levi Dulstein",
"author_id": 101988,
"author_profile": "https://wordpress.stackexchange.com/users/101988",
"pm_score": 0,
"selected": false,
"text": "<p>Apart from the WordPress functions that the_dramatist mentioned above by linking to <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">WordPress Codex</a>, there is also a very useful native PHP function that allows you to sanitize all data from $_POST super global at once: <code>filter_input_array</code>. See <a href=\"http://php.net/manual/en/function.filter-input-array.php\" rel=\"nofollow noreferrer\">php docs</a>. Example:</p>\n\n<pre><code>// let's say I'm expecting to get data like this:\n$_POST = [\n 'myString' => 'Hello World',\n 'myInteger' => 42,\n 'myArrayOfStrings' => [\n 'hello',\n 'world',\n ],\n];\n\n// sanitizing $_POST super global:\n\n$data = filter_input_array( INPUT_POST, [\n 'myString' => FILTER_SANITIZE_STRING,\n 'myInteger' => FILTER_VALIDATE_INT,\n 'myArrayOfStrings' => [\n 'filter' => FILTER_SANITIZE_STRING,\n 'flags' => FILTER_REQUIRE_ARRAY,\n ],\n] );\n\n// now $data contains array of sanitized values\n</code></pre>\n"
}
]
| 2018/03/12 | [
"https://wordpress.stackexchange.com/questions/296512",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137717/"
]
| Currently, I have a meta box that all Editors of my site can see. I want all contributers to see this meta box.
I've used a user-role plugin and it looks like the meta box is linked to post settings. As when I enable any user to publish post they can see this meta box.
Is there a way to make this meta-box viewable by all users but still make it so contributors cant publish posts.
I'm using Tagdiv-newspaper theme and trying to get the post settings meta box to show.
I believe the meta box id is: td\_post\_theme\_settings\_metabox
Thanks | You have to sanitize or escape the data based on type and application of the data. Like below-
```
$title = sanitize_text_field( $_POST['title'] );
update_post_meta( $post->ID, 'title', $title );
```
It's a quite huge topic. You better read this [Validating Sanitizing and Escaping User Data](https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data). |
296,529 | <p>I want to get unique results from this function</p>
<pre><code>global $wpdb;
$helloworld_id = $wpdb->get_results(
"SELECT * FROM $wpdb->postmeta WHERE meta_key = 'wc_billing_field_3465'"
);
foreach( $helloworld_id as $result ) {
echo $result->meta_value;
}
</code></pre>
| [
{
"answer_id": 296530,
"author": "Zachary Reese",
"author_id": 83342,
"author_profile": "https://wordpress.stackexchange.com/users/83342",
"pm_score": 0,
"selected": false,
"text": "<p>You'd want to use an array to store the results, then the <a href=\"http://php.net/manual/en/function.array-unique.php\" rel=\"nofollow noreferrer\">array_unique</a> function to remove duplicates.</p>\n\n<pre><code>global $wpdb;\n$billing_fields = $wpdb->get_results(\"SELECT * FROM $wpdb->postmeta WHERE meta_key = 'wc_billing_field_3465'\");\n// define your array\n$billing_fields_array = array(); \n\nforeach ( $billing_fields as $result ) {\n // push results to the array\n $billing_fields_array[] = $result->meta_value; \n}\n\n// sort the unique values\n$unique_billing_fields_array = array_unique($billing_fields_array);\n\nforeach($unique_billing_fields_array as $unique_result) {\n // echo each unique value\n echo $unique_result;\n}\n</code></pre>\n\n<p>I renamed <code>$helloworld_id</code> to <code>$billing_fields</code> to make things easier to read.</p>\n"
},
{
"answer_id": 296536,
"author": "josephmcm",
"author_id": 138254,
"author_profile": "https://wordpress.stackexchange.com/users/138254",
"pm_score": 1,
"selected": false,
"text": "<p>It would likely be more efficient to change your database query to</p>\n\n<blockquote>\n <p>SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wc_billing_field_3465'</p>\n</blockquote>\n"
}
]
| 2018/03/12 | [
"https://wordpress.stackexchange.com/questions/296529",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89477/"
]
| I want to get unique results from this function
```
global $wpdb;
$helloworld_id = $wpdb->get_results(
"SELECT * FROM $wpdb->postmeta WHERE meta_key = 'wc_billing_field_3465'"
);
foreach( $helloworld_id as $result ) {
echo $result->meta_value;
}
``` | It would likely be more efficient to change your database query to
>
> SELECT DISTINCT meta\_value FROM $wpdb->postmeta WHERE meta\_key = 'wc\_billing\_field\_3465'
>
>
> |
296,537 | <p>I am making a category template page with pagination and below is my code:</p>
<pre><code><?php
$current_page = get_queried_object();
$category = $current_page->slug;
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$query = new WP_Query(
array(
'paged' => $paged,
'category_name' => $category,
'order' => 'asc',
'post_type' => 'page',
'post_status' => array('publish'),
'posts_per_page' => 6,
'post_parent' => 2,
)
);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post(); ?>
<article id="post-<?php the_ID(); ?>">
<header class="entry-header">
<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
</header><!-- .entry-header -->
<div class="entry-content">
<?php the_content(); ?>
</div><!-- .entry-content -->
</article><!-- #post-## --><hr>
<?php
}
// next_posts_link() usage with max_num_pages
next_posts_link( 'Older Entries', $query->max_num_pages );
previous_posts_link( 'Newer Entries' );
wp_reset_postdata();
}
?>
</code></pre>
<p>So I have about 10 pages with the same category (e.g. arts).</p>
<p>And I will get the next page link from <code>next_posts_link( 'Older Entries', $query->max_num_pages );</code>. It generates link like this:</p>
<p><a href="http://mywebsite.com/category/arts/page/2/" rel="nofollow noreferrer">http://mywebsite.com/category/arts/page/2/</a></p>
<p>But I get a <strong>404</strong> page when I click on this url above. It should <strong>stays at the category template</strong>, shouldn't it?</p>
<p>So I added the <a href="https://wordpress.stackexchange.com/questions/58471/including-category-base-in-a-post-permalink-results-in-404">following fix</a> into functions.php:</p>
<pre><code>add_action( 'init', 'wpa58471_category_base' );
function wpa58471_category_base() {
// Remember to flush the rules once manually after you added this code!
add_rewrite_rule(
// The regex to match the incoming URL
'category/([^/]+)/page/([0-9]+)?/?$',
// The resulting internal URL
'index.php?category_name=$matches[1]&paged=$matches[2]',
// Add the rule to the top of the rewrite list
'top' );
}
</code></pre>
<p>But I still get the 404 page. What have I done wrong?</p>
<p><strong>Even if I access it with the direct address, I still get 404:</strong></p>
<p><a href="http://mywebsite.com/index.php?category_name=arts&paged=2" rel="nofollow noreferrer">http://mywebsite.com/index.php?category_name=arts&paged=2</a></p>
<p>Any ideas <strong>why</strong>? </p>
| [
{
"answer_id": 296548,
"author": "Run",
"author_id": 89898,
"author_profile": "https://wordpress.stackexchange.com/users/89898",
"pm_score": 1,
"selected": false,
"text": "<p>This how I fix this problem:</p>\n\n<pre><code>// Fix 404 on category pagination.\n// https://teamtreehouse.com/community/wordpress-pagination-gives-404-unless-i-set-blog-pages-show-at-most-to-1-in-reading\nadd_action( 'pre_get_posts', function($q) {\n if( !is_admin() && $q->is_main_query() && !$q->is_tax() ) {\n $q->set ('post_type', array( 'post', 'page' ) );\n }\n});\n</code></pre>\n\n<p>Pagination is meant for <strong>posts</strong> only I guess. So I must add <code>page</code> to the <code>post_type</code>.</p>\n"
},
{
"answer_id": 296552,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>The steps WordPress takes to serve a front end request are roughly-</p>\n\n<ol>\n<li><p>The incoming URL is parsed and converted to query vars.</p></li>\n<li><p>These query vars form the <strong>Main Query</strong>, which is sent to the database.</p></li>\n<li><p>WordPress looks at the results and determines if the request was successful or not, which determines what status header to send- 200 OK, or 404 not found.</p></li>\n<li><p>WordPress loads the template that corresponds to this type of request, for example, a category archive template in the case of your category request, or the 404 template, in the case the main query has no posts.</p></li>\n</ol>\n\n<p>So the shortest answer to your question as to why you are seeing a 404, is that the main query has no posts.</p>\n\n<p>The query you run in the template and whatever pagination it generates is irrelevant to the main query. This is why you need to <em>alter the main query</em> with <code>pre_get_posts</code> to customize the results of an archive page.</p>\n\n<p>If you just want pages, you can set post type to just <code>page</code>:</p>\n\n<pre><code>add_action( 'pre_get_posts', function($q) {\n if( !is_admin() && $q->is_main_query() && !$q->is_tax() ) {\n $q->set ('post_type', array( 'page' ) );\n }\n});\n</code></pre>\n"
}
]
| 2018/03/12 | [
"https://wordpress.stackexchange.com/questions/296537",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89898/"
]
| I am making a category template page with pagination and below is my code:
```
<?php
$current_page = get_queried_object();
$category = $current_page->slug;
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$query = new WP_Query(
array(
'paged' => $paged,
'category_name' => $category,
'order' => 'asc',
'post_type' => 'page',
'post_status' => array('publish'),
'posts_per_page' => 6,
'post_parent' => 2,
)
);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post(); ?>
<article id="post-<?php the_ID(); ?>">
<header class="entry-header">
<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
</header><!-- .entry-header -->
<div class="entry-content">
<?php the_content(); ?>
</div><!-- .entry-content -->
</article><!-- #post-## --><hr>
<?php
}
// next_posts_link() usage with max_num_pages
next_posts_link( 'Older Entries', $query->max_num_pages );
previous_posts_link( 'Newer Entries' );
wp_reset_postdata();
}
?>
```
So I have about 10 pages with the same category (e.g. arts).
And I will get the next page link from `next_posts_link( 'Older Entries', $query->max_num_pages );`. It generates link like this:
<http://mywebsite.com/category/arts/page/2/>
But I get a **404** page when I click on this url above. It should **stays at the category template**, shouldn't it?
So I added the [following fix](https://wordpress.stackexchange.com/questions/58471/including-category-base-in-a-post-permalink-results-in-404) into functions.php:
```
add_action( 'init', 'wpa58471_category_base' );
function wpa58471_category_base() {
// Remember to flush the rules once manually after you added this code!
add_rewrite_rule(
// The regex to match the incoming URL
'category/([^/]+)/page/([0-9]+)?/?$',
// The resulting internal URL
'index.php?category_name=$matches[1]&paged=$matches[2]',
// Add the rule to the top of the rewrite list
'top' );
}
```
But I still get the 404 page. What have I done wrong?
**Even if I access it with the direct address, I still get 404:**
<http://mywebsite.com/index.php?category_name=arts&paged=2>
Any ideas **why**? | The steps WordPress takes to serve a front end request are roughly-
1. The incoming URL is parsed and converted to query vars.
2. These query vars form the **Main Query**, which is sent to the database.
3. WordPress looks at the results and determines if the request was successful or not, which determines what status header to send- 200 OK, or 404 not found.
4. WordPress loads the template that corresponds to this type of request, for example, a category archive template in the case of your category request, or the 404 template, in the case the main query has no posts.
So the shortest answer to your question as to why you are seeing a 404, is that the main query has no posts.
The query you run in the template and whatever pagination it generates is irrelevant to the main query. This is why you need to *alter the main query* with `pre_get_posts` to customize the results of an archive page.
If you just want pages, you can set post type to just `page`:
```
add_action( 'pre_get_posts', function($q) {
if( !is_admin() && $q->is_main_query() && !$q->is_tax() ) {
$q->set ('post_type', array( 'page' ) );
}
});
``` |
296,589 | <p>I try every solution what I find on the net, but none of them work. I using generatepress.</p>
<p>My latest trying that, but not working...:</p>
<pre><code>if ( is_front_page() && is_home() ) {
remove_theme_support( 'title-tag' );
echo '<title>' . get_bloginfo( 'name' ) . ' | mydomain.com</title>';
}
</code></pre>
<p>Very frustrating, but it does not matter what i writing to between the <code><title></code> tags, I can even leave it empty so: <code><title></title></code>, in every case the output will be this:</p>
<pre><code> My Site Title | Tagline
</code></pre>
<p>I cannot use plugin for this, because I launch a multisite, and example if I modify my SEO plugin defaults settings in that core, the titles not will be dinamic on the home pages, so example my user create a page with this title: Original Site Title, I can solve it, that will be the home page title, if I get the bloginfo( 'name' ) in the All In One SEO Pack's core, but if my user change him site's title to Changed Site Title, the <code><title></code> tag (what generating the plugin) will using later on the first title.</p>
| [
{
"answer_id": 296593,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 3,
"selected": true,
"text": "<p>If first check in your header.php file and check in title tag what is print. if in title tag bloginfo then it's replace with wp_title('') because bloginfo is not replace with code. </p>\n\n<p>Header.php</p>\n\n<pre><code><title><?php wp_title(''); ?></title>\n</code></pre>\n\n<p>After function.php file put this code:</p>\n\n<pre><code> function wpdocs_theme_name_wp_title( $title, $sep ) {\n if ( is_feed() ) {\n return $title;\n }\n\n if ( is_home() || is_front_page() ) {\n return $title;\n }\n\n global $page, $paged;\n\n // Add the blog name\n $title .= bloginfo( 'name' );\n\n // Add a page number if necessary:\n if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) {\n $title .= \" $sep \" . sprintf( __( 'Page %s', '_s' ), max( $paged, $page ) );\n }\n\n return $title;\n}\nadd_filter( 'wp_title', 'wpdocs_theme_name_wp_title', 10, 2 );\n</code></pre>\n\n<p>NOTE: your title tag is blank then in tab display your SITE URL.</p>\n"
},
{
"answer_id": 296595,
"author": "Galgóczi Levente",
"author_id": 134567,
"author_profile": "https://wordpress.stackexchange.com/users/134567",
"pm_score": 0,
"selected": false,
"text": "<p>If you using All In One SEO Pack and dont working for you Patel Jignesh's solution, your problem originate from the plugin. I just managed to solve it, that I updated the core file: all-in-one-seo-pack/aioseop_class.php row 1612.\nChange this (on row 1612):</p>\n\n<pre><code> $title = $this->internationalize( get_option( 'blogname' ) ) . ' | ' . $this-\n >internationalize( get_bloginfo( 'description' ) );\n</code></pre>\n\n<p>To your preferred title, example:</p>\n\n<pre><code> $title = '' . get_bloginfo( 'name' ) . ' | Your Network Title';\n</code></pre>\n\n<p>My situation is isolated, because if dont need for you at all events dinamically generating the home page title and description with AIOSEP on your subsites, you can do simply write your and your client's subsites seo titles in the plugin's general settings.</p>\n\n<p>But, if you are in a similar situation, I recommend you call the subsite's description on your theme's header file, because counter to the title, the AIOSEP dont generate description if the $description is empty, so your subsites home's will dont have meta descriptions. (Otherwise even though I like this plugin, dont clear for me, why calling the <code>get_bloginfo( 'description' )</code> in the home_title, that the $title (and also the $description) is empty, instead of it fill in both metas...)</p>\n\n<p>Use this code in your header:</p>\n\n<pre><code> if ( is_front_page() || is_home() ) {\n $homedesc = 'description';\n echo '<meta name=\"description\" content=\"' . get_bloginfo( '' . $homedesc \n . '' ) . '\" />';\n }\n</code></pre>\n"
}
]
| 2018/03/13 | [
"https://wordpress.stackexchange.com/questions/296589",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134567/"
]
| I try every solution what I find on the net, but none of them work. I using generatepress.
My latest trying that, but not working...:
```
if ( is_front_page() && is_home() ) {
remove_theme_support( 'title-tag' );
echo '<title>' . get_bloginfo( 'name' ) . ' | mydomain.com</title>';
}
```
Very frustrating, but it does not matter what i writing to between the `<title>` tags, I can even leave it empty so: `<title></title>`, in every case the output will be this:
```
My Site Title | Tagline
```
I cannot use plugin for this, because I launch a multisite, and example if I modify my SEO plugin defaults settings in that core, the titles not will be dinamic on the home pages, so example my user create a page with this title: Original Site Title, I can solve it, that will be the home page title, if I get the bloginfo( 'name' ) in the All In One SEO Pack's core, but if my user change him site's title to Changed Site Title, the `<title>` tag (what generating the plugin) will using later on the first title. | If first check in your header.php file and check in title tag what is print. if in title tag bloginfo then it's replace with wp\_title('') because bloginfo is not replace with code.
Header.php
```
<title><?php wp_title(''); ?></title>
```
After function.php file put this code:
```
function wpdocs_theme_name_wp_title( $title, $sep ) {
if ( is_feed() ) {
return $title;
}
if ( is_home() || is_front_page() ) {
return $title;
}
global $page, $paged;
// Add the blog name
$title .= bloginfo( 'name' );
// Add a page number if necessary:
if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) {
$title .= " $sep " . sprintf( __( 'Page %s', '_s' ), max( $paged, $page ) );
}
return $title;
}
add_filter( 'wp_title', 'wpdocs_theme_name_wp_title', 10, 2 );
```
NOTE: your title tag is blank then in tab display your SITE URL. |
296,592 | <p>I have wordpress installed in root folder of domain.com</p>
<p>I want to load index.html when domain.com is visited and domain.com/my-posts/ should load normal wordpress posts.</p>
<p>I am doing this to increase speed of my wordpress homepage.I dont want any php to be involved.</p>
<p>Will renaming index.php to index.html and putting my html content will work ?</p>
| [
{
"answer_id": 296816,
"author": "Dave Hunt",
"author_id": 1769,
"author_profile": "https://wordpress.stackexchange.com/users/1769",
"pm_score": 2,
"selected": false,
"text": "<p>If your concern is that PHP or MySQL is causing the page load speed to decrease, I recommend installing a Caching plugin and configuring Page Caching. A free plugin that I've used for this purpose is <a href=\"https://en-ca.wordpress.org/plugins/w3-total-cache/\" rel=\"nofollow noreferrer\">W3 Total Cache</a></p>\n\n<p>Page caching essentially does what you are looking for, which is to serve a static HTML file with CSS and Javascript assets, instead of running PHP and MySQL queries whenever a page is loaded.</p>\n\n<p>It does this by pre-generating each page as a static HTML file, and then serves those static files in place of the dynamic PHP / MySQL Wordpress engine.</p>\n\n<p>It's much easier to set up than having to manage a separate static HTML file for your landing page.</p>\n"
},
{
"answer_id": 296819,
"author": "Xhynk",
"author_id": 13724,
"author_profile": "https://wordpress.stackexchange.com/users/13724",
"pm_score": 4,
"selected": true,
"text": "<p>I <strong>strongly</strong> advise you to heed the advice already given. If your PHP is well structured and you take advantage of caching methods, it won't have a significant increase on your page load time. We've got pages with extremely complex queries that are hardly optimized, but using some clever caching methods, we're able to get those pages served in 500-900ms, or 2-3s for some of the much more complex pages.</p>\n\n<p>It's a much better long term solution than using a static HTML page as your homepage.</p>\n\n<p><em>That said</em> - if you still wish to proceed with a static HTML homepage instead (again, please don't, <strong>especially</strong> if the only reason is \"page speed\", since there are so many other ways to decrease your page load time)</p>\n\n<p>... Still reading?</p>\n\n<h1>Method 1: .htaccess</h1>\n\n<p>The… … \"generally accepted\" way to do this is with a <code>.htaccess</code> rule that targets your homepage only, such as <code>RewriteRule ^$ http://example.com/path-to-html.html [L,R=301]</code></p>\n\n<h1>Method 2: Page Template</h1>\n\n<p>Alternatively, to maintain <em>some</em> semblance to the WordPress ecosystem would be to set up a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"noreferrer\">Page Template</a></p>\n\n<ul>\n<li>Add a <code>home.php</code> (yes, PHP file) to your active theme directory: <code>/wp-content/themes/CURRENT-THEME/home.php</code>.</li>\n<li><p>Place the following \"Page Template Header\" code in that file (leave a note to your future self/fellow devs that say where the file is so it's less confusing):</p>\n\n<pre><code><?php\n /*\n * Template Name: My HTML Homepage\n */\n?>\n<!-- This page is generated outside of WP by: /wp-content/themes/CURRENT-THEME/home.php -->\n<!-- Your HTML Code Here -->\n</code></pre></li>\n<li><p>Add a new Page with <strong>Pages</strong> > <strong>Add New</strong> with a recognizable name, such as \"My HTML Homepage\"</p></li>\n<li>On the right hand side, in the <strong>Template</strong> selector, choose \"My HTML Homepage\" as the template.</li>\n<li>In <strong>Settings</strong> > <strong>Reading</strong> change \"Your Homepage Displays:\" to \"A Static Page\", and pick the \"My HTML Homepage\" page you just added.</li>\n</ul>\n\n<h1>Method 3: Move your WordPress Install</h1>\n\n<p>You can also just install WordPress on a subdirectory, have <code>index.html</code> in the root directory, and use .htaccess to remove the /wp from your URLs.</p>\n\n<h1>Method 4: Don't.</h1>\n\n<p>Again, I <strong>strongly</strong> urge you to consider other methods:</p>\n\n<ul>\n<li>Taking advantaged of PHP 7.x and memcache/d</li>\n<li>Caching plugins like WP Super Cache/W3 Total Cache</li>\n<li>Optimizing your images (manually or with WP Smush)\n\n<ul>\n<li>Serve images from a CDN</li>\n</ul></li>\n<li>Optimizing Script/Style delivery (WP Hummingbird can help with this):\n\n<ul>\n<li>Combine files where appropriate/able</li>\n<li>Minify those files</li>\n<li>Serve those files from a CDN</li>\n</ul></li>\n<li>Remove unnecessary plugins from WP, optimize JS functions, remove unused CSS selectors, etc.</li>\n</ul>\n"
},
{
"answer_id": 403648,
"author": "Jeremy",
"author_id": 220204,
"author_profile": "https://wordpress.stackexchange.com/users/220204",
"pm_score": 0,
"selected": false,
"text": "<p>Another method if you're using Apache is to name your index file something special and prepend that name to your DirectoryIndexes. For example:</p>\n<ol>\n<li><p>Save your static index file as <code>index-static.html</code></p>\n</li>\n<li><p>Open <code>httpd.conf</code> and edit the <code>DirectoryIndex</code> list</p>\n<pre><code><IfModule dir_module>\n DirectoryIndex index-static.html index.php index.html\n</IfModule>\n</code></pre>\n</li>\n<li><p>Save <code>httpd.conf</code> and run <code>sudo service httpd restart</code></p>\n</li>\n</ol>\n<p>Compared to Method 1 in the previous answer, this method has the benefit of not modifying your homepage URL — that is, visitors won't see <code>static-index.html</code> appended to the domain when they visit your site because no redirect occurs. This is probably better for SEO purposes in addition to being transparent to visitors.</p>\n"
}
]
| 2018/03/13 | [
"https://wordpress.stackexchange.com/questions/296592",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138510/"
]
| I have wordpress installed in root folder of domain.com
I want to load index.html when domain.com is visited and domain.com/my-posts/ should load normal wordpress posts.
I am doing this to increase speed of my wordpress homepage.I dont want any php to be involved.
Will renaming index.php to index.html and putting my html content will work ? | I **strongly** advise you to heed the advice already given. If your PHP is well structured and you take advantage of caching methods, it won't have a significant increase on your page load time. We've got pages with extremely complex queries that are hardly optimized, but using some clever caching methods, we're able to get those pages served in 500-900ms, or 2-3s for some of the much more complex pages.
It's a much better long term solution than using a static HTML page as your homepage.
*That said* - if you still wish to proceed with a static HTML homepage instead (again, please don't, **especially** if the only reason is "page speed", since there are so many other ways to decrease your page load time)
... Still reading?
Method 1: .htaccess
===================
The… … "generally accepted" way to do this is with a `.htaccess` rule that targets your homepage only, such as `RewriteRule ^$ http://example.com/path-to-html.html [L,R=301]`
Method 2: Page Template
=======================
Alternatively, to maintain *some* semblance to the WordPress ecosystem would be to set up a [Page Template](https://developer.wordpress.org/themes/template-files-section/page-template-files/)
* Add a `home.php` (yes, PHP file) to your active theme directory: `/wp-content/themes/CURRENT-THEME/home.php`.
* Place the following "Page Template Header" code in that file (leave a note to your future self/fellow devs that say where the file is so it's less confusing):
```
<?php
/*
* Template Name: My HTML Homepage
*/
?>
<!-- This page is generated outside of WP by: /wp-content/themes/CURRENT-THEME/home.php -->
<!-- Your HTML Code Here -->
```
* Add a new Page with **Pages** > **Add New** with a recognizable name, such as "My HTML Homepage"
* On the right hand side, in the **Template** selector, choose "My HTML Homepage" as the template.
* In **Settings** > **Reading** change "Your Homepage Displays:" to "A Static Page", and pick the "My HTML Homepage" page you just added.
Method 3: Move your WordPress Install
=====================================
You can also just install WordPress on a subdirectory, have `index.html` in the root directory, and use .htaccess to remove the /wp from your URLs.
Method 4: Don't.
================
Again, I **strongly** urge you to consider other methods:
* Taking advantaged of PHP 7.x and memcache/d
* Caching plugins like WP Super Cache/W3 Total Cache
* Optimizing your images (manually or with WP Smush)
+ Serve images from a CDN
* Optimizing Script/Style delivery (WP Hummingbird can help with this):
+ Combine files where appropriate/able
+ Minify those files
+ Serve those files from a CDN
* Remove unnecessary plugins from WP, optimize JS functions, remove unused CSS selectors, etc. |
296,612 | <p>I try to build an plugin with an custom db table. So I include the notifications.php in the plugin index.php file. If I do a die; in the public function init() (in notifications.php), it dies so it's loaded, but the register_activation_hook not triggers on activate te plugin and the my_notifications_install fuction not execute. What's the problem? The activation not respond with an error.</p>
<p>The plugin structure:</p>
<p>/plugins/plugindir/index.php</p>
<pre><code>// Notifications
include_once plugin_dir_path( __FILE__ ) . '/notifications.php';
$my_notifications = new my_notifications( __FILE__ );
</code></pre>
<p>/plugins/plugindir/notifications.php</p>
<pre><code>class my_notifications {
public function __construct( ) {
$this->init();
}
public function init() {
global $my_notifications_db_version;
$my_notifications_db_version = '1.0';
register_activation_hook( __FILE__, array( $this, 'my_notifications_install' ) );
}
private function my_notifications_install() {
global $wpdb;
global $my_notifications_db_version;
$table_name = $wpdb->prefix . 'my_notifications';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
user_id mediumint(9) NOT NULL,
post_id mediumint(9) NOT NULL,
attachment_id mediumint(9) NOT NULL,
message text NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
add_option( 'my_notifications_db_version', $my_notifications_db_version );
}
</code></pre>
<p>}</p>
| [
{
"answer_id": 296615,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 1,
"selected": false,
"text": "<pre><code>register_activation_hook( __FILE__, array( $this, 'my_notifications_install' ) );\n</code></pre>\n<p>This should be in main plugin file. Because it use <strong>FILE</strong> to create name of hook. So change the reference or move this peace of code to main plugin file.</p>\n<p>Check this link for more info about <code>register_activation_hook</code> <a href=\"https://developer.wordpress.org/reference/functions/register_activation_hook/\" rel=\"nofollow noreferrer\">codex</a>, noone there use $this as reference to object, I saw &$this in some plugins for example wp-discuzz.</p>\n<p>Also using <code>db_delta</code> with <code>plugin activation hook</code> is not good idea because when You need to <code>update</code> Your <code>table schema</code> after next release You need manually restart Your plugin because <code>Wordpress</code> doesn't trigger activation_hook while update since version 3.9 and <code>dbdelta</code> check of table exists and does nothing when table already exist if You use it more often than only on <code>activation hook</code>.</p>\n"
},
{
"answer_id": 296628,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": true,
"text": "<p>The rule of thumb is to never do anything which is not triggered by action or filter. </p>\n\n<p>In this case you try register a hook before wordpress even finished to \"boot\". This may work sometimes, but totally not an healthy idea. Use at least the 'init' hook (and even better the 'wp_loaded' if you can), to trigger you initialization, and do not do anything before that unless you have a very good reason.</p>\n\n<p>As for the activation hook, be very careful with trusting it being triggered as it will not be triggered on multisite install, and not when updates are done, so you might as well plan in advance and detect by yourself when DB initialization or updates are required.</p>\n"
}
]
| 2018/03/13 | [
"https://wordpress.stackexchange.com/questions/296612",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54693/"
]
| I try to build an plugin with an custom db table. So I include the notifications.php in the plugin index.php file. If I do a die; in the public function init() (in notifications.php), it dies so it's loaded, but the register\_activation\_hook not triggers on activate te plugin and the my\_notifications\_install fuction not execute. What's the problem? The activation not respond with an error.
The plugin structure:
/plugins/plugindir/index.php
```
// Notifications
include_once plugin_dir_path( __FILE__ ) . '/notifications.php';
$my_notifications = new my_notifications( __FILE__ );
```
/plugins/plugindir/notifications.php
```
class my_notifications {
public function __construct( ) {
$this->init();
}
public function init() {
global $my_notifications_db_version;
$my_notifications_db_version = '1.0';
register_activation_hook( __FILE__, array( $this, 'my_notifications_install' ) );
}
private function my_notifications_install() {
global $wpdb;
global $my_notifications_db_version;
$table_name = $wpdb->prefix . 'my_notifications';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
user_id mediumint(9) NOT NULL,
post_id mediumint(9) NOT NULL,
attachment_id mediumint(9) NOT NULL,
message text NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
add_option( 'my_notifications_db_version', $my_notifications_db_version );
}
```
} | The rule of thumb is to never do anything which is not triggered by action or filter.
In this case you try register a hook before wordpress even finished to "boot". This may work sometimes, but totally not an healthy idea. Use at least the 'init' hook (and even better the 'wp\_loaded' if you can), to trigger you initialization, and do not do anything before that unless you have a very good reason.
As for the activation hook, be very careful with trusting it being triggered as it will not be triggered on multisite install, and not when updates are done, so you might as well plan in advance and detect by yourself when DB initialization or updates are required. |
296,620 | <p>I'm writing a plugin which collects a pretty large feed. From each feed item a custom post will be created. The feed can also contain images for each item that is uploaded from the remote url. Processing the entire feed can take some time and since I would like to do the processing in the background I am looking into cron as a way to achieve this. Currently I'm doing something like this:</p>
<pre><code>class Cron_Task {
const DEFAULT_TASK_INTERVAL = 30;
public function __construct($taskName, $data) {
add_filter('cron_schedules', array($this, 'addSchedule'));
add_action('cron_task', 'Cron_Task::run');
if (!wp_next_scheduled('cron_task', array($taskName))) {
// Store data in cache.
set_transient($taskName, serialize($data));
wp_schedule_event(time(), $taskName, 'cron_task', array($taskName));
}
}
public static function processItem($data) {
// Execute long running task.
}
public function addSchedule($schedules) {
$schedules['crontask'] = array(
'interval' => self::DEFAULT_TASK_INTERVAL,
'display' => __('Cron_Task'),
);
return $schedules;
}
public static function run($taskName) {
// Get data from cache.
$data = unserialize(get_transient($taskName));
if ($data) {
$item = array_shift($data);
// Process one item.
self::processItem($item);
// Check if we have processed all items.
if (!count($data)) {
delete_transient($taskName);
wp_clear_scheduled_hook('cron_task', array($taskName));
} else {
// Update the items to process.
set_transient($taskName, serialize($data));
}
}
}
}
// When a feed is collected we create a cron_task to be run every 30 seconds.
if (get_feed()) {
$cronTask = new Cron_Task('testEvent', $feed);
}
</code></pre>
<p>The above sort of works, but I think there must be a better way of doing this kind of thing? For instance, since the configured cron tasks will only be run on page load, the task might not be run at the desired interval if there are no visitors.</p>
| [
{
"answer_id": 296615,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 1,
"selected": false,
"text": "<pre><code>register_activation_hook( __FILE__, array( $this, 'my_notifications_install' ) );\n</code></pre>\n<p>This should be in main plugin file. Because it use <strong>FILE</strong> to create name of hook. So change the reference or move this peace of code to main plugin file.</p>\n<p>Check this link for more info about <code>register_activation_hook</code> <a href=\"https://developer.wordpress.org/reference/functions/register_activation_hook/\" rel=\"nofollow noreferrer\">codex</a>, noone there use $this as reference to object, I saw &$this in some plugins for example wp-discuzz.</p>\n<p>Also using <code>db_delta</code> with <code>plugin activation hook</code> is not good idea because when You need to <code>update</code> Your <code>table schema</code> after next release You need manually restart Your plugin because <code>Wordpress</code> doesn't trigger activation_hook while update since version 3.9 and <code>dbdelta</code> check of table exists and does nothing when table already exist if You use it more often than only on <code>activation hook</code>.</p>\n"
},
{
"answer_id": 296628,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": true,
"text": "<p>The rule of thumb is to never do anything which is not triggered by action or filter. </p>\n\n<p>In this case you try register a hook before wordpress even finished to \"boot\". This may work sometimes, but totally not an healthy idea. Use at least the 'init' hook (and even better the 'wp_loaded' if you can), to trigger you initialization, and do not do anything before that unless you have a very good reason.</p>\n\n<p>As for the activation hook, be very careful with trusting it being triggered as it will not be triggered on multisite install, and not when updates are done, so you might as well plan in advance and detect by yourself when DB initialization or updates are required.</p>\n"
}
]
| 2018/03/13 | [
"https://wordpress.stackexchange.com/questions/296620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14870/"
]
| I'm writing a plugin which collects a pretty large feed. From each feed item a custom post will be created. The feed can also contain images for each item that is uploaded from the remote url. Processing the entire feed can take some time and since I would like to do the processing in the background I am looking into cron as a way to achieve this. Currently I'm doing something like this:
```
class Cron_Task {
const DEFAULT_TASK_INTERVAL = 30;
public function __construct($taskName, $data) {
add_filter('cron_schedules', array($this, 'addSchedule'));
add_action('cron_task', 'Cron_Task::run');
if (!wp_next_scheduled('cron_task', array($taskName))) {
// Store data in cache.
set_transient($taskName, serialize($data));
wp_schedule_event(time(), $taskName, 'cron_task', array($taskName));
}
}
public static function processItem($data) {
// Execute long running task.
}
public function addSchedule($schedules) {
$schedules['crontask'] = array(
'interval' => self::DEFAULT_TASK_INTERVAL,
'display' => __('Cron_Task'),
);
return $schedules;
}
public static function run($taskName) {
// Get data from cache.
$data = unserialize(get_transient($taskName));
if ($data) {
$item = array_shift($data);
// Process one item.
self::processItem($item);
// Check if we have processed all items.
if (!count($data)) {
delete_transient($taskName);
wp_clear_scheduled_hook('cron_task', array($taskName));
} else {
// Update the items to process.
set_transient($taskName, serialize($data));
}
}
}
}
// When a feed is collected we create a cron_task to be run every 30 seconds.
if (get_feed()) {
$cronTask = new Cron_Task('testEvent', $feed);
}
```
The above sort of works, but I think there must be a better way of doing this kind of thing? For instance, since the configured cron tasks will only be run on page load, the task might not be run at the desired interval if there are no visitors. | The rule of thumb is to never do anything which is not triggered by action or filter.
In this case you try register a hook before wordpress even finished to "boot". This may work sometimes, but totally not an healthy idea. Use at least the 'init' hook (and even better the 'wp\_loaded' if you can), to trigger you initialization, and do not do anything before that unless you have a very good reason.
As for the activation hook, be very careful with trusting it being triggered as it will not be triggered on multisite install, and not when updates are done, so you might as well plan in advance and detect by yourself when DB initialization or updates are required. |
296,699 | <p>For the purposes of my site, I have my Permalinks set to <code>/blog/%postname%/</code> for all posts.</p>
<p>However, I need to give Posts with a specific Category (in this case, "Testimonials") its own permalink structure, where each individual post assigned the Category "Testimonials" returns as <code>/testimonials/%postname%/</code> and the Category Archive page returns as <code>/testimonials/</code>. </p>
<p>Here is the code I have so far:</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->ID);
if ( !empty($category) && $category[0]->cat_name == "Testimonials" ) {
$cat_name = strtolower($category[0]->cat_name);
$permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post->post_name .'/' ) );
}
return $permalink;
}
add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
'testimonials/([^/]+)(?:/([0-9]+))?/?$',
'index.php?category_name=testimonials&name=$matches[1]&page=$matches[2]',
'top' // The rule position; either 'top' or 'bottom' (default).
);
}
</code></pre>
<p>This successfully returns each individual post with the category "Testimonials" as <code>/testimonials/%postname%/</code>. However, the Category Archive page returns as <code>/blog/category/testimonials</code>. I need this to just return as <code>/testimonials/</code>, while still returning all other Posts as <code>/blog/%postname%/</code></p>
<p>I tried using this plugin, <a href="https://wordpress.org/plugins/custom-permalinks/" rel="nofollow noreferrer">https://wordpress.org/plugins/custom-permalinks/</a>, which solved the Category Archive page issue, but broke each individual testimonial post, returning them as a 404 error.</p>
<p>In this case, I cannot register Testimonials as a Custom Post Type as it will affect other site functionality, </p>
| [
{
"answer_id": 296703,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 4,
"selected": true,
"text": "<p>Try these steps:</p>\n\n<p><strong>Step #1:</strong> Replace this:</p>\n\n<pre><code>add_action( 'init', 'custom_rewrite_rules' );\nfunction custom_rewrite_rules() {\n add_rewrite_rule(\n 'testimonials/([^/]+)(?:/([0-9]+))?/?$',\n 'index.php?category_name=testimonials&name=$matches[1]&page=$matches[2]',\n 'top' // The rule position; either 'top' or 'bottom' (default).\n );\n}\n</code></pre>\n\n<p>..with this one:</p>\n\n<pre><code>add_filter( 'category_link', 'custom_category_permalink', 10, 2 );\nfunction custom_category_permalink( $link, $cat_id ) {\n $slug = get_term_field( 'slug', $cat_id, 'category' );\n if ( ! is_wp_error( $slug ) && 'testimonials' === $slug ) {\n $link = home_url( user_trailingslashit( '/testimonials/', 'category' ) );\n }\n return $link;\n}\n\nadd_action( 'init', 'custom_rewrite_rules' );\nfunction custom_rewrite_rules() {\n add_rewrite_rule(\n 'testimonials(?:/page/?([0-9]{1,})|)/?$',\n 'index.php?category_name=testimonials&paged=$matches[1]',\n 'top' // The rule position; either 'top' or 'bottom' (default).\n );\n\n add_rewrite_rule(\n 'testimonials/([^/]+)(?:/([0-9]+))?/?$',\n 'index.php?category_name=testimonials&name=$matches[1]&page=$matches[2]',\n 'top' // The rule position; either 'top' or 'bottom' (default).\n );\n}\n</code></pre>\n\n<p><strong>Step #2:</strong> Go to the <em>Permalink Settings</em> page, and click on the <em>Save Changes</em> button without actually making any changes.</p>\n"
},
{
"answer_id": 296722,
"author": "tom",
"author_id": 138544,
"author_profile": "https://wordpress.stackexchange.com/users/138544",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just add the post id then? If that's all you need? You could just do this with <code>query_vars</code></p>\n\n<pre><code>add_filter('query_vars', 'my_query_vars' );\n</code></pre>\n\n<p>You only need to check if you are in the 'special' category and if yes, add the var. Then utilizing the <code>pre_get_posts</code> hook, check if your post contains an ID and if yes change your query to get desired post.</p>\n"
}
]
| 2018/03/13 | [
"https://wordpress.stackexchange.com/questions/296699",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118009/"
]
| For the purposes of my site, I have my Permalinks set to `/blog/%postname%/` for all posts.
However, I need to give Posts with a specific Category (in this case, "Testimonials") its own permalink structure, where each individual post assigned the Category "Testimonials" returns as `/testimonials/%postname%/` and the Category Archive page returns as `/testimonials/`.
Here is the code I have so far:
```
//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 == "Testimonials" ) {
$cat_name = strtolower($category[0]->cat_name);
$permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post->post_name .'/' ) );
}
return $permalink;
}
add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
'testimonials/([^/]+)(?:/([0-9]+))?/?$',
'index.php?category_name=testimonials&name=$matches[1]&page=$matches[2]',
'top' // The rule position; either 'top' or 'bottom' (default).
);
}
```
This successfully returns each individual post with the category "Testimonials" as `/testimonials/%postname%/`. However, the Category Archive page returns as `/blog/category/testimonials`. I need this to just return as `/testimonials/`, while still returning all other Posts as `/blog/%postname%/`
I tried using this plugin, <https://wordpress.org/plugins/custom-permalinks/>, which solved the Category Archive page issue, but broke each individual testimonial post, returning them as a 404 error.
In this case, I cannot register Testimonials as a Custom Post Type as it will affect other site functionality, | Try these steps:
**Step #1:** Replace this:
```
add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
'testimonials/([^/]+)(?:/([0-9]+))?/?$',
'index.php?category_name=testimonials&name=$matches[1]&page=$matches[2]',
'top' // The rule position; either 'top' or 'bottom' (default).
);
}
```
..with this one:
```
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 ) && 'testimonials' === $slug ) {
$link = home_url( user_trailingslashit( '/testimonials/', 'category' ) );
}
return $link;
}
add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
'testimonials(?:/page/?([0-9]{1,})|)/?$',
'index.php?category_name=testimonials&paged=$matches[1]',
'top' // The rule position; either 'top' or 'bottom' (default).
);
add_rewrite_rule(
'testimonials/([^/]+)(?:/([0-9]+))?/?$',
'index.php?category_name=testimonials&name=$matches[1]&page=$matches[2]',
'top' // The rule position; either 'top' or 'bottom' (default).
);
}
```
**Step #2:** Go to the *Permalink Settings* page, and click on the *Save Changes* button without actually making any changes. |
296,716 | <p>I'm developing 'multi category select search form'.
And make it like this</p>
<pre><code><form role="search" action="http://localhost:5757/alpool/" method="get">
<input type="hidden" name="alp-search" value="true">
<div class="ui fluid search dropdown huge selection multiple">
<select name="cat_s[]" multiple="multiple">
<option value=""> Select Category </option>
<option value="358">Apple</option>
<option value="399">Banana</option>
<option value="359">Water</option>
</select>
</div>
<button type="submit" class="ui primary basic button">검색</button>
</form>
</code></pre>
<p>And, when I select 'Apple' and 'Banana' my browser show me this.</p>
<pre><code>http://localhost:5757/alpool/?alp-search=true&cat_s%5B%5D=358&cat_s%5B%5D=399
</code></pre>
<p>My question are these.</p>
<ol>
<li>What is %5B%5D ? </li>
<li><p>How can I change the url like this</p>
<p><code>http://localhost:5757/alpool/?alp-search=true&cat_s=358,399</code></p></li>
</ol>
<p>(should I use javascript? or PHP?)</p>
<p>Thanks.</p>
| [
{
"answer_id": 296719,
"author": "danielh",
"author_id": 110001,
"author_profile": "https://wordpress.stackexchange.com/users/110001",
"pm_score": 0,
"selected": false,
"text": "<p>%5B%5D is urlencoded for <code>[]</code>, as specified with <code>cat_s[]</code>.</p>\n\n<p>If you want it have it submit as comma-separated, I think you'd have to use some JavaScript to modify the submitted result (onsubmit event, modify/add variable that contains comma-separated values).</p>\n\n<p>PHP can also read the array without client-side JavaScript (if you're submitting to a PHP page).</p>\n"
},
{
"answer_id": 296854,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>My question are these.</p>\n \n <ol>\n <li>What is %5B%5D ? </li>\n <li><p>How can I change the url like this</p>\n \n <p><code>http://localhost:5757/alpool/?alp-search=true&cat_s=358,399</code></p></li>\n </ol>\n</blockquote>\n\n<ol>\n<li><p><code>%5B</code> and <code>%5D</code> are <em>percent-encoded</em>/URL-encoded version of the <code>[</code> (left square bracket) and <code>]</code> (right square bracket) characters, respectively. See <a href=\"https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters\" rel=\"nofollow noreferrer\">Percent-encoding reserved characters</a> on Wikipedia.</p></li>\n<li><p>You can \"change\" it using JavaScript, and here's an example of how you can do that without making major changes to the <code>form</code> markup that you currently have:</p>\n\n<ul>\n<li>The only change you need to do is add <code>alp-search-form</code> to the <code>class</code> attribute of the <code>form</code>. The rest can/should remain the same.</li>\n<li>This method works both with and without JavaScript; but of course, without JavaScript, you'll get the \"ugly\" URL having those URL-encoded square brackets.</li>\n</ul></li>\n</ol>\n\n<p><strong>The JS Script</strong></p>\n\n<pre><code>jQuery( function( $ ) {\n $( '.alp-search-form' ).on( 'submit', function( e ) {\n e.preventDefault();\n\n var url = $( this ).attr( 'action' ),\n cat_ids = $( 'select[name=\"cat_s[]\"]', this ).val() || [],\n s = /\\?[a-z0-9]+/i.test( url ) ? '&' : '?';\n\n url += s + 'alp-search=true';\n url += '&cat_s=' + cat_ids.join( ',' );\n\n // \"Submits\" the form.\n //location.href = url; // Uncomment after done testing.\n alert( url ); // Remove this after done testing.\n } );\n} );\n</code></pre>\n\n<p><a href=\"https://jsbin.com/texigecoja/edit?html,js,output\" rel=\"nofollow noreferrer\">Demo on JS Bin</a></p>\n\n<p><strong>Additional Note</strong></p>\n\n<p>In the PHP script/<code>function</code> that processes the form data (or handle the search), you can use this snippet (which uses the <a href=\"https://developer.wordpress.org/reference/functions/wp_parse_id_list/\" rel=\"nofollow noreferrer\"><code>wp_parse_id_list()</code></a> function in WordPress) to grab the selected category IDs:</p>\n\n<pre><code>// This variable will/should always be an array.\n$cat_ids = isset( $_GET['cat_s'] ) ?\n wp_parse_id_list( $_GET['cat_s'] ) : array();\n</code></pre>\n"
}
]
| 2018/03/14 | [
"https://wordpress.stackexchange.com/questions/296716",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136439/"
]
| I'm developing 'multi category select search form'.
And make it like this
```
<form role="search" action="http://localhost:5757/alpool/" method="get">
<input type="hidden" name="alp-search" value="true">
<div class="ui fluid search dropdown huge selection multiple">
<select name="cat_s[]" multiple="multiple">
<option value=""> Select Category </option>
<option value="358">Apple</option>
<option value="399">Banana</option>
<option value="359">Water</option>
</select>
</div>
<button type="submit" class="ui primary basic button">검색</button>
</form>
```
And, when I select 'Apple' and 'Banana' my browser show me this.
```
http://localhost:5757/alpool/?alp-search=true&cat_s%5B%5D=358&cat_s%5B%5D=399
```
My question are these.
1. What is %5B%5D ?
2. How can I change the url like this
`http://localhost:5757/alpool/?alp-search=true&cat_s=358,399`
(should I use javascript? or PHP?)
Thanks. | >
> My question are these.
>
>
> 1. What is %5B%5D ?
> 2. How can I change the url like this
>
>
> `http://localhost:5757/alpool/?alp-search=true&cat_s=358,399`
>
>
>
1. `%5B` and `%5D` are *percent-encoded*/URL-encoded version of the `[` (left square bracket) and `]` (right square bracket) characters, respectively. See [Percent-encoding reserved characters](https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters) on Wikipedia.
2. You can "change" it using JavaScript, and here's an example of how you can do that without making major changes to the `form` markup that you currently have:
* The only change you need to do is add `alp-search-form` to the `class` attribute of the `form`. The rest can/should remain the same.
* This method works both with and without JavaScript; but of course, without JavaScript, you'll get the "ugly" URL having those URL-encoded square brackets.
**The JS Script**
```
jQuery( function( $ ) {
$( '.alp-search-form' ).on( 'submit', function( e ) {
e.preventDefault();
var url = $( this ).attr( 'action' ),
cat_ids = $( 'select[name="cat_s[]"]', this ).val() || [],
s = /\?[a-z0-9]+/i.test( url ) ? '&' : '?';
url += s + 'alp-search=true';
url += '&cat_s=' + cat_ids.join( ',' );
// "Submits" the form.
//location.href = url; // Uncomment after done testing.
alert( url ); // Remove this after done testing.
} );
} );
```
[Demo on JS Bin](https://jsbin.com/texigecoja/edit?html,js,output)
**Additional Note**
In the PHP script/`function` that processes the form data (or handle the search), you can use this snippet (which uses the [`wp_parse_id_list()`](https://developer.wordpress.org/reference/functions/wp_parse_id_list/) function in WordPress) to grab the selected category IDs:
```
// This variable will/should always be an array.
$cat_ids = isset( $_GET['cat_s'] ) ?
wp_parse_id_list( $_GET['cat_s'] ) : array();
``` |
296,726 | <p>I want to set margin-bottom:10px for article in <a href="http://104.223.65.117/wp/?s=emmet" rel="nofollow noreferrer">http://104.223.65.117/wp/?s=emmet</a>.</p>
<p>Method 1:</p>
<p>sudo cat /var/www/html/wp/wp-content/themes/twentyfourteen-child/style.css</p>
<pre><code>*{
font-family:"DejaVu Sans Mono" !important;
}
.site {
max-width: 1920px;
}
.site::before{
width:400px;
}
.site-header {
max-width: 1920px;
}
.site-content header .entry-meta {
max-width: 100%;
}
.site-content .entry-header,
.site-content .entry-content,
.site-content .entry-summary,
.site-content .entry-meta,
.site-content .navigation,
.comments-area,
.page-header,
.page-content {
max-width: 70%;
}
#secondary ul li{
color:black;
width:360px;
font-size:16px;
}
.entry-meta .cat-links{
display:none;
}
pre{
font-family:inherit;
font-size:16px;
border:1px solid red;
}
article{
margin-bottom:10px;
}
</code></pre>
<p>I have added the margin-bottom for artilce at the end of twentyfourteen-child/style.css file.</p>
<pre><code>article{
margin-bottom:10px;
}
</code></pre>
<p>Method 2:
In the Customizing--Additional CSS</p>
<p><a href="https://i.stack.imgur.com/CDtVv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CDtVv.png" alt="enter image description here"></a></p>
<p>For both of them ,<code>sudo service apache2 restart</code>, it take no effect.</p>
<p><a href="https://i.stack.imgur.com/0N5XK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0N5XK.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 296719,
"author": "danielh",
"author_id": 110001,
"author_profile": "https://wordpress.stackexchange.com/users/110001",
"pm_score": 0,
"selected": false,
"text": "<p>%5B%5D is urlencoded for <code>[]</code>, as specified with <code>cat_s[]</code>.</p>\n\n<p>If you want it have it submit as comma-separated, I think you'd have to use some JavaScript to modify the submitted result (onsubmit event, modify/add variable that contains comma-separated values).</p>\n\n<p>PHP can also read the array without client-side JavaScript (if you're submitting to a PHP page).</p>\n"
},
{
"answer_id": 296854,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>My question are these.</p>\n \n <ol>\n <li>What is %5B%5D ? </li>\n <li><p>How can I change the url like this</p>\n \n <p><code>http://localhost:5757/alpool/?alp-search=true&cat_s=358,399</code></p></li>\n </ol>\n</blockquote>\n\n<ol>\n<li><p><code>%5B</code> and <code>%5D</code> are <em>percent-encoded</em>/URL-encoded version of the <code>[</code> (left square bracket) and <code>]</code> (right square bracket) characters, respectively. See <a href=\"https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters\" rel=\"nofollow noreferrer\">Percent-encoding reserved characters</a> on Wikipedia.</p></li>\n<li><p>You can \"change\" it using JavaScript, and here's an example of how you can do that without making major changes to the <code>form</code> markup that you currently have:</p>\n\n<ul>\n<li>The only change you need to do is add <code>alp-search-form</code> to the <code>class</code> attribute of the <code>form</code>. The rest can/should remain the same.</li>\n<li>This method works both with and without JavaScript; but of course, without JavaScript, you'll get the \"ugly\" URL having those URL-encoded square brackets.</li>\n</ul></li>\n</ol>\n\n<p><strong>The JS Script</strong></p>\n\n<pre><code>jQuery( function( $ ) {\n $( '.alp-search-form' ).on( 'submit', function( e ) {\n e.preventDefault();\n\n var url = $( this ).attr( 'action' ),\n cat_ids = $( 'select[name=\"cat_s[]\"]', this ).val() || [],\n s = /\\?[a-z0-9]+/i.test( url ) ? '&' : '?';\n\n url += s + 'alp-search=true';\n url += '&cat_s=' + cat_ids.join( ',' );\n\n // \"Submits\" the form.\n //location.href = url; // Uncomment after done testing.\n alert( url ); // Remove this after done testing.\n } );\n} );\n</code></pre>\n\n<p><a href=\"https://jsbin.com/texigecoja/edit?html,js,output\" rel=\"nofollow noreferrer\">Demo on JS Bin</a></p>\n\n<p><strong>Additional Note</strong></p>\n\n<p>In the PHP script/<code>function</code> that processes the form data (or handle the search), you can use this snippet (which uses the <a href=\"https://developer.wordpress.org/reference/functions/wp_parse_id_list/\" rel=\"nofollow noreferrer\"><code>wp_parse_id_list()</code></a> function in WordPress) to grab the selected category IDs:</p>\n\n<pre><code>// This variable will/should always be an array.\n$cat_ids = isset( $_GET['cat_s'] ) ?\n wp_parse_id_list( $_GET['cat_s'] ) : array();\n</code></pre>\n"
}
]
| 2018/03/14 | [
"https://wordpress.stackexchange.com/questions/296726",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119358/"
]
| I want to set margin-bottom:10px for article in <http://104.223.65.117/wp/?s=emmet>.
Method 1:
sudo cat /var/www/html/wp/wp-content/themes/twentyfourteen-child/style.css
```
*{
font-family:"DejaVu Sans Mono" !important;
}
.site {
max-width: 1920px;
}
.site::before{
width:400px;
}
.site-header {
max-width: 1920px;
}
.site-content header .entry-meta {
max-width: 100%;
}
.site-content .entry-header,
.site-content .entry-content,
.site-content .entry-summary,
.site-content .entry-meta,
.site-content .navigation,
.comments-area,
.page-header,
.page-content {
max-width: 70%;
}
#secondary ul li{
color:black;
width:360px;
font-size:16px;
}
.entry-meta .cat-links{
display:none;
}
pre{
font-family:inherit;
font-size:16px;
border:1px solid red;
}
article{
margin-bottom:10px;
}
```
I have added the margin-bottom for artilce at the end of twentyfourteen-child/style.css file.
```
article{
margin-bottom:10px;
}
```
Method 2:
In the Customizing--Additional CSS
[](https://i.stack.imgur.com/CDtVv.png)
For both of them ,`sudo service apache2 restart`, it take no effect.
[](https://i.stack.imgur.com/0N5XK.png) | >
> My question are these.
>
>
> 1. What is %5B%5D ?
> 2. How can I change the url like this
>
>
> `http://localhost:5757/alpool/?alp-search=true&cat_s=358,399`
>
>
>
1. `%5B` and `%5D` are *percent-encoded*/URL-encoded version of the `[` (left square bracket) and `]` (right square bracket) characters, respectively. See [Percent-encoding reserved characters](https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters) on Wikipedia.
2. You can "change" it using JavaScript, and here's an example of how you can do that without making major changes to the `form` markup that you currently have:
* The only change you need to do is add `alp-search-form` to the `class` attribute of the `form`. The rest can/should remain the same.
* This method works both with and without JavaScript; but of course, without JavaScript, you'll get the "ugly" URL having those URL-encoded square brackets.
**The JS Script**
```
jQuery( function( $ ) {
$( '.alp-search-form' ).on( 'submit', function( e ) {
e.preventDefault();
var url = $( this ).attr( 'action' ),
cat_ids = $( 'select[name="cat_s[]"]', this ).val() || [],
s = /\?[a-z0-9]+/i.test( url ) ? '&' : '?';
url += s + 'alp-search=true';
url += '&cat_s=' + cat_ids.join( ',' );
// "Submits" the form.
//location.href = url; // Uncomment after done testing.
alert( url ); // Remove this after done testing.
} );
} );
```
[Demo on JS Bin](https://jsbin.com/texigecoja/edit?html,js,output)
**Additional Note**
In the PHP script/`function` that processes the form data (or handle the search), you can use this snippet (which uses the [`wp_parse_id_list()`](https://developer.wordpress.org/reference/functions/wp_parse_id_list/) function in WordPress) to grab the selected category IDs:
```
// This variable will/should always be an array.
$cat_ids = isset( $_GET['cat_s'] ) ?
wp_parse_id_list( $_GET['cat_s'] ) : array();
``` |
296,727 | <p>I'm not talking about subdomain/subfolder. I am talking about moving my whole Wordpress Multisite installation to example.com/ms/. And keeping the root for another non-multisite install of wordpress.
I tried creating a folder /ms/ in the root. Moved everything there. Went to wp-config, changed to define('DOMAIN_CURRENT_SITE', 'example.com/ms');
Then went to phpmyadmin and changed every setting that had example.com to example.com/ms.</p>
<p>Still can't make it work?</p>
<p>How do I do a successful move?</p>
| [
{
"answer_id": 296719,
"author": "danielh",
"author_id": 110001,
"author_profile": "https://wordpress.stackexchange.com/users/110001",
"pm_score": 0,
"selected": false,
"text": "<p>%5B%5D is urlencoded for <code>[]</code>, as specified with <code>cat_s[]</code>.</p>\n\n<p>If you want it have it submit as comma-separated, I think you'd have to use some JavaScript to modify the submitted result (onsubmit event, modify/add variable that contains comma-separated values).</p>\n\n<p>PHP can also read the array without client-side JavaScript (if you're submitting to a PHP page).</p>\n"
},
{
"answer_id": 296854,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>My question are these.</p>\n \n <ol>\n <li>What is %5B%5D ? </li>\n <li><p>How can I change the url like this</p>\n \n <p><code>http://localhost:5757/alpool/?alp-search=true&cat_s=358,399</code></p></li>\n </ol>\n</blockquote>\n\n<ol>\n<li><p><code>%5B</code> and <code>%5D</code> are <em>percent-encoded</em>/URL-encoded version of the <code>[</code> (left square bracket) and <code>]</code> (right square bracket) characters, respectively. See <a href=\"https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters\" rel=\"nofollow noreferrer\">Percent-encoding reserved characters</a> on Wikipedia.</p></li>\n<li><p>You can \"change\" it using JavaScript, and here's an example of how you can do that without making major changes to the <code>form</code> markup that you currently have:</p>\n\n<ul>\n<li>The only change you need to do is add <code>alp-search-form</code> to the <code>class</code> attribute of the <code>form</code>. The rest can/should remain the same.</li>\n<li>This method works both with and without JavaScript; but of course, without JavaScript, you'll get the \"ugly\" URL having those URL-encoded square brackets.</li>\n</ul></li>\n</ol>\n\n<p><strong>The JS Script</strong></p>\n\n<pre><code>jQuery( function( $ ) {\n $( '.alp-search-form' ).on( 'submit', function( e ) {\n e.preventDefault();\n\n var url = $( this ).attr( 'action' ),\n cat_ids = $( 'select[name=\"cat_s[]\"]', this ).val() || [],\n s = /\\?[a-z0-9]+/i.test( url ) ? '&' : '?';\n\n url += s + 'alp-search=true';\n url += '&cat_s=' + cat_ids.join( ',' );\n\n // \"Submits\" the form.\n //location.href = url; // Uncomment after done testing.\n alert( url ); // Remove this after done testing.\n } );\n} );\n</code></pre>\n\n<p><a href=\"https://jsbin.com/texigecoja/edit?html,js,output\" rel=\"nofollow noreferrer\">Demo on JS Bin</a></p>\n\n<p><strong>Additional Note</strong></p>\n\n<p>In the PHP script/<code>function</code> that processes the form data (or handle the search), you can use this snippet (which uses the <a href=\"https://developer.wordpress.org/reference/functions/wp_parse_id_list/\" rel=\"nofollow noreferrer\"><code>wp_parse_id_list()</code></a> function in WordPress) to grab the selected category IDs:</p>\n\n<pre><code>// This variable will/should always be an array.\n$cat_ids = isset( $_GET['cat_s'] ) ?\n wp_parse_id_list( $_GET['cat_s'] ) : array();\n</code></pre>\n"
}
]
| 2018/03/14 | [
"https://wordpress.stackexchange.com/questions/296727",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138051/"
]
| I'm not talking about subdomain/subfolder. I am talking about moving my whole Wordpress Multisite installation to example.com/ms/. And keeping the root for another non-multisite install of wordpress.
I tried creating a folder /ms/ in the root. Moved everything there. Went to wp-config, changed to define('DOMAIN\_CURRENT\_SITE', 'example.com/ms');
Then went to phpmyadmin and changed every setting that had example.com to example.com/ms.
Still can't make it work?
How do I do a successful move? | >
> My question are these.
>
>
> 1. What is %5B%5D ?
> 2. How can I change the url like this
>
>
> `http://localhost:5757/alpool/?alp-search=true&cat_s=358,399`
>
>
>
1. `%5B` and `%5D` are *percent-encoded*/URL-encoded version of the `[` (left square bracket) and `]` (right square bracket) characters, respectively. See [Percent-encoding reserved characters](https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters) on Wikipedia.
2. You can "change" it using JavaScript, and here's an example of how you can do that without making major changes to the `form` markup that you currently have:
* The only change you need to do is add `alp-search-form` to the `class` attribute of the `form`. The rest can/should remain the same.
* This method works both with and without JavaScript; but of course, without JavaScript, you'll get the "ugly" URL having those URL-encoded square brackets.
**The JS Script**
```
jQuery( function( $ ) {
$( '.alp-search-form' ).on( 'submit', function( e ) {
e.preventDefault();
var url = $( this ).attr( 'action' ),
cat_ids = $( 'select[name="cat_s[]"]', this ).val() || [],
s = /\?[a-z0-9]+/i.test( url ) ? '&' : '?';
url += s + 'alp-search=true';
url += '&cat_s=' + cat_ids.join( ',' );
// "Submits" the form.
//location.href = url; // Uncomment after done testing.
alert( url ); // Remove this after done testing.
} );
} );
```
[Demo on JS Bin](https://jsbin.com/texigecoja/edit?html,js,output)
**Additional Note**
In the PHP script/`function` that processes the form data (or handle the search), you can use this snippet (which uses the [`wp_parse_id_list()`](https://developer.wordpress.org/reference/functions/wp_parse_id_list/) function in WordPress) to grab the selected category IDs:
```
// This variable will/should always be an array.
$cat_ids = isset( $_GET['cat_s'] ) ?
wp_parse_id_list( $_GET['cat_s'] ) : array();
``` |
296,775 | <p>Basically, I'm trying to override some files of the Uncode theme. But this is not a theme-specific question: it can be applied to any theme. The Uncode theme has a custom dir <code>'partials'</code> (<code>/uncode/partials/</code>) that contains some layout elements. On my child theme I created a 'partials' folder as well (<code>my-child-theme/partials</code>), but the inner files seem not to be overridden. Is it normal? WP docs say that any file of the same name should be overridable, but is seems that's not true. Am I doing something wrong?</p>
| [
{
"answer_id": 296791,
"author": "weston deboer",
"author_id": 8926,
"author_profile": "https://wordpress.stackexchange.com/users/8926",
"pm_score": 0,
"selected": false,
"text": "<p>That is a very good question, the theme directory can be quite confusing sometimes. </p>\n\n<p>The answer is No, WordPress only looks at core theme files. Since a sub directory isn't part of this it will not look for sub folders in your child theme. What you can do is include the file that includes the partials folder, and that will include your custom partials folder in your child theme. </p>\n"
},
{
"answer_id": 296845,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>It depends entirely on the parent theme. While WordPress will check the child theme for templates in the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">Template Hierarchy</a> and use those if they are present, it's up to theme authors to decide how much overwriting by child themes they want to support for any other files outside this hierarchy.</p>\n\n<p>For example, when including template parts the theme author could use:</p>\n\n<pre><code>require 'partials/partial.php';\n</code></pre>\n\n<p>And this would work fine, but if the theme author wanted to support child theming they would use:</p>\n\n<pre><code>get_template_part( 'partials/partial' );\n</code></pre>\n\n<p>This is because <code>get_template_part()</code> will check the child theme for <code>partials/partial.php</code> and use that if it exists, otherwise it will fall back to the parent theme's copy of <code>partials/partial.php</code>.</p>\n\n<p>Since 4.7.0, WordPress has added several functions that allow theme authors to support child theming for other files.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_theme_file_uri()</code></a> will return a URL for a file in the child theme if it exists, otherwise it will use the parent themes'. This allows themes to support replacing CSS and JS files in child themes. </p>\n\n<p>For example, if the parent theme enqueues a stylesheet like this:</p>\n\n<pre><code>wp_enqueue_style( 'custom-style', get_theme_file_uri( 'assets/custom.css' ) );\n</code></pre>\n\n<p>Then a child theme author can replace that stylesheet by just placing <code>assets/custom.css</code> in their child theme.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"nofollow noreferrer\"><code>get_theme_file_path()</code></a> will return the <em>path</em> for a file in the child theme if it exists, otherwise it will use the parent themes'. This can be used by parent themes to allow child themes to replace entire included PHP files.</p>\n\n<p>For example, if the parent theme included a PHP file like this:</p>\n\n<pre><code>include get_theme_file_path( 'inc/template-tags.php' );\n</code></pre>\n\n<p>Then a child theme author could replace <code>template-tags.php</code> by just placing <code>inc/template-tags.php</code> in their child theme.</p>\n\n<p>So the takeaway here is that WordPress <em>does</em> support child themes replacing arbitrary files from their parent theme, but the parent theme author needs to explicitly support it by using the correct functions.</p>\n\n<p>Uncode is a paid theme, so I can't see the code, but I suspect it's not using <code>get_template_part()</code>, which is why you can't replace the files in your child theme. Paid themes are often not good 'WordPress citizens' and have pretty spotty support for functionality like this.</p>\n"
}
]
| 2018/03/14 | [
"https://wordpress.stackexchange.com/questions/296775",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
]
| Basically, I'm trying to override some files of the Uncode theme. But this is not a theme-specific question: it can be applied to any theme. The Uncode theme has a custom dir `'partials'` (`/uncode/partials/`) that contains some layout elements. On my child theme I created a 'partials' folder as well (`my-child-theme/partials`), but the inner files seem not to be overridden. Is it normal? WP docs say that any file of the same name should be overridable, but is seems that's not true. Am I doing something wrong? | It depends entirely on the parent theme. While WordPress will check the child theme for templates in the [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) and use those if they are present, it's up to theme authors to decide how much overwriting by child themes they want to support for any other files outside this hierarchy.
For example, when including template parts the theme author could use:
```
require 'partials/partial.php';
```
And this would work fine, but if the theme author wanted to support child theming they would use:
```
get_template_part( 'partials/partial' );
```
This is because `get_template_part()` will check the child theme for `partials/partial.php` and use that if it exists, otherwise it will fall back to the parent theme's copy of `partials/partial.php`.
Since 4.7.0, WordPress has added several functions that allow theme authors to support child theming for other files.
[`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/) will return a URL for a file in the child theme if it exists, otherwise it will use the parent themes'. This allows themes to support replacing CSS and JS files in child themes.
For example, if the parent theme enqueues a stylesheet like this:
```
wp_enqueue_style( 'custom-style', get_theme_file_uri( 'assets/custom.css' ) );
```
Then a child theme author can replace that stylesheet by just placing `assets/custom.css` in their child theme.
[`get_theme_file_path()`](https://developer.wordpress.org/reference/functions/get_theme_file_path/) will return the *path* for a file in the child theme if it exists, otherwise it will use the parent themes'. This can be used by parent themes to allow child themes to replace entire included PHP files.
For example, if the parent theme included a PHP file like this:
```
include get_theme_file_path( 'inc/template-tags.php' );
```
Then a child theme author could replace `template-tags.php` by just placing `inc/template-tags.php` in their child theme.
So the takeaway here is that WordPress *does* support child themes replacing arbitrary files from their parent theme, but the parent theme author needs to explicitly support it by using the correct functions.
Uncode is a paid theme, so I can't see the code, but I suspect it's not using `get_template_part()`, which is why you can't replace the files in your child theme. Paid themes are often not good 'WordPress citizens' and have pretty spotty support for functionality like this. |
296,778 | <p>So I'm working on a medical site that has a custom post type "doctors". Within this post type are custom taxonomies for "locations" and "procedures". I've created a custom taxonomy-locations.php file to control how my locations pages look, on this page is some general information like contact info, maps, related doctors. I also need to include a list of all procedures offered at each location. Since procedures are attached to each doctor, not to each location, I created a function containing a loop to run through all doctors tagged at the current location and output a comma separated list of all tagged procedures term ids. See below: </p>
<pre><code>// Get the doctors procedures
function location_doctors_procedure_loop() {
$tax_slug = get_query_var( 'locations' );
$args = array(
'posts_per_page' => -1,
'order' => 'DESC',
'post_type' => 'our_team',
'locations' => $tax_slug
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$terms = get_the_terms( $post, 'procedures' );
if ( !empty($terms) ) {
foreach( $terms as $term ) {
echo $term->term_id . ',';
}
}
}
wp_reset_postdata();
}
}
</code></pre>
<p>I then created a function that loops through all active procedure taxonomies and lists them hierarchically as parent, child, grandparent. See below:</p>
<pre><code>// Get the procedures
function tax_location_procedures() {
$doctor_procedures = location_doctors_procedure_loop();
$terms = get_terms( array(
'taxonomy' => 'procedures',
'hide_empty' => true,
'include' => array( $doctor_procedures ),
) );
echo '<h2 class="doctor-bio-procedure-condition-header">Procedures</h2>';
if ( !empty($terms) ) {
echo '<div class="doctor-bio-procedures">';
foreach( $terms as $term ) {
if( $term->parent == 0 ) {
?>
<p class="doctor-bio-procedure-condition-sub-header"><?php echo $term->name; ?></p>
<?php
echo '<ul>';
foreach( $terms as $childterm ) {
if($childterm->parent == $term->term_id) {
echo '<li>' . $childterm->name . '</li>';
echo '<ul>';
foreach( $terms as $grandchildterm ) {
if($grandchildterm->parent == $childterm->term_id) {
echo '<li>' . $grandchildterm->name . '</li>';
}
}
echo '</ul>';
}
}
echo '</ul>';
}
}
echo '</div>';
}
}
</code></pre>
<p>What I'm trying to do is use my first function "location_doctors_procedure_loop()" to populated the 'include' arguments array in "function tax_location_procedures()". The problem I'm having is that while "location_doctors_procedure_loop()" does echo out a comma separated list of the correct term IDs (e.g 231,229,) it does nothing for my 'include" argument because its echoing as a string rather than integers, so it's reading as</p>
<pre><code>'include' => array('231,229,')
</code></pre>
<p>rather than</p>
<pre><code>'include' => array(231,229,)
</code></pre>
<p>I'm stuck on this and have already spent the better part of a day trying to get this to work properly. Any help you guys can provide would be greatly appreciated.</p>
| [
{
"answer_id": 296781,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to change these lines</p>\n\n<pre><code>if ( !empty($terms) ) {\n foreach( $terms as $term ) {\n echo $term->term_id . ','; \n }\n\n}\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>if ( !empty($terms) ) {\n // create an empty array\n $procedures_to_include = array();\n foreach( $terms as $term ) {\n // now instead of echoing, add each term to the array\n $procedures_to_include[] = $term->term_id;\n }\n\n}\n</code></pre>\n\n<p>Basically instead of echoing manually, you're creating the array to begin with, and in your <code>get_terms</code> call you can just use <code>$procedures_to_include</code> directly:</p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' => 'procedures',\n 'hide_empty' => true,\n 'include' => $procedures_to_include\n) );\n</code></pre>\n"
},
{
"answer_id": 296782,
"author": "Stender",
"author_id": 82677,
"author_profile": "https://wordpress.stackexchange.com/users/82677",
"pm_score": 0,
"selected": false,
"text": "<p>Turn your comma seperated string into an array like this : </p>\n\n<pre><code>$inclusionArray = explode(',', $doctor_procedures);\n</code></pre>\n\n<p>Then use that array.</p>\n\n<pre><code>'include' => $inclusionArray\n</code></pre>\n"
},
{
"answer_id": 296784,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>So there's a few things you need to do in <code>location_doctors_procedure_loop()</code> for this to work:</p>\n\n<ol>\n<li>Have the function <em>return</em> values, rather than echo them. If you need to assign the output of the function to a variable, or use it as an argument, it needs to be returned. <code>echo</code> outputs the values to the screen, which you don't want.</li>\n<li>To do this you'll need to build up an array of values within the loop. Do this by creating an empty array at the beginning, then adding procedures to it in the loop before ultimately returning the array.</li>\n<li>Probably not required, but it might be a good idea to strip out duplicates from the array.</li>\n</ol>\n\n<p>But you can go further. All you're doing with these IDs is retrieving the terms. Why not just pass the full terms all the way through, thus avoiding the need to call <code>get_terms()</code> at all. You can avoid duplicates by using the term ID as the key of the array.</p>\n\n<p>Here's a version of your function with this all applied:</p>\n\n<pre><code>function location_doctors_procedure_loop() {\n /**\n * Create the array to return at the end.\n */\n $procedures = array();\n\n /**\n * Get all doctors for the current location.\n * We're not using template tags, so a custom WP_Query is unnecessary.\n */\n $doctors = get_posts( array(\n 'posts_per_page' => -1,\n 'order' => 'DESC',\n 'post_type' => 'our_team',\n 'locations' => get_query_var( 'locations' )\n ) );\n\n /**\n * Loop through each doctor and add its procedures' to the array.\n * If a term is added a second time, it will just replace the original \n * because the key is the ID.\n */\n foreach ( $doctors as $doctor ) {\n $terms = get_the_terms( $doctor, 'procedures' );\n\n if ( ! empty( $terms ) ) {\n foreach( $terms as $term ) {\n $procedures[$term->term_id] = $term;\n }\n }\n }\n\n /**\n * Return the array.\n */\n return $procedures;\n}\n</code></pre>\n\n<p>Now in your <code>tax_location_procedures()</code> function you can just pass this directly to <code>$terms</code>:</p>\n\n<pre><code>$terms = location_doctors_procedure_loop();\n</code></pre>\n"
},
{
"answer_id": 296787,
"author": "Arpita Hunka",
"author_id": 86864,
"author_profile": "https://wordpress.stackexchange.com/users/86864",
"pm_score": 0,
"selected": false,
"text": "<p>You need to convert values into an integer array because you are getting string in this </p>\n\n<pre><code>$doctor_procedures = location_doctors_procedure_loop();\n</code></pre>\n\n<p>variable. You can convert it by using following option : </p>\n\n<pre><code>$doctor_procedures_int_val = array_map('intval', explode(',', $doctor_procedures));\n</code></pre>\n\n<p>after this you need to pass this new array variable in \"include\" index.</p>\n\n<p>so currently you are getting</p>\n\n<pre><code>'include' => array('231,229,')\n</code></pre>\n\n<p>by using <code>array_map('intval', explode(',', '231,229,'))</code> this you will get <code>array(231,229,)</code> </p>\n\n<p>So need to update your function with this :</p>\n\n<pre><code>$doctor_procedures = location_doctors_procedure_loop();\n$doctor_procedures_int_val = array_map('intval', explode(',', $doctor_procedures));\n$terms = get_terms( array(\n 'taxonomy' => 'procedures',\n 'hide_empty' => true,\n 'include' => array( $doctor_procedures_int_val ),\n ) );\n</code></pre>\n\n<p>Or you can make changes in your first function as well. Instead of doing echo the ids, you can put them in an array. then you do not need to do the above steps.</p>\n\n<p>Let me know, if you need any more clarification.</p>\n"
}
]
| 2018/03/14 | [
"https://wordpress.stackexchange.com/questions/296778",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138635/"
]
| So I'm working on a medical site that has a custom post type "doctors". Within this post type are custom taxonomies for "locations" and "procedures". I've created a custom taxonomy-locations.php file to control how my locations pages look, on this page is some general information like contact info, maps, related doctors. I also need to include a list of all procedures offered at each location. Since procedures are attached to each doctor, not to each location, I created a function containing a loop to run through all doctors tagged at the current location and output a comma separated list of all tagged procedures term ids. See below:
```
// Get the doctors procedures
function location_doctors_procedure_loop() {
$tax_slug = get_query_var( 'locations' );
$args = array(
'posts_per_page' => -1,
'order' => 'DESC',
'post_type' => 'our_team',
'locations' => $tax_slug
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$terms = get_the_terms( $post, 'procedures' );
if ( !empty($terms) ) {
foreach( $terms as $term ) {
echo $term->term_id . ',';
}
}
}
wp_reset_postdata();
}
}
```
I then created a function that loops through all active procedure taxonomies and lists them hierarchically as parent, child, grandparent. See below:
```
// Get the procedures
function tax_location_procedures() {
$doctor_procedures = location_doctors_procedure_loop();
$terms = get_terms( array(
'taxonomy' => 'procedures',
'hide_empty' => true,
'include' => array( $doctor_procedures ),
) );
echo '<h2 class="doctor-bio-procedure-condition-header">Procedures</h2>';
if ( !empty($terms) ) {
echo '<div class="doctor-bio-procedures">';
foreach( $terms as $term ) {
if( $term->parent == 0 ) {
?>
<p class="doctor-bio-procedure-condition-sub-header"><?php echo $term->name; ?></p>
<?php
echo '<ul>';
foreach( $terms as $childterm ) {
if($childterm->parent == $term->term_id) {
echo '<li>' . $childterm->name . '</li>';
echo '<ul>';
foreach( $terms as $grandchildterm ) {
if($grandchildterm->parent == $childterm->term_id) {
echo '<li>' . $grandchildterm->name . '</li>';
}
}
echo '</ul>';
}
}
echo '</ul>';
}
}
echo '</div>';
}
}
```
What I'm trying to do is use my first function "location\_doctors\_procedure\_loop()" to populated the 'include' arguments array in "function tax\_location\_procedures()". The problem I'm having is that while "location\_doctors\_procedure\_loop()" does echo out a comma separated list of the correct term IDs (e.g 231,229,) it does nothing for my 'include" argument because its echoing as a string rather than integers, so it's reading as
```
'include' => array('231,229,')
```
rather than
```
'include' => array(231,229,)
```
I'm stuck on this and have already spent the better part of a day trying to get this to work properly. Any help you guys can provide would be greatly appreciated. | You should be able to change these lines
```
if ( !empty($terms) ) {
foreach( $terms as $term ) {
echo $term->term_id . ',';
}
}
```
to this:
```
if ( !empty($terms) ) {
// create an empty array
$procedures_to_include = array();
foreach( $terms as $term ) {
// now instead of echoing, add each term to the array
$procedures_to_include[] = $term->term_id;
}
}
```
Basically instead of echoing manually, you're creating the array to begin with, and in your `get_terms` call you can just use `$procedures_to_include` directly:
```
$terms = get_terms( array(
'taxonomy' => 'procedures',
'hide_empty' => true,
'include' => $procedures_to_include
) );
``` |
296,780 | <p><strong>I have this situation:</strong></p>
<ol>
<li>I activated Multisite mode to develop the main website in a secondary site with subdomain "beta";</li>
</ol>
<blockquote>
<p>EX: www.mysite.com, beta.mysite.com</p>
</blockquote>
<ol start="2">
<li><p>I duplicated the default theme with "beta" suffix, but it is not set as a child theme;</p></li>
<li><p>every site has applied with the own respective theme.</p></li>
</ol>
<blockquote>
<p>EX: <em>mysite-theme</em> for www.mysite.com, <em>mysite-beta</em> for beta.mysite.com</p>
</blockquote>
<p><strong>The problem is:</strong> when I visit the beta site, php files are loaded from <em>mysite-beta</em> as expected, but the css files are loaded from <em>mysite-theme</em>.</p>
<p>Why does happen this with Wordpress? How can solve this situation?</p>
| [
{
"answer_id": 296781,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to change these lines</p>\n\n<pre><code>if ( !empty($terms) ) {\n foreach( $terms as $term ) {\n echo $term->term_id . ','; \n }\n\n}\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>if ( !empty($terms) ) {\n // create an empty array\n $procedures_to_include = array();\n foreach( $terms as $term ) {\n // now instead of echoing, add each term to the array\n $procedures_to_include[] = $term->term_id;\n }\n\n}\n</code></pre>\n\n<p>Basically instead of echoing manually, you're creating the array to begin with, and in your <code>get_terms</code> call you can just use <code>$procedures_to_include</code> directly:</p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' => 'procedures',\n 'hide_empty' => true,\n 'include' => $procedures_to_include\n) );\n</code></pre>\n"
},
{
"answer_id": 296782,
"author": "Stender",
"author_id": 82677,
"author_profile": "https://wordpress.stackexchange.com/users/82677",
"pm_score": 0,
"selected": false,
"text": "<p>Turn your comma seperated string into an array like this : </p>\n\n<pre><code>$inclusionArray = explode(',', $doctor_procedures);\n</code></pre>\n\n<p>Then use that array.</p>\n\n<pre><code>'include' => $inclusionArray\n</code></pre>\n"
},
{
"answer_id": 296784,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>So there's a few things you need to do in <code>location_doctors_procedure_loop()</code> for this to work:</p>\n\n<ol>\n<li>Have the function <em>return</em> values, rather than echo them. If you need to assign the output of the function to a variable, or use it as an argument, it needs to be returned. <code>echo</code> outputs the values to the screen, which you don't want.</li>\n<li>To do this you'll need to build up an array of values within the loop. Do this by creating an empty array at the beginning, then adding procedures to it in the loop before ultimately returning the array.</li>\n<li>Probably not required, but it might be a good idea to strip out duplicates from the array.</li>\n</ol>\n\n<p>But you can go further. All you're doing with these IDs is retrieving the terms. Why not just pass the full terms all the way through, thus avoiding the need to call <code>get_terms()</code> at all. You can avoid duplicates by using the term ID as the key of the array.</p>\n\n<p>Here's a version of your function with this all applied:</p>\n\n<pre><code>function location_doctors_procedure_loop() {\n /**\n * Create the array to return at the end.\n */\n $procedures = array();\n\n /**\n * Get all doctors for the current location.\n * We're not using template tags, so a custom WP_Query is unnecessary.\n */\n $doctors = get_posts( array(\n 'posts_per_page' => -1,\n 'order' => 'DESC',\n 'post_type' => 'our_team',\n 'locations' => get_query_var( 'locations' )\n ) );\n\n /**\n * Loop through each doctor and add its procedures' to the array.\n * If a term is added a second time, it will just replace the original \n * because the key is the ID.\n */\n foreach ( $doctors as $doctor ) {\n $terms = get_the_terms( $doctor, 'procedures' );\n\n if ( ! empty( $terms ) ) {\n foreach( $terms as $term ) {\n $procedures[$term->term_id] = $term;\n }\n }\n }\n\n /**\n * Return the array.\n */\n return $procedures;\n}\n</code></pre>\n\n<p>Now in your <code>tax_location_procedures()</code> function you can just pass this directly to <code>$terms</code>:</p>\n\n<pre><code>$terms = location_doctors_procedure_loop();\n</code></pre>\n"
},
{
"answer_id": 296787,
"author": "Arpita Hunka",
"author_id": 86864,
"author_profile": "https://wordpress.stackexchange.com/users/86864",
"pm_score": 0,
"selected": false,
"text": "<p>You need to convert values into an integer array because you are getting string in this </p>\n\n<pre><code>$doctor_procedures = location_doctors_procedure_loop();\n</code></pre>\n\n<p>variable. You can convert it by using following option : </p>\n\n<pre><code>$doctor_procedures_int_val = array_map('intval', explode(',', $doctor_procedures));\n</code></pre>\n\n<p>after this you need to pass this new array variable in \"include\" index.</p>\n\n<p>so currently you are getting</p>\n\n<pre><code>'include' => array('231,229,')\n</code></pre>\n\n<p>by using <code>array_map('intval', explode(',', '231,229,'))</code> this you will get <code>array(231,229,)</code> </p>\n\n<p>So need to update your function with this :</p>\n\n<pre><code>$doctor_procedures = location_doctors_procedure_loop();\n$doctor_procedures_int_val = array_map('intval', explode(',', $doctor_procedures));\n$terms = get_terms( array(\n 'taxonomy' => 'procedures',\n 'hide_empty' => true,\n 'include' => array( $doctor_procedures_int_val ),\n ) );\n</code></pre>\n\n<p>Or you can make changes in your first function as well. Instead of doing echo the ids, you can put them in an array. then you do not need to do the above steps.</p>\n\n<p>Let me know, if you need any more clarification.</p>\n"
}
]
| 2018/03/14 | [
"https://wordpress.stackexchange.com/questions/296780",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136313/"
]
| **I have this situation:**
1. I activated Multisite mode to develop the main website in a secondary site with subdomain "beta";
>
> EX: www.mysite.com, beta.mysite.com
>
>
>
2. I duplicated the default theme with "beta" suffix, but it is not set as a child theme;
3. every site has applied with the own respective theme.
>
> EX: *mysite-theme* for www.mysite.com, *mysite-beta* for beta.mysite.com
>
>
>
**The problem is:** when I visit the beta site, php files are loaded from *mysite-beta* as expected, but the css files are loaded from *mysite-theme*.
Why does happen this with Wordpress? How can solve this situation? | You should be able to change these lines
```
if ( !empty($terms) ) {
foreach( $terms as $term ) {
echo $term->term_id . ',';
}
}
```
to this:
```
if ( !empty($terms) ) {
// create an empty array
$procedures_to_include = array();
foreach( $terms as $term ) {
// now instead of echoing, add each term to the array
$procedures_to_include[] = $term->term_id;
}
}
```
Basically instead of echoing manually, you're creating the array to begin with, and in your `get_terms` call you can just use `$procedures_to_include` directly:
```
$terms = get_terms( array(
'taxonomy' => 'procedures',
'hide_empty' => true,
'include' => $procedures_to_include
) );
``` |
296,805 | <p>I have thousands of posts that I am displaying on my home page. I want to control number of posts so for this I am using <code>posts_per_page</code>but it is not working for me. All other arguments works but <code>posts_per_page</code> is not working. I have pagination on this page and <code>posts_per_page</code> works for all other pages of pagination but not for first (main) page.
So for testing purpose i create a blank template that just have one simple WordPress loop and not have pagination or any thing else that is displaying just post title and in this template i have limit on number of posts again but <code>posts_per_page</code> is not working even on this page.
I have tried disabling all plugins but there was no effect so i think this issue is with theme that is setting <code>posts_per_page</code> value dynamically.
I am also resetting the query before this loop using <code>wp_reset_query();</code> and tried this code in <code>functions.php</code> as well.</p>
<pre><code>add_action( 'pre_get_posts', 'set_posts_per_page' );
function set_posts_per_page( $query ) {
global $wp_the_query;
$query->set( 'posts_per_page', 12 );
return $query;
}
</code></pre>
<p>But nothing working for me. I have tried to display query content using <code>var_dump($query->request)</code>and in the query limit was 12 but on page i am still seeing 100+ posts. On WordPress settings page on theme settings page the posts limit is 12 but on front end this limit is not working. Here is the result of this query.</p>
<pre><code>string(489) "SELECT SQL_CALC_FOUND_ROWS wp_mdw75t47kk_posts.ID FROM wp_mdw75t47kk_posts INNER JOIN wp_mdw75t47kk_postmeta ON ( wp_mdw75t47kk_posts.ID = wp_mdw75t47kk_postmeta.post_id ) WHERE 1=1 AND ( wp_mdw75t47kk_postmeta.meta_key = '_imwb_zonpress_post_ctr' ) AND wp_mdw75t47kk_posts.post_type = 'post' AND (wp_mdw75t47kk_posts.post_status = 'publish' OR wp_mdw75t47kk_posts.post_status = 'private') GROUP BY wp_mdw75t47kk_posts.ID ORDER BY wp_mdw75t47kk_postmeta.meta_value+0 DESC LIMIT 0, 12"
</code></pre>
<p>I am also sharing url of this testing page if anybody wants to see this.
<a href="http://ifyougiveagirlaleotard.com/test/" rel="nofollow noreferrer">Test Page link</a>
You will also be able to see this issue on main page as well. For me this is very strange issue because i have tried everything from google but nothing working for me. <BR>
I am using covert store builder theme. Any suggestion will be much appreciated.
Thank you!</p>
<p>Here is complete code for this loop.</p>
<pre><code>wp_reset_query();
$args = Array(
'posts_per_page' => 12
);
$query = new WP_Query( $args );
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
</code></pre>
<p>Then there is some code to display image, title and excerpt and I think this should not effect number of posts. After this these lines are given</p>
<pre><code><?php
endwhile; ?>
</code></pre>
<p>But as i mention i have tried this code in a blank template without pagination but still posts_per_page was not working. So i think an external hook setting this value. I have tried to find out this in theme files but was not successful. I know this is just because of this theme.</p>
| [
{
"answer_id": 296807,
"author": "mad2kx",
"author_id": 138622,
"author_profile": "https://wordpress.stackexchange.com/users/138622",
"pm_score": 0,
"selected": false,
"text": "<p>Did you try this one?</p>\n\n<pre><code>function posts_on_homepage( $query ) {\n if ( $query->is_home() && $query->is_main_query() ) {\n $query->set( 'posts_per_page', 10 );\n }\n}\nadd_action( 'pre_get_posts', 'posts_on_homepage' );\n</code></pre>\n"
},
{
"answer_id": 298104,
"author": "Dunder",
"author_id": 68610,
"author_profile": "https://wordpress.stackexchange.com/users/68610",
"pm_score": 0,
"selected": false,
"text": "<p>Try adding this one before the query argument.</p>\n\n<pre><code> if (get_query_var('paged')) {\n $paged = get_query_var('paged');\n } elseif (get_query_var('page')) {\n $paged = get_query_var('page');\n } else {\n $paged = 1;\n }\n</code></pre>\n\n<p>At the argument, make <code>'paged' => $paged</code></p>\n"
},
{
"answer_id": 298118,
"author": "Asrsagar",
"author_id": 129292,
"author_profile": "https://wordpress.stackexchange.com/users/129292",
"pm_score": 1,
"selected": false,
"text": "<p>Did you try this one? </p>\n\n<pre><code><?php \n $blogpost = new WP_Query(array( \n 'post_type' => 'post',\n 'posts_per_page' => 6\n ));\n?>\n<?php while($blogpost->have_posts()) : $blogpost->the_post(); ?>\n// Writhe your Blog article Here.\n<?php endwhile; ?>\n</code></pre>\n"
},
{
"answer_id": 298570,
"author": "Rocketlaunch",
"author_id": 137052,
"author_profile": "https://wordpress.stackexchange.com/users/137052",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried adding the following before the main args and the loop?</p>\n\n<pre><code><!-- Modify pagination function for front page -->\n<?php\nglobal $paged, $wp_query, $wp;\n$args = wp_parse_args($wp->matched_query);\nif ( !empty ( $args['paged'] ) && 0 == $paged ) {\n$wp_query->set('paged', $args['paged']);\n$paged = $args['paged']; } ?>\n</code></pre>\n\n<p>Then add the pagination like so:</p>\n\n<pre><code><?php\n$args = array(\n'posts_per_page' => 12,\n'paged' => $paged ); ?>\n\n$query = new WP_Query($args);\n\n<?php if ($query->have_posts()) : $i = 1; ?>\n\n<?php while ( $query->have_posts() ) : $query->the_post(); ?>\n\n// Content Here\n\n<?php $i++; endwhile; ?>\n<?php else : ?>\n<h2>Content not found!</h2>\n<?php endif; ?>\n\n//pagination code\n</code></pre>\n\n<p>In my case I am using WP pagenavi, so I would use:</p>\n\n<pre><code><?php wp_pagenavi( array( 'query' => $query )); ?>\n<?php wp_reset_query(); ?>\n</code></pre>\n"
},
{
"answer_id": 298711,
"author": "mopsyd",
"author_id": 60036,
"author_profile": "https://wordpress.stackexchange.com/users/60036",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect that your theme is binding to a filter that is resetting the query also within your loop, which is causing unending recursion. If that is the case, you have three options:</p>\n\n<p>You can ditch the theme and use another one. That is probably a bad answer if you are heavily invested in it.</p>\n\n<p>You can hack the theme, which is also a bad answer, because you'll have to do it again when it updates, or you'll have to override a bunch of its core code in a child theme which can get very messy.</p>\n\n<p>Or, you can do it the quick and dirty way, which is to just use a good old <code>for</code> loop instead of <code>while</code>.</p>\n\n<pre><code>wp_reset_query();\n$GLOBALS['my_counter'] = 12;\n$args = Array(\n 'posts_per_page' => $GLOBALS['my_counter'];\n);\n\n$query = new WP_Query( $args );\n\n<?php\nfor ( $i = 0; $i < $GLOBALS['my_counter'], $i++ )\n{\n if (!$query->the_post())\n {\n break;\n }\n}\nunset($GLOBALS['my_counter']);\n?>\n</code></pre>\n\n<p>It's ugly, but it should do what you want. The <code>for</code> loop will only run 12 times, regardless of whether or not anything else is resetting the query. If you see duplicate posts, you can also put a break point in the loop and use <code>debug_backtrace(1)</code> to sniff out where it is happening, which is not really feasible in a <code>while</code> loop, unless you like the idea of about 8 bjillionty pages of debug code and possibly crashing your server.</p>\n\n<hr>\n\n<p>If this does work for you, consider finding a more elegant solution for a couple of reasons:</p>\n\n<p><strong>A)</strong> Globals are bad.</p>\n\n<p><strong>B)</strong> Doing things the wrong way usually leads to more doing things the wrong way. I can't say what is the right way for your specific theme, but if it provides any way to do what you want on your home page, you should do that. If it does not provide any kind of api though, do what you have to.</p>\n"
}
]
| 2018/03/14 | [
"https://wordpress.stackexchange.com/questions/296805",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120693/"
]
| I have thousands of posts that I am displaying on my home page. I want to control number of posts so for this I am using `posts_per_page`but it is not working for me. All other arguments works but `posts_per_page` is not working. I have pagination on this page and `posts_per_page` works for all other pages of pagination but not for first (main) page.
So for testing purpose i create a blank template that just have one simple WordPress loop and not have pagination or any thing else that is displaying just post title and in this template i have limit on number of posts again but `posts_per_page` is not working even on this page.
I have tried disabling all plugins but there was no effect so i think this issue is with theme that is setting `posts_per_page` value dynamically.
I am also resetting the query before this loop using `wp_reset_query();` and tried this code in `functions.php` as well.
```
add_action( 'pre_get_posts', 'set_posts_per_page' );
function set_posts_per_page( $query ) {
global $wp_the_query;
$query->set( 'posts_per_page', 12 );
return $query;
}
```
But nothing working for me. I have tried to display query content using `var_dump($query->request)`and in the query limit was 12 but on page i am still seeing 100+ posts. On WordPress settings page on theme settings page the posts limit is 12 but on front end this limit is not working. Here is the result of this query.
```
string(489) "SELECT SQL_CALC_FOUND_ROWS wp_mdw75t47kk_posts.ID FROM wp_mdw75t47kk_posts INNER JOIN wp_mdw75t47kk_postmeta ON ( wp_mdw75t47kk_posts.ID = wp_mdw75t47kk_postmeta.post_id ) WHERE 1=1 AND ( wp_mdw75t47kk_postmeta.meta_key = '_imwb_zonpress_post_ctr' ) AND wp_mdw75t47kk_posts.post_type = 'post' AND (wp_mdw75t47kk_posts.post_status = 'publish' OR wp_mdw75t47kk_posts.post_status = 'private') GROUP BY wp_mdw75t47kk_posts.ID ORDER BY wp_mdw75t47kk_postmeta.meta_value+0 DESC LIMIT 0, 12"
```
I am also sharing url of this testing page if anybody wants to see this.
[Test Page link](http://ifyougiveagirlaleotard.com/test/)
You will also be able to see this issue on main page as well. For me this is very strange issue because i have tried everything from google but nothing working for me.
I am using covert store builder theme. Any suggestion will be much appreciated.
Thank you!
Here is complete code for this loop.
```
wp_reset_query();
$args = Array(
'posts_per_page' => 12
);
$query = new WP_Query( $args );
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
```
Then there is some code to display image, title and excerpt and I think this should not effect number of posts. After this these lines are given
```
<?php
endwhile; ?>
```
But as i mention i have tried this code in a blank template without pagination but still posts\_per\_page was not working. So i think an external hook setting this value. I have tried to find out this in theme files but was not successful. I know this is just because of this theme. | Did you try this one?
```
<?php
$blogpost = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 6
));
?>
<?php while($blogpost->have_posts()) : $blogpost->the_post(); ?>
// Writhe your Blog article Here.
<?php endwhile; ?>
``` |
296,817 | <p>So, I have a loop that works great.</p>
<p>But I need to count how many posts that loop has, and I need to do it via a query to the DB.</p>
<p>My loop looks like:</p>
<pre><code>$adsArg = array(
'offset' => $offset,
'post_type' => 'ads',
'meta_key' => $metaKey,
'tax_query' => $taxQuery,
'meta_query' => $metaValue,
);
$adsQuery = new WP_Query($adsArg);
</code></pre>
<p>And the query I have so far looks like:</p>
<pre><code>$wpdb->get_var($wpdb->prepare("SELECT COUNT(ID) FROM " . $table_name . " WHERE post_type = 'ads' AND post_status = 'publish' AND tax_query = " . $taxQuery . " AND meta_query = " . $metaValue . ", array() ) );
</code></pre>
<p>It's not working and I have no idea the proper way to do that.</p>
<p>The counter has to be done this way, with a direct query to the database.</p>
| [
{
"answer_id": 296818,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 3,
"selected": true,
"text": "<p>To get the number of posts you can do it easily without a second query with</p>\n\n<pre><code>$adsQuery->post_count;\n</code></pre>\n\n<p>But if there's some reason (I'd love to know the context!) I can't grasp that the same query has to be run twice and to the database directly- to answer your question as to why it's not working:</p>\n\n<ul>\n<li><p>Has <code>$table_name</code> been defined? Are you using <code>{$wpdb->prefix}_posts</code> or <code>{$wpdb->posts}</code> in <code>$table_name</code>? </p></li>\n<li><p>You have no sql string value quotes around <code>$taxQuery</code> or <code>$metaValue</code> values, so that'll break the query, unless they integers</p></li>\n<li><p>Has <code>$wpdb</code> has been globally declared?</p></li>\n<li><p>Are you using <code>$wpdb->print_error()</code> to show the issue?</p></li>\n<li><p>If you echo'ed the string query instead of running it, do it look like you expect? whats missing? if you paste it in phpmyAdmin/sqlworkbench does it give you any indication of the problem?</p></li>\n<li><p>do you have any errors in your servers errors logs? mysql error logs?</p></li>\n</ul>\n\n<hr>\n\n<p>I would suggest something like the following</p>\n\n<pre><code><?php\nglobal $wpdb;\n\n$query = \"\n SELECT COUNT(ID) \n FROM {$wpdb->posts}\n WHERE post_type = 'ads' \n AND post_status = 'publish' \n AND tax_query = \\\"%s\\\"\n AND meta_query = \\\"%s\\\"\";\n\n// show query\n// echo \"<pre>{$query}</pre>\";\n\n$count = $wpdb->get_var( $wpdb->prepare( \n $query, \n $taxQuery,\n $metaValue\n));\n\n\n\necho \"<pre>\";\nif($wpdb->last_error !== '') {\n echo \" ERROR: \";\n $wpdb->print_error();\n} else {\n echo \"Count: {$count}\";\n}\necho \"</pre>\";\n</code></pre>\n"
},
{
"answer_id": 296898,
"author": "Marcelo Henriques Cortez",
"author_id": 44437,
"author_profile": "https://wordpress.stackexchange.com/users/44437",
"pm_score": 1,
"selected": false,
"text": "<p>Since I left out a detail in my question, I approved David Sword's answer because it helped me connect correctly to my DB the way I asked.</p>\n\n<p>But in my specific case, the 'post_count' didn't work because it considers the 'offset' and 'post per page' attr.</p>\n\n<p>Since I need all the posts in the query, I had to use 'found_posts'.</p>\n\n<p>Ex.: $adsQuery->found_posts;</p>\n\n<blockquote>\n <p>This hook is especially useful when developing custom pagination. For instance, if you are declaring a custom offset value in your queries, WordPress will NOT deduct the offset from the the $wp_query->found_posts parameter (for example, if you have 45 usable posts after an offset of 10, WordPress will ignore the offset and still give found_posts a value of 55).</p>\n</blockquote>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/found_posts\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/found_posts</a></p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n\n<p>Thnx also to @JacobPeattie for pointing that I should be trying to fix 'post_count' problem.</p>\n"
}
]
| 2018/03/14 | [
"https://wordpress.stackexchange.com/questions/296817",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44437/"
]
| So, I have a loop that works great.
But I need to count how many posts that loop has, and I need to do it via a query to the DB.
My loop looks like:
```
$adsArg = array(
'offset' => $offset,
'post_type' => 'ads',
'meta_key' => $metaKey,
'tax_query' => $taxQuery,
'meta_query' => $metaValue,
);
$adsQuery = new WP_Query($adsArg);
```
And the query I have so far looks like:
```
$wpdb->get_var($wpdb->prepare("SELECT COUNT(ID) FROM " . $table_name . " WHERE post_type = 'ads' AND post_status = 'publish' AND tax_query = " . $taxQuery . " AND meta_query = " . $metaValue . ", array() ) );
```
It's not working and I have no idea the proper way to do that.
The counter has to be done this way, with a direct query to the database. | To get the number of posts you can do it easily without a second query with
```
$adsQuery->post_count;
```
But if there's some reason (I'd love to know the context!) I can't grasp that the same query has to be run twice and to the database directly- to answer your question as to why it's not working:
* Has `$table_name` been defined? Are you using `{$wpdb->prefix}_posts` or `{$wpdb->posts}` in `$table_name`?
* You have no sql string value quotes around `$taxQuery` or `$metaValue` values, so that'll break the query, unless they integers
* Has `$wpdb` has been globally declared?
* Are you using `$wpdb->print_error()` to show the issue?
* If you echo'ed the string query instead of running it, do it look like you expect? whats missing? if you paste it in phpmyAdmin/sqlworkbench does it give you any indication of the problem?
* do you have any errors in your servers errors logs? mysql error logs?
---
I would suggest something like the following
```
<?php
global $wpdb;
$query = "
SELECT COUNT(ID)
FROM {$wpdb->posts}
WHERE post_type = 'ads'
AND post_status = 'publish'
AND tax_query = \"%s\"
AND meta_query = \"%s\"";
// show query
// echo "<pre>{$query}</pre>";
$count = $wpdb->get_var( $wpdb->prepare(
$query,
$taxQuery,
$metaValue
));
echo "<pre>";
if($wpdb->last_error !== '') {
echo " ERROR: ";
$wpdb->print_error();
} else {
echo "Count: {$count}";
}
echo "</pre>";
``` |
296,852 | <p>I would like to change the "Product has been added to your cart." text for variable products to include the variation.</p>
<p>For example if I added a size 7 Shoe to my cart it should say: "Shoe in Size 7 was added to your cart"</p>
<p>What do I have to edit to change this?</p>
| [
{
"answer_id": 296853,
"author": "melvin",
"author_id": 130740,
"author_profile": "https://wordpress.stackexchange.com/users/130740",
"pm_score": 3,
"selected": true,
"text": "<pre><code>add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_function', 10, 2 ); \n\nfunction my_add_to_cart_function( $message, $product_id ) { \n $message = sprintf(esc_html__('« %s » has been added by to your cart.','woocommerce'), get_the_title( $product_id ) ); \n return $message; \n}\n</code></pre>\n\n<p>The above code will help you to change the message. Since by knowing the hook <code>wc_add_to_cart_message</code> you can improve the code</p>\n"
},
{
"answer_id": 296860,
"author": "Vivekpathak",
"author_id": 135442,
"author_profile": "https://wordpress.stackexchange.com/users/135442",
"pm_score": 0,
"selected": false,
"text": "<pre><code> add_filter( 'wc_add_to_cart_message', 'custom_wc_add_to_cart_message', 10, 2 ); \n\n function custom_wc_add_to_cart_message( $message, $product_id ) { \n\n $message = sprintf( '%s has been added to your selection.', get_the_title( $product_id ) ); \n\n return $message; \n\n }\n</code></pre>\n\n<p>Hope this will help you:)</p>\n"
}
]
| 2018/03/15 | [
"https://wordpress.stackexchange.com/questions/296852",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128837/"
]
| I would like to change the "Product has been added to your cart." text for variable products to include the variation.
For example if I added a size 7 Shoe to my cart it should say: "Shoe in Size 7 was added to your cart"
What do I have to edit to change this? | ```
add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_function', 10, 2 );
function my_add_to_cart_function( $message, $product_id ) {
$message = sprintf(esc_html__('« %s » has been added by to your cart.','woocommerce'), get_the_title( $product_id ) );
return $message;
}
```
The above code will help you to change the message. Since by knowing the hook `wc_add_to_cart_message` you can improve the code |
296,882 | <p>I have big problem with white screen in WordPress.</p>
<p>I would like to migrate site from live to localhost, I don't have credentials for hosting, and I've migrated site using All In One Import Plugin.</p>
<p><strong>Steps:</strong></p>
<ol>
<li>I've extracted <code>.wpress</code> file using <code>wpress-extractor</code>.</li>
<li>On Localhost installed fresh WordPress</li>
<li>Created new database and imported database from live site</li>
<li>Files from extracted <code>.wpress</code> file I've copied into <code>wp-content</code></li>
<li>Inside <code>wp-config.php</code> change database, set credentials for login, change prefix of database etc ...</li>
<li>After that I've run <code>Interconnect/it</code> script to change paths inside Database</li>
<li>Finally when I visit site I've got <strong>white screen</strong> , If I try to login I've got login inputs, but when click on submit button I see white screen.</li>
</ol>
<p><strong>What I tried:</strong></p>
<ol>
<li>Deleting all plugins</li>
<li>Deleting theme</li>
<li><code>define( 'WP_DEBUG', true )</code></li>
<li><code>define('WP_MEMORY_LIMIT', '256M');</code></li>
<li>Tried to run in incognito mode of Chrome</li>
<li>Deleted <code>.htaccess</code></li>
</ol>
<p>and still same problem ... </p>
<p>Can someone help me, thank you in advance.</p>
| [
{
"answer_id": 296853,
"author": "melvin",
"author_id": 130740,
"author_profile": "https://wordpress.stackexchange.com/users/130740",
"pm_score": 3,
"selected": true,
"text": "<pre><code>add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_function', 10, 2 ); \n\nfunction my_add_to_cart_function( $message, $product_id ) { \n $message = sprintf(esc_html__('« %s » has been added by to your cart.','woocommerce'), get_the_title( $product_id ) ); \n return $message; \n}\n</code></pre>\n\n<p>The above code will help you to change the message. Since by knowing the hook <code>wc_add_to_cart_message</code> you can improve the code</p>\n"
},
{
"answer_id": 296860,
"author": "Vivekpathak",
"author_id": 135442,
"author_profile": "https://wordpress.stackexchange.com/users/135442",
"pm_score": 0,
"selected": false,
"text": "<pre><code> add_filter( 'wc_add_to_cart_message', 'custom_wc_add_to_cart_message', 10, 2 ); \n\n function custom_wc_add_to_cart_message( $message, $product_id ) { \n\n $message = sprintf( '%s has been added to your selection.', get_the_title( $product_id ) ); \n\n return $message; \n\n }\n</code></pre>\n\n<p>Hope this will help you:)</p>\n"
}
]
| 2018/03/15 | [
"https://wordpress.stackexchange.com/questions/296882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132584/"
]
| I have big problem with white screen in WordPress.
I would like to migrate site from live to localhost, I don't have credentials for hosting, and I've migrated site using All In One Import Plugin.
**Steps:**
1. I've extracted `.wpress` file using `wpress-extractor`.
2. On Localhost installed fresh WordPress
3. Created new database and imported database from live site
4. Files from extracted `.wpress` file I've copied into `wp-content`
5. Inside `wp-config.php` change database, set credentials for login, change prefix of database etc ...
6. After that I've run `Interconnect/it` script to change paths inside Database
7. Finally when I visit site I've got **white screen** , If I try to login I've got login inputs, but when click on submit button I see white screen.
**What I tried:**
1. Deleting all plugins
2. Deleting theme
3. `define( 'WP_DEBUG', true )`
4. `define('WP_MEMORY_LIMIT', '256M');`
5. Tried to run in incognito mode of Chrome
6. Deleted `.htaccess`
and still same problem ...
Can someone help me, thank you in advance. | ```
add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_function', 10, 2 );
function my_add_to_cart_function( $message, $product_id ) {
$message = sprintf(esc_html__('« %s » has been added by to your cart.','woocommerce'), get_the_title( $product_id ) );
return $message;
}
```
The above code will help you to change the message. Since by knowing the hook `wc_add_to_cart_message` you can improve the code |
296,942 | <p>It's the first I have seen this.
In a project I'm working on, I tried to switch on the debug mode for wordpress to see logs. Even if I activate the debug_log in <code>wp-config.php</code>, <code>debug.log</code> file is never created in <code>/htdocs/wp-content/</code></p>
<p><strong>wp-config.php</strong></p>
<pre><code>define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);
define('SCRIPT_DEBUG', true);
</code></pre>
<p><strong>wp-content dir rights</strong></p>
<p><a href="https://i.stack.imgur.com/XDOG4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XDOG4.png" alt="enter image description here"></a></p>
<p><strong>load.php</strong></p>
<pre><code>if ( WP_DEBUG_LOG ) {
ini_set( 'log_errors', 1 );
var_dump( WP_CONTENT_DIR . '/debug.log' );
// display correctly this => "/htdocs/wp-content/debug.log";
ini_set( 'error_log', WP_CONTENT_DIR . '/debug.log' );
}
</code></pre>
| [
{
"answer_id": 301298,
"author": "J.BizMai",
"author_id": 128094,
"author_profile": "https://wordpress.stackexchange.com/users/128094",
"pm_score": 4,
"selected": true,
"text": "<p>I found the problem.\nIn the Apache server, inside the php.ini, the variable...</p>\n\n<pre><code>track_errors = Off\n</code></pre>\n\n<p>To get this information, you can do in a phpfile <code>phpinfo();</code>.\nSo, to write the debug log file, you need to set <code>track_errors</code> as <code>'On'</code>.</p>\n"
},
{
"answer_id": 411491,
"author": "Eric Klien",
"author_id": 74790,
"author_profile": "https://wordpress.stackexchange.com/users/74790",
"pm_score": 0,
"selected": false,
"text": "<p>None of the above solutions worked for me.</p>\n<p>So I ran phpinfo() and found that error_log = /var/log/php-fpm/www-error.log on my machine and I was finally able to see the error. In my case, a script was exceeding 30 seconds allowed of execution time.</p>\n<p>So use phpinfo() and find out where your logs are stored!</p>\n"
}
]
| 2018/03/15 | [
"https://wordpress.stackexchange.com/questions/296942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128094/"
]
| It's the first I have seen this.
In a project I'm working on, I tried to switch on the debug mode for wordpress to see logs. Even if I activate the debug\_log in `wp-config.php`, `debug.log` file is never created in `/htdocs/wp-content/`
**wp-config.php**
```
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);
define('SCRIPT_DEBUG', true);
```
**wp-content dir rights**
[](https://i.stack.imgur.com/XDOG4.png)
**load.php**
```
if ( WP_DEBUG_LOG ) {
ini_set( 'log_errors', 1 );
var_dump( WP_CONTENT_DIR . '/debug.log' );
// display correctly this => "/htdocs/wp-content/debug.log";
ini_set( 'error_log', WP_CONTENT_DIR . '/debug.log' );
}
``` | I found the problem.
In the Apache server, inside the php.ini, the variable...
```
track_errors = Off
```
To get this information, you can do in a phpfile `phpinfo();`.
So, to write the debug log file, you need to set `track_errors` as `'On'`. |
296,947 | <p>I was reading <a href="https://stackoverflow.com/a/4447615/1080355">this answer</a>, and tried to used its guide to <a href="http://www.bestwpthemez.com/wordpress/how-to-hide-your-wp-admin-login-page-2437/" rel="nofollow noreferrer">hide login page</a>. It suggest to edit <code>.htaccess</code> file of my website to something like this:</p>
<pre><code>RewriteEngine On
RewriteBase /
##### ABOVE THIS POINT IS ALREADY INSERTED BY WORD PRESS
##### Michi’s code is BELOW #####
RewriteCond %{REQUEST_URI} wp-admin/
RewriteCond %{QUERY_STRING} !YOURSECRETWORDHERE
RewriteRule .*\.php [F,L]
RewriteCond %{QUERY_STRING} !YOURSECRETWORDHERE
RewriteRule ^ADMINFOLDER/(.*) wp-admin/$1?%{QUERY_STRING}&YOURSECRETWORDHERE [L]
##### Michi’s code is ABOVE #####
##### BELOW THIS POINT IS ALREADY INSERTED BY WORD PRESS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</code></pre>
<p>My <code>.htaccess</code> file starts with these lines:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>I want to know if I add anything between <code># BEGIN WordPress</code> and <code># END WordPress</code> is it possible that it will be overwritten by wordpress or not? This is usual about automated scripts but since it is not mentioned any warnings, I want to know may be it is safe to add some rules inside this block.</p>
| [
{
"answer_id": 296948,
"author": "Oliver Leach",
"author_id": 138726,
"author_profile": "https://wordpress.stackexchange.com/users/138726",
"pm_score": -1,
"selected": false,
"text": "<p>No it shouldn't interfere, I have rules inside that block and they are all still active, even after changing permalink structure. Hope this helps. </p>\n"
},
{
"answer_id": 296951,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 4,
"selected": true,
"text": "<p>Wordpress uses those markers to put its rules between. I never have and never would put custom rules in there.</p>\n\n<p>Check out <code>insert_with_markers()</code> and <code>save_mod_rewrite_rules()</code> in \n<a href=\"https://github.com/WordPress/WordPress/blob/d7025e778704c7cd98f0a3544fbe93cacbef7ae6/wp-admin/includes/misc.php\" rel=\"nofollow noreferrer\"><code>wp-admin/includes/misc.php</code></a></p>\n\n<p>Most notably this comment block which answers your question:</p>\n\n<pre><code>/**\n * Inserts an array of strings into a file (.htaccess ), placing it between\n * BEGIN and END markers.\n *\n * Replaces existing marked info. Retains surrounding\n * data. Creates file if none exists.\n */\n</code></pre>\n"
},
{
"answer_id": 296952,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>This is usual about automated scripts </p>\n</blockquote>\n\n<p>Exactly. When wordpress will need to regenerate the htaccess rule it will read the current file and replace the \"wordpress\" section in it. If you need rules to be in that section, you can write a plugin to override/change the rules being generated.</p>\n\n<p>Side notes: obscurity is not security, brute force is not how sites are getting hacked, and you will need to disable xml-rpc, and maybe later the rest-api as well.</p>\n"
},
{
"answer_id": 297066,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<p><em>Aside:</em> Michi's code is not quite correct, and perhaps not as secure as you might think...</p>\n\n<blockquote>\n<pre><code>##### Michi’s code is BELOW #####\nRewriteCond %{REQUEST_URI} wp-admin/\nRewriteCond %{QUERY_STRING} !YOURSECRETWORDHERE\nRewriteRule .*\\.php [F,L]\nRewriteCond %{QUERY_STRING} !YOURSECRETWORDHERE\nRewriteRule ^ADMINFOLDER/(.*) wp-admin/$1?%{QUERY_STRING}&YOURSECRETWORDHERE [L]\n##### Michi’s code is ABOVE #####\n</code></pre>\n</blockquote>\n\n<p>The first <code>RewriteRule</code> is missing a <em>substitution</em> argument. This will result in the request being (incorrectly) rewritten to <code>/[F,L]</code>, which will result in a 404. Ok, so access is essentially blocked, but the intention is to serve a 403 Forbidden (which is what the <code>F</code> flag is for). So, the following:</p>\n\n<blockquote>\n<pre><code>RewriteRule .*\\.php [F,L]\n</code></pre>\n</blockquote>\n\n<p>Should be rewritten as:</p>\n\n<pre><code>RewriteRule \\.php$ - [F]\n</code></pre>\n\n<p>Note the use of the hyphen (<code>-</code>) for the second argument. This looks like an accidental omission in the original code. Also, no need for the <code>L</code> flag when the <code>F</code> flag is used.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>RewriteCond %{QUERY_STRING} !YOURSECRETWORDHERE\nRewriteRule ^ADMINFOLDER/(.*) wp-admin/$1?%{QUERY_STRING}&YOURSECRETWORDHERE [L]\n</code></pre>\n</blockquote>\n\n<p>This second rule allows you to gain access if you know the <code>ADMINFOLDER</code>. The <code>YOURSECRETWORDHERE</code> is essentially bypassed (and not required by the end user)!? So, the <code>ADMINFOLDER</code> is really the \"secret\" that should be long and cryptic. (TBH, there's no need for 2 \"secrets\" here, when 1 will do.)</p>\n\n<hr>\n\n<p>Any blocking directives like this should go <em>before</em> the WordPress front-controller. (Although if you are only blocking physical files then it doesn't strictly matter in order to be functional, since the WP front-controller only routes URL paths that don't map to physical files/directories.)</p>\n"
}
]
| 2018/03/15 | [
"https://wordpress.stackexchange.com/questions/296947",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86163/"
]
| I was reading [this answer](https://stackoverflow.com/a/4447615/1080355), and tried to used its guide to [hide login page](http://www.bestwpthemez.com/wordpress/how-to-hide-your-wp-admin-login-page-2437/). It suggest to edit `.htaccess` file of my website to something like this:
```
RewriteEngine On
RewriteBase /
##### ABOVE THIS POINT IS ALREADY INSERTED BY WORD PRESS
##### Michi’s code is BELOW #####
RewriteCond %{REQUEST_URI} wp-admin/
RewriteCond %{QUERY_STRING} !YOURSECRETWORDHERE
RewriteRule .*\.php [F,L]
RewriteCond %{QUERY_STRING} !YOURSECRETWORDHERE
RewriteRule ^ADMINFOLDER/(.*) wp-admin/$1?%{QUERY_STRING}&YOURSECRETWORDHERE [L]
##### Michi’s code is ABOVE #####
##### BELOW THIS POINT IS ALREADY INSERTED BY WORD PRESS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
```
My `.htaccess` file starts with these lines:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
I want to know if I add anything between `# BEGIN WordPress` and `# END WordPress` is it possible that it will be overwritten by wordpress or not? This is usual about automated scripts but since it is not mentioned any warnings, I want to know may be it is safe to add some rules inside this block. | Wordpress uses those markers to put its rules between. I never have and never would put custom rules in there.
Check out `insert_with_markers()` and `save_mod_rewrite_rules()` in
[`wp-admin/includes/misc.php`](https://github.com/WordPress/WordPress/blob/d7025e778704c7cd98f0a3544fbe93cacbef7ae6/wp-admin/includes/misc.php)
Most notably this comment block which answers your question:
```
/**
* Inserts an array of strings into a file (.htaccess ), placing it between
* BEGIN and END markers.
*
* Replaces existing marked info. Retains surrounding
* data. Creates file if none exists.
*/
``` |
296,953 | <p>I'm working on a site that uses FacetWP for an events location page and one critical feature is not working. Last year, another dev set up a custom solution to list out FacetWP posts and have them sorted by the state they are in. They used a custom taxonomy for this, but since then, the plugin and is map add-on have had updates that broke that solution.</p>
<p>The dev behind FacetWP has been helping me a bit to rework the custom solution, but he's unavailable now, and I still need some help. He directed me to redo the query to cut out the custom taxonomy and use a custom field instead for the state names as that works better with the plugin. So the query for this template looks like this:</p>
<pre><code><?php
return array(
'post_type' => 'location',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_key' => 'state',
'orderby' => array(
'meta_value' => 'ASC',
'title' => 'ASC',
),
);
</code></pre>
<p>This part works great and solved an earlier problem I had. I rebuilt the template's display code like this:</p>
<pre><code><?php
while ($query->have_posts()) {
$state = get_field('state');
$show_header = (empty($prev_state) || $state != $prev_state);
$prev_state = $state;
$query->the_post();
$post_id = get_the_ID();
$title = get_the_title($post_id);
$distance = facetwp_get_distance($post_id);
$distance = (false !== $distance) ? round($distance, 1) . ' miles away' : '';
$coords = get_post_meta($post_id, 'location', true);
$content = get_the_content();
?>
<?php if ($show_header): ?>
<h1 class="state-name"><?php echo esc_html($state); ?></h1>
<?php endif;?>
<div class="post-item" data-title="<?php echo esc_attr($title); ?>"
data-latitude="<?php echo $coords['lat']; ?>" data-longitude="<?php echo $coords['lng']; ?>"
data-distance="<?php echo $distance; ?>">
<div class="post-item-content">
<h2><?php echo $title; ?></h2>
<?php echo $content; ?>
</div>
</div>
<?php
}
wp_reset_query();
?>
</code></pre>
<p>You can see from <a href="http://d2slive.staging.wpengine.com/locations/" rel="nofollow noreferrer">the staging server where I'm testing this</a> that it's almost working, but not 100% correctly. The posts are not listing by state correctly, and the state title is incorrect above the listings.</p>
<p>It's been a long day and my brain is just not seeing what I need to do to correct this. I could definitely use a nudge in the right direction.</p>
| [
{
"answer_id": 296957,
"author": "digDoug",
"author_id": 138731,
"author_profile": "https://wordpress.stackexchange.com/users/138731",
"pm_score": 0,
"selected": false,
"text": "<p>All you need to do is list out the custom field values in a few foreach loops like so: </p>\n\n<pre><code><?php\n\nwhile ($query->have_posts()) {\n $query->the_post();\n $posts = $query->have_posts();\n $post_id = get_the_ID();\n $title = get_the_title($post_id);\n $distance = facetwp_get_distance($post_id);\n $distance = (false !== $distance) ? round($distance, 1) . ' miles away' : '';\n $coords = get_post_meta($post_id, 'location', true);\n $content = get_the_content();\n\n foreach ($posts as $post) {\n $state = get_field('state');\n $state_posts[$state][] = $post;\n }\n}\n\nforeach ($state_posts as $state_post => $state_title) {\n ?>\n <h1 class=\"state-name\"><?php echo esc_html($state); ?></h1>\n <?php\n foreach ($state_title as $listing) {\n ?>\n <div class=\"post-item\" data-title=\"<?php echo esc_attr($title); ?>\"\n data-latitude=\"<?php echo $coords['lat']; ?>\" data-longitude=\"<?php echo $coords['lng']; ?>\" data-distance=\"<?php echo $distance; ?>\">\n <div class=\"post-item-content\">\n <h2><?php echo $title; ?></h2>\n <?php echo $content; ?>\n </div>\n </div>\n <?php\n }\n}\n</code></pre>\n"
},
{
"answer_id": 296964,
"author": "KreigD",
"author_id": 118681,
"author_profile": "https://wordpress.stackexchange.com/users/118681",
"pm_score": 3,
"selected": true,
"text": "<p>I finally fixed it:</p>\n\n<pre><code><?php\n\n $state_posts = array();\n\n while ($query->have_posts()) {\n $query->the_post();\n $state = get_post_meta(get_the_ID(), 'state', true);\n $state_posts[$state][] = $post;\n }\n\n wp_reset_query();\n\n foreach ($state_posts as $state_post => $state_title) {\n?>\n <h1 class=\"state-name\"><?php echo esc_html($state_post); ?></h1>\n<?php\n foreach ($state_title as $listing => $single_listing) {\n setup_postdata($single_listing);\n $post_id = $single_listing->ID;\n $title = get_the_title($post_id);\n $distance = facetwp_get_distance($post_id);\n $distance = (false !== $distance) ? round($distance, 1) . ' miles away' : '';\n $coords = get_post_meta($post_id, 'location', true);\n $content = get_the_content();\n?>\n <div class=\"post-item\" data-title=\"<?php echo esc_attr($title); ?>\" data-latitude=\"<?php echo $coords['lat']; ?>\" data-longitude=\"<?php echo $coords['lng']; ?>\" data-distance=\"<?php echo $distance; ?>\">\n <div class=\"post-item-content\">\n <h2><?php echo $title; ?></h2>\n <?php echo $content; ?>\n </div>\n </div>\n<?php\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>I had the post data like <code>the_title</code>, <code>the_content</code>, etc. in the <code>while</code> loop when I needed it in the very last <code>foreach</code> loop in order to apply those to only the individual posts.</p>\n"
}
]
| 2018/03/15 | [
"https://wordpress.stackexchange.com/questions/296953",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118681/"
]
| I'm working on a site that uses FacetWP for an events location page and one critical feature is not working. Last year, another dev set up a custom solution to list out FacetWP posts and have them sorted by the state they are in. They used a custom taxonomy for this, but since then, the plugin and is map add-on have had updates that broke that solution.
The dev behind FacetWP has been helping me a bit to rework the custom solution, but he's unavailable now, and I still need some help. He directed me to redo the query to cut out the custom taxonomy and use a custom field instead for the state names as that works better with the plugin. So the query for this template looks like this:
```
<?php
return array(
'post_type' => 'location',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_key' => 'state',
'orderby' => array(
'meta_value' => 'ASC',
'title' => 'ASC',
),
);
```
This part works great and solved an earlier problem I had. I rebuilt the template's display code like this:
```
<?php
while ($query->have_posts()) {
$state = get_field('state');
$show_header = (empty($prev_state) || $state != $prev_state);
$prev_state = $state;
$query->the_post();
$post_id = get_the_ID();
$title = get_the_title($post_id);
$distance = facetwp_get_distance($post_id);
$distance = (false !== $distance) ? round($distance, 1) . ' miles away' : '';
$coords = get_post_meta($post_id, 'location', true);
$content = get_the_content();
?>
<?php if ($show_header): ?>
<h1 class="state-name"><?php echo esc_html($state); ?></h1>
<?php endif;?>
<div class="post-item" data-title="<?php echo esc_attr($title); ?>"
data-latitude="<?php echo $coords['lat']; ?>" data-longitude="<?php echo $coords['lng']; ?>"
data-distance="<?php echo $distance; ?>">
<div class="post-item-content">
<h2><?php echo $title; ?></h2>
<?php echo $content; ?>
</div>
</div>
<?php
}
wp_reset_query();
?>
```
You can see from [the staging server where I'm testing this](http://d2slive.staging.wpengine.com/locations/) that it's almost working, but not 100% correctly. The posts are not listing by state correctly, and the state title is incorrect above the listings.
It's been a long day and my brain is just not seeing what I need to do to correct this. I could definitely use a nudge in the right direction. | I finally fixed it:
```
<?php
$state_posts = array();
while ($query->have_posts()) {
$query->the_post();
$state = get_post_meta(get_the_ID(), 'state', true);
$state_posts[$state][] = $post;
}
wp_reset_query();
foreach ($state_posts as $state_post => $state_title) {
?>
<h1 class="state-name"><?php echo esc_html($state_post); ?></h1>
<?php
foreach ($state_title as $listing => $single_listing) {
setup_postdata($single_listing);
$post_id = $single_listing->ID;
$title = get_the_title($post_id);
$distance = facetwp_get_distance($post_id);
$distance = (false !== $distance) ? round($distance, 1) . ' miles away' : '';
$coords = get_post_meta($post_id, 'location', true);
$content = get_the_content();
?>
<div class="post-item" data-title="<?php echo esc_attr($title); ?>" data-latitude="<?php echo $coords['lat']; ?>" data-longitude="<?php echo $coords['lng']; ?>" data-distance="<?php echo $distance; ?>">
<div class="post-item-content">
<h2><?php echo $title; ?></h2>
<?php echo $content; ?>
</div>
</div>
<?php
}
wp_reset_postdata();
}
```
I had the post data like `the_title`, `the_content`, etc. in the `while` loop when I needed it in the very last `foreach` loop in order to apply those to only the individual posts. |
296,956 | <p>I'm working on a messy customer project.
To debug it, I would like to work on it on localhost.
I'm using Wampserver.</p>
<p>This is what I did :</p>
<p>1 - I made a virtualhost</p>
<p><strong>httpd-vhosts.conf</strong></p>
<pre><code><VirtualHost *:80>
ServerName devfoo.pro
DocumentRoot "c:/path/to/project/src/www"
<Directory "c:/path/to/project/src/www/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
</code></pre>
<p>2 - I renamed the file <code>.htaccess</code> to <code>_.htaccess</code></p>
<p>At that point when I run the page, there is still a redirection from <code>http://devfoo.pro</code> to <code>https://devfoo.pro</code>.</p>
<p>Notice : If I rename the plugin <code>really-simple-ssl</code> to <code>_really-simple-ssl</code>, the page redirect to the online website.</p>
<p>So... how can I import a WordPress project on localhost and deactivate the https protocol properly ? (Keeping the https on localhost is so messy! I never manage to simulate https on a local server with or without documentation, tutorials etc... )</p>
| [
{
"answer_id": 296960,
"author": "JBoulhous",
"author_id": 137648,
"author_profile": "https://wordpress.stackexchange.com/users/137648",
"pm_score": 1,
"selected": false,
"text": "<p>I also had this experience with chrome and firefox, they switch http to https and did not find a way to overcome it, so i used internet explorer in that windows machine.<br>\nI don't think you can have ssl on localhost or an ip address, i guess you know it as you used devfoo.pro. SSL certificate could be generated only for fully qualified domain names. </p>\n\n<p>So, you will need to <strong>buy</strong> a certificate to have things working, out of the box. <strong>Easy and \"secure\"</strong>.<br>\nOr you can self sign one for your self, following a tutorial :-). <strong>Might be difficult</strong> and you will need to accept it in your browser or os.<br>\nOr better (at least for me), use this <a href=\"http://www.selfsignedcertificate.com/\" rel=\"nofollow noreferrer\">website</a>. It will self sign a certificate for a provided domain.</p>\n"
},
{
"answer_id": 296968,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 0,
"selected": false,
"text": "<p>to remove <code>https</code> on an install, you can do a find and replace on the local database, I found <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">wpcli is the easiest way</a>:</p>\n\n<pre><code>wp search-replace 'https://example.com' 'http://example.com'\nwp search-replace 'https://www.example.com' 'http://www.example.com'\n</code></pre>\n\n<p>you can also do a find+replace with a normal <code>.sql</code>. be mindful for serialized strings in the _options table, they often break, but if you know it's broken and why it's not hard to fix.</p>\n\n<p>beyond that:</p>\n\n<ul>\n<li><p>look for plugins like \"force https\" and make sure they're removed</p></li>\n<li><p>look in wp-config.php and make sure there's no hard coded HTTPS rule in there (sometimes force_ssl, sometimes, site_url, etc.)</p></li>\n<li><p>the .htaccess renaming was a good move, but all that needs to be taken out of there is any <code>http</code>-><code>https</code> rule.</p></li>\n</ul>\n"
}
]
| 2018/03/15 | [
"https://wordpress.stackexchange.com/questions/296956",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128094/"
]
| I'm working on a messy customer project.
To debug it, I would like to work on it on localhost.
I'm using Wampserver.
This is what I did :
1 - I made a virtualhost
**httpd-vhosts.conf**
```
<VirtualHost *:80>
ServerName devfoo.pro
DocumentRoot "c:/path/to/project/src/www"
<Directory "c:/path/to/project/src/www/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
```
2 - I renamed the file `.htaccess` to `_.htaccess`
At that point when I run the page, there is still a redirection from `http://devfoo.pro` to `https://devfoo.pro`.
Notice : If I rename the plugin `really-simple-ssl` to `_really-simple-ssl`, the page redirect to the online website.
So... how can I import a WordPress project on localhost and deactivate the https protocol properly ? (Keeping the https on localhost is so messy! I never manage to simulate https on a local server with or without documentation, tutorials etc... ) | I also had this experience with chrome and firefox, they switch http to https and did not find a way to overcome it, so i used internet explorer in that windows machine.
I don't think you can have ssl on localhost or an ip address, i guess you know it as you used devfoo.pro. SSL certificate could be generated only for fully qualified domain names.
So, you will need to **buy** a certificate to have things working, out of the box. **Easy and "secure"**.
Or you can self sign one for your self, following a tutorial :-). **Might be difficult** and you will need to accept it in your browser or os.
Or better (at least for me), use this [website](http://www.selfsignedcertificate.com/). It will self sign a certificate for a provided domain. |
296,966 | <p>I'm working on a Wordpress theme for a website that makes heavy use of its default media player. In the process of styling its playlists, I found that a core file injects hardcoded characters that can't be made invisible just by using CSS, so I'm a bit clueless about how to hide/remove them. </p>
<p>These characters are injected on 3 different places on each playlist entry:</p>
<ol>
<li>those entries are numbered, but the container is a div instead of an ol, so using list-style-type: none is not possible;</li>
<li>they add curly quotes to the song title, but not by using :before and :after;</li>
<li>and they add an em dash before the artist name, also not by using the :before pseudo-class.</li>
</ol>
<p>On wordpress\wp-includes\js\media.php there's a function called <strong>wp_underscore_playlist_templates</strong> which declares the following script:</p>
<pre><code><script type="text/html" id="tmpl-wp-playlist-item">
<div class="wp-playlist-item">
<a class="wp-playlist-caption" href="{{ data.src }}">
{{ data.index ? ( data.index + '. ' ) : '' }}
<# if ( data.caption ) { #>
{{ data.caption }}
<# } else { #>
<span class="wp-playlist-item-title"><?php
/* translators: playlist item title */
printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{{ data.title }}}' );
?></span>
<# if ( data.artists && data.meta.artist ) { #>
<span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
<# } #>
<# } #>
</a>
<# if ( data.meta.length_formatted ) { #>
<div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
<# } #>
</div>
</script>
</code></pre>
<p>Of course I could edit this core file, but I don't want to do that. So what should I do? Add a filter on functions.php? Make a JS file?</p>
| [
{
"answer_id": 296967,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 4,
"selected": true,
"text": "<p>Inside the shortcode function for playlists, there is this line:</p>\n\n<pre><code>do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );\n</code></pre>\n\n<p>Hooked into that is <code>wp_playlist_scripts()</code> which hooks the templates into the footer:</p>\n\n<pre><code>add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );\nadd_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );\n</code></pre>\n\n<p>So if you want to replace the templates, you can hook into <code>wp_playlist_scripts</code> <em>after</em> those hooks have been added (so any priority greater than 10), remove the hooks, then hook in your own templates:</p>\n\n<pre><code>function wpse_296966_hook_new_playlist_templates() {\n // Unhook default templates.\n remove_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );\n remove_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );\n\n // Hook in new templates.\n add_action( 'wp_footer', 'wpse_296966_underscore_playlist_templates', 0 );\n add_action( 'admin_footer', 'wpse_296966_underscore_playlist_templates', 0 );\n}\nadd_action( 'wp_playlist_scripts', 'wpse_296966_hook_new_playlist_templates', 20 );\n</code></pre>\n\n<p>Then you just need to copy the <code>wp_underscore_playlist_templates()</code> function, in its entirety, to a new function in your theme/plugin called <code>wpse_296966_underscore_playlist_templates()</code> (or whatever you want, just needs to match the <code>add_action()</code> call. Then make any modifications you want to the function to get the markup you wanted.</p>\n\n<p>I would avoid doing anything <em>too</em> drastic though, since the scripts likely depend on specific classes, and the general structure. But removing these unwanted characters shouldn't be a problem.</p>\n"
},
{
"answer_id": 315305,
"author": "Jonas Lundman",
"author_id": 43172,
"author_profile": "https://wordpress.stackexchange.com/users/43172",
"pm_score": 2,
"selected": false,
"text": "<p>For the <strong>title</strong> in question <em>\"they add curly quotes to the song title, but not by using :before and :after;\"</em> and other kind of templates <strong>using gettext calls</strong>, you can filter the javascript templates like this in your functions.php:</p>\n\n<pre><code>add_filter('gettext_with_context', function($translated, $text, $context, $domain){\n if($context = 'playlist item title' && $text == '&#8220;%s&#8221;') $translated = \"%s\";\n return $translated;\n}, 10, 4);\n</code></pre>\n\n<p>Remark the filter name, its differ from context <code>_x(</code> calls vs <code>__(</code> calls.</p>\n\n<p>/If someone struggles with same issues</p>\n"
}
]
| 2018/03/16 | [
"https://wordpress.stackexchange.com/questions/296966",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86030/"
]
| I'm working on a Wordpress theme for a website that makes heavy use of its default media player. In the process of styling its playlists, I found that a core file injects hardcoded characters that can't be made invisible just by using CSS, so I'm a bit clueless about how to hide/remove them.
These characters are injected on 3 different places on each playlist entry:
1. those entries are numbered, but the container is a div instead of an ol, so using list-style-type: none is not possible;
2. they add curly quotes to the song title, but not by using :before and :after;
3. and they add an em dash before the artist name, also not by using the :before pseudo-class.
On wordpress\wp-includes\js\media.php there's a function called **wp\_underscore\_playlist\_templates** which declares the following script:
```
<script type="text/html" id="tmpl-wp-playlist-item">
<div class="wp-playlist-item">
<a class="wp-playlist-caption" href="{{ data.src }}">
{{ data.index ? ( data.index + '. ' ) : '' }}
<# if ( data.caption ) { #>
{{ data.caption }}
<# } else { #>
<span class="wp-playlist-item-title"><?php
/* translators: playlist item title */
printf( _x( '“%s”', 'playlist item title' ), '{{{ data.title }}}' );
?></span>
<# if ( data.artists && data.meta.artist ) { #>
<span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span>
<# } #>
<# } #>
</a>
<# if ( data.meta.length_formatted ) { #>
<div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
<# } #>
</div>
</script>
```
Of course I could edit this core file, but I don't want to do that. So what should I do? Add a filter on functions.php? Make a JS file? | Inside the shortcode function for playlists, there is this line:
```
do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
```
Hooked into that is `wp_playlist_scripts()` which hooks the templates into the footer:
```
add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
```
So if you want to replace the templates, you can hook into `wp_playlist_scripts` *after* those hooks have been added (so any priority greater than 10), remove the hooks, then hook in your own templates:
```
function wpse_296966_hook_new_playlist_templates() {
// Unhook default templates.
remove_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
remove_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
// Hook in new templates.
add_action( 'wp_footer', 'wpse_296966_underscore_playlist_templates', 0 );
add_action( 'admin_footer', 'wpse_296966_underscore_playlist_templates', 0 );
}
add_action( 'wp_playlist_scripts', 'wpse_296966_hook_new_playlist_templates', 20 );
```
Then you just need to copy the `wp_underscore_playlist_templates()` function, in its entirety, to a new function in your theme/plugin called `wpse_296966_underscore_playlist_templates()` (or whatever you want, just needs to match the `add_action()` call. Then make any modifications you want to the function to get the markup you wanted.
I would avoid doing anything *too* drastic though, since the scripts likely depend on specific classes, and the general structure. But removing these unwanted characters shouldn't be a problem. |
296,983 | <p>I want to change heading tags from child theme but i can't figure out how to add filter to parent theme function. </p>
<p>Parent theme function that i want to change:</p>
<pre><code>if(! class_exists('WpkPageHelper')) {
class WpkPageHelper
{
public static function zn_get_subheader( $args = array(), $is_pb_element = false )
{
$config = zn_get_pb_template_config();
self::render_sub_header( $args );
}
public static function render_sub_header( $args = array() )
{
$defaults = array(
'title_tag' => 'h2'
);
}
}
}
</code></pre>
<p>I want the default title_tag value to be 'span'.</p>
| [
{
"answer_id": 296986,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": -1,
"selected": false,
"text": "<p>I do not see you actually calling child_remove_parent_function() in your code.</p>\n\n<p>Another issue to be aware of is timing. It is counter–intuitive, but functions.php files are loaded in order of child first, parent second.</p>\n\n<p>Overall you need to ensure two things: </p>\n\n<ol>\n<li><p>code works at all</p></li>\n<li><p>it is called at the appropriate moment, after parent theme is done\nwith its set up</p></li>\n</ol>\n"
},
{
"answer_id": 297018,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": true,
"text": "<p>There is no filter. To filter a value the developer needs to create a filter by wrapping the filterable value in a call to <code>apply_filters()</code> with a name for that filter. They have not done that. </p>\n\n<p>What they <em>have</em> done is make the <code>WpkPageHelper</code> class <em>pluggable</em>. This means that it's possible for a child theme to replace the entire class. </p>\n\n<p>Before defining the <code>WpkPageHelper</code> class, the parent theme is checking <code>if(! class_exists('WpkPageHelper')) {</code>. This is checking if the class has been defined already and only defining the class if it hasn't been. Because child themes are loaded before parent themes this gives you an opportunity to define <code>WpkPageHelper</code> before the parent theme does. The parent theme will then use your version.</p>\n\n<p>So all you need to do is copy the code for the <code>WpkPageHelper</code> class into your child theme's functions.php file (or another file included in your child theme's functions file) and make the change you want. Just leave out the <code>class_exists()</code> check:</p>\n\n<pre><code>class WpkPageHelper\n{\n public static function zn_get_subheader( $args = array(), $is_pb_element = false )\n {\n $config = zn_get_pb_template_config();\n self::render_sub_header( $args );\n }\n\n public static function render_sub_header( $args = array() )\n {\n $defaults = array(\n 'title_tag' => 'span'\n );\n } \n}\n</code></pre>\n\n<p>This is what WordPress and some themes and plugins are doing when they wrap class and function definitions in conditional statements. You'll occasionally see conditions like <code>if ( ! function_exists( 'function_name' ) ) {</code>. This is WordPress or the theme/plugin giving developers an opportunity to define their own versions of these functions or classes for WordPress or the theme/plugin to use instead of their own.</p>\n"
}
]
| 2018/03/16 | [
"https://wordpress.stackexchange.com/questions/296983",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138751/"
]
| I want to change heading tags from child theme but i can't figure out how to add filter to parent theme function.
Parent theme function that i want to change:
```
if(! class_exists('WpkPageHelper')) {
class WpkPageHelper
{
public static function zn_get_subheader( $args = array(), $is_pb_element = false )
{
$config = zn_get_pb_template_config();
self::render_sub_header( $args );
}
public static function render_sub_header( $args = array() )
{
$defaults = array(
'title_tag' => 'h2'
);
}
}
}
```
I want the default title\_tag value to be 'span'. | There is no filter. To filter a value the developer needs to create a filter by wrapping the filterable value in a call to `apply_filters()` with a name for that filter. They have not done that.
What they *have* done is make the `WpkPageHelper` class *pluggable*. This means that it's possible for a child theme to replace the entire class.
Before defining the `WpkPageHelper` class, the parent theme is checking `if(! class_exists('WpkPageHelper')) {`. This is checking if the class has been defined already and only defining the class if it hasn't been. Because child themes are loaded before parent themes this gives you an opportunity to define `WpkPageHelper` before the parent theme does. The parent theme will then use your version.
So all you need to do is copy the code for the `WpkPageHelper` class into your child theme's functions.php file (or another file included in your child theme's functions file) and make the change you want. Just leave out the `class_exists()` check:
```
class WpkPageHelper
{
public static function zn_get_subheader( $args = array(), $is_pb_element = false )
{
$config = zn_get_pb_template_config();
self::render_sub_header( $args );
}
public static function render_sub_header( $args = array() )
{
$defaults = array(
'title_tag' => 'span'
);
}
}
```
This is what WordPress and some themes and plugins are doing when they wrap class and function definitions in conditional statements. You'll occasionally see conditions like `if ( ! function_exists( 'function_name' ) ) {`. This is WordPress or the theme/plugin giving developers an opportunity to define their own versions of these functions or classes for WordPress or the theme/plugin to use instead of their own. |
296,988 | <pre><code>add_action('admin_menu', 'remove_admin_menu_links');
function remove_admin_menu_links(){
$user = wp_get_current_user();
if( $user && isset($user->user_email) && '[email protected]' == $user->user_email ) {
remove_menu_page('upload.php'); // Media - works(remove)
remove_menu_page( 'gf_edit_forms' ); //Forms - doesn't work(visibile)
remove_menu_page('edit.php?post_type=page'); // Pages - works(removed)
remove_menu_page('wpseo_dashboard'); // SEO - works(remove)
remove_menu_page('admin.php?page=wpseo_dashboard'); // SEO - works(remove)
remove_menu_page('envanto-market'); // Envanto Market - doesn't work(visibile)
remove_menu_page('admin.php?page=envanto-market'); // Envanto Market - doesn't work(visibile)
remove_menu_page('gadwp_settings'); // Google Analytics - doesn't work(visibile)
remove_menu_page('admin.php?page=gadwp_settings'); // Google Analytics - doesn't work(visibile)
}
}
add_action( 'admin_menu', 'remove_admin_menus_links' , 9999 );
</code></pre>
<p>Outlined above shows the action added to remove menu items from a specific admin users menu items.</p>
<p>I cant seem to be able to remove Forms, Envanto Market or Google Analytics. The rest of the menu items have been removed, bit I cant figure out why these few don't appear to moving.</p>
<p>If anyone can see why these menu items are still available?</p>
<p>Also, there is a full list of these menu items still available in the admin_bar_menu, new_Post option at the top of the page. If Anyone can point me in the right direction to remove these too?</p>
<p>I've tried adding to <code>functions.php:</code></p>
<pre><code>// admin_bar_menu hook
add_action('admin_bar_menu', 'update_adminbar', 999);
</code></pre>
<p>and in the <code>/plugins/admin_bar.php :</code></p>
<pre><code><?php
// update toolbar
function update_adminbar($wp_adminbar) {
// remove unnecessary items
$wp_adminbar->remove_node('wp-logo');
$wp_adminbar->remove_node('customize');
$wp_adminbar->remove_node('comments');
$wp_adminbar->remove_node('post-new');
}
?>
</code></pre>
| [
{
"answer_id": 297008,
"author": "Beee",
"author_id": 103402,
"author_profile": "https://wordpress.stackexchange.com/users/103402",
"pm_score": 1,
"selected": true,
"text": "<p>The admin bar is hooked incorrectly.It should be hooked to <code>wp_before_admin_bar_render</code>.</p>\n\n<p>This is what I use (and works):</p>\n\n<pre><code>function alter_admin_bar() {\n global $wp_admin_bar;\n $wp_admin_bar->remove_menu( 'customize' );\n $wp_admin_bar->remove_menu( 'ddw-gravityforms-toolbar' );\n $wp_admin_bar->remove_menu( 'members-new-role' );\n $wp_admin_bar->remove_menu( 'new-media' );\n $wp_admin_bar->remove_menu( 'new-post' );\n $wp_admin_bar->remove_menu( 'new-user' );\n $wp_admin_bar->remove_menu( 'wp-logo' );\n}\nadd_action( 'wp_before_admin_bar_render', 'alter_admin_bar' );\n</code></pre>\n\n<p>Regarding the side menu I don't know. My first guess would be that you're using incorrect identifiers.</p>\n"
},
{
"answer_id": 298365,
"author": "Alin",
"author_id": 140045,
"author_profile": "https://wordpress.stackexchange.com/users/140045",
"pm_score": 1,
"selected": false,
"text": "<p>There's a typo on your callback function name.</p>\n\n<pre><code>add_action( 'admin_menu', 'remove_admin_menus_links' , 9999 );\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>add_action( 'admin_menu', 'remove_admin_menu_links' , 9999 );\n</code></pre>\n\n<p>If you correct that, the action will get fired later and the GADWP menu link will get removed.</p>\n"
}
]
| 2018/03/16 | [
"https://wordpress.stackexchange.com/questions/296988",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136745/"
]
| ```
add_action('admin_menu', 'remove_admin_menu_links');
function remove_admin_menu_links(){
$user = wp_get_current_user();
if( $user && isset($user->user_email) && '[email protected]' == $user->user_email ) {
remove_menu_page('upload.php'); // Media - works(remove)
remove_menu_page( 'gf_edit_forms' ); //Forms - doesn't work(visibile)
remove_menu_page('edit.php?post_type=page'); // Pages - works(removed)
remove_menu_page('wpseo_dashboard'); // SEO - works(remove)
remove_menu_page('admin.php?page=wpseo_dashboard'); // SEO - works(remove)
remove_menu_page('envanto-market'); // Envanto Market - doesn't work(visibile)
remove_menu_page('admin.php?page=envanto-market'); // Envanto Market - doesn't work(visibile)
remove_menu_page('gadwp_settings'); // Google Analytics - doesn't work(visibile)
remove_menu_page('admin.php?page=gadwp_settings'); // Google Analytics - doesn't work(visibile)
}
}
add_action( 'admin_menu', 'remove_admin_menus_links' , 9999 );
```
Outlined above shows the action added to remove menu items from a specific admin users menu items.
I cant seem to be able to remove Forms, Envanto Market or Google Analytics. The rest of the menu items have been removed, bit I cant figure out why these few don't appear to moving.
If anyone can see why these menu items are still available?
Also, there is a full list of these menu items still available in the admin\_bar\_menu, new\_Post option at the top of the page. If Anyone can point me in the right direction to remove these too?
I've tried adding to `functions.php:`
```
// admin_bar_menu hook
add_action('admin_bar_menu', 'update_adminbar', 999);
```
and in the `/plugins/admin_bar.php :`
```
<?php
// update toolbar
function update_adminbar($wp_adminbar) {
// remove unnecessary items
$wp_adminbar->remove_node('wp-logo');
$wp_adminbar->remove_node('customize');
$wp_adminbar->remove_node('comments');
$wp_adminbar->remove_node('post-new');
}
?>
``` | The admin bar is hooked incorrectly.It should be hooked to `wp_before_admin_bar_render`.
This is what I use (and works):
```
function alter_admin_bar() {
global $wp_admin_bar;
$wp_admin_bar->remove_menu( 'customize' );
$wp_admin_bar->remove_menu( 'ddw-gravityforms-toolbar' );
$wp_admin_bar->remove_menu( 'members-new-role' );
$wp_admin_bar->remove_menu( 'new-media' );
$wp_admin_bar->remove_menu( 'new-post' );
$wp_admin_bar->remove_menu( 'new-user' );
$wp_admin_bar->remove_menu( 'wp-logo' );
}
add_action( 'wp_before_admin_bar_render', 'alter_admin_bar' );
```
Regarding the side menu I don't know. My first guess would be that you're using incorrect identifiers. |
296,999 | <p>I am creating a plugin that adds a custom sortable column(Reputation Score) to the users table displayed at admin page > users, the problem is the column's data should be fetched from a MySQL table wp_user_reputation (<code>userid</code>,<code>user_reputation_score</code>) [created for our own purpose].</p>
<p>My assessment is that I would need the column to be present
in query so that I can add sorting capability for it. How do I make make WordPress to join the wp_users table with wp_user_reputation.</p>
<p>I appreciate your help.</p>
| [
{
"answer_id": 297013,
"author": "Florian",
"author_id": 10595,
"author_profile": "https://wordpress.stackexchange.com/users/10595",
"pm_score": 0,
"selected": false,
"text": "<p>You would have to construct a custom MySQL-query to retrieve the sorted <code>userid</code> from your <code>wp_user_reputation</code> table. Then you could use the sorted <code>userid</code>s to construct a <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow noreferrer\"><code>get_users()</code></a> query with <code>'include' => $your_retrieved_ids</code> and <code>'order' => 'include'</code>.</p>\n"
},
{
"answer_id": 297022,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>To avoid a second query just for sorting you could use the <code>pre_user_query</code> hook to support a custom <code>orderby</code> value.</p>\n\n<p>This code will enable sorting users by reputation in a single query just by setting <code>orderby</code> to <code>reputation</code>.</p>\n\n<pre><code>function wpse_296999_pre_user_query( $user_query ) {\n global $wpdb;\n\n $order = $user_query->query_vars['order'];\n $orderby = $user_query->query_vars['orderby'];\n\n // If orderby is 'reputation'.\n if ( 'reputation' === $orderby ) {\n // Join reputation table.\n $user_search->query_from .= \" INNER JOIN {$wpdb->prefix}user_reputation AS reputation ON {$wpdb->users}.ID = reputation.userid\"; \n // And order by it.\n $user_search->query_orderby = \" ORDER BY reputation.user_reputation_score $order\";\n } \n}\nadd_action('pre_user_query','wpse_27518_pre_user_query');\n</code></pre>\n\n<p>Just make sure that on this line:</p>\n\n<pre><code>if ( 'reputation' === $orderby ) {\n</code></pre>\n\n<p><code>'reputation'</code> is whatever the actual name of your sortable column is.</p>\n"
}
]
| 2018/03/16 | [
"https://wordpress.stackexchange.com/questions/296999",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138763/"
]
| I am creating a plugin that adds a custom sortable column(Reputation Score) to the users table displayed at admin page > users, the problem is the column's data should be fetched from a MySQL table wp\_user\_reputation (`userid`,`user_reputation_score`) [created for our own purpose].
My assessment is that I would need the column to be present
in query so that I can add sorting capability for it. How do I make make WordPress to join the wp\_users table with wp\_user\_reputation.
I appreciate your help. | To avoid a second query just for sorting you could use the `pre_user_query` hook to support a custom `orderby` value.
This code will enable sorting users by reputation in a single query just by setting `orderby` to `reputation`.
```
function wpse_296999_pre_user_query( $user_query ) {
global $wpdb;
$order = $user_query->query_vars['order'];
$orderby = $user_query->query_vars['orderby'];
// If orderby is 'reputation'.
if ( 'reputation' === $orderby ) {
// Join reputation table.
$user_search->query_from .= " INNER JOIN {$wpdb->prefix}user_reputation AS reputation ON {$wpdb->users}.ID = reputation.userid";
// And order by it.
$user_search->query_orderby = " ORDER BY reputation.user_reputation_score $order";
}
}
add_action('pre_user_query','wpse_27518_pre_user_query');
```
Just make sure that on this line:
```
if ( 'reputation' === $orderby ) {
```
`'reputation'` is whatever the actual name of your sortable column is. |
297,007 | <p>I am using a premium theme on my page. The theme only accepts one menu in the whole site.</p>
<p>The site is a single page site. And the way the theme works is that we have to set up a Home Page and then use the Menu items in order to make the sections of the site. </p>
<p>So, I created a Menu with all the sections I want to have using pages I created already set up as sections. So for example: I have Home, Photos, Videos, etc. These are individual pages but when I include them as part of the menu they will appear one below the other one in a single page and the menu items will scroll to that anchor on that single page.</p>
<p>Many themes work like that.</p>
<p><strong>My problem is</strong> :</p>
<p>I need to translate the menu OR set up another page (not as section, but a normal independent page) with a different menu with the items linking to anchors on that page and not the Main Page.</p>
<p>I'm asking this mainly because I want to have the site in two different languages. So I have a main page (In English) with a normal Menu and one of the Items of the Menu is not a section but a link to the second language (Spanish). I can easily make a page and declare it as a Single Page and not a section but then, when the menu appears in that page it's in English and those links are linking to the Main Page sections in English.</p>
<p>I already made the translation myself and I want to have my own translation not an automated one. My page is mainly informative and the text almost never changes.</p>
<p>I do not want to pay for the WPML plugin and the other free plug ins out there aren't any good. It's such a simple thing and I can't find a way around it.</p>
| [
{
"answer_id": 297010,
"author": "Interactive",
"author_id": 52240,
"author_profile": "https://wordpress.stackexchange.com/users/52240",
"pm_score": -1,
"selected": false,
"text": "<p>There are good plugins for this without paying...</p>\n\n<p>But you can also (which you should have already) create a child theme.\nAdd another menu in the child functions and create custom links.</p>\n\n<p>Keep in mind that this is extremely high-maintenance.</p>\n\n<p>Besides that this is just a crappy work around</p>\n"
},
{
"answer_id": 297023,
"author": "Florian",
"author_id": 10595,
"author_profile": "https://wordpress.stackexchange.com/users/10595",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure, but if I understand correctly you should create a second menu which is only visible on your Spanish language page.</p>\n\n<pre><code>if (is_page($english_page_id)) {\n wp_nav_menu( array('menu'=>$english_menu) );\n} \nif (is_page($spanish_page_id)) {\n wp_nav_menu( array('menu'=>$spanish_menu) )\n}\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\"><code>is_page()</code></a><br>\n<a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu()</code></a></p>\n"
}
]
| 2018/03/16 | [
"https://wordpress.stackexchange.com/questions/297007",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138772/"
]
| I am using a premium theme on my page. The theme only accepts one menu in the whole site.
The site is a single page site. And the way the theme works is that we have to set up a Home Page and then use the Menu items in order to make the sections of the site.
So, I created a Menu with all the sections I want to have using pages I created already set up as sections. So for example: I have Home, Photos, Videos, etc. These are individual pages but when I include them as part of the menu they will appear one below the other one in a single page and the menu items will scroll to that anchor on that single page.
Many themes work like that.
**My problem is** :
I need to translate the menu OR set up another page (not as section, but a normal independent page) with a different menu with the items linking to anchors on that page and not the Main Page.
I'm asking this mainly because I want to have the site in two different languages. So I have a main page (In English) with a normal Menu and one of the Items of the Menu is not a section but a link to the second language (Spanish). I can easily make a page and declare it as a Single Page and not a section but then, when the menu appears in that page it's in English and those links are linking to the Main Page sections in English.
I already made the translation myself and I want to have my own translation not an automated one. My page is mainly informative and the text almost never changes.
I do not want to pay for the WPML plugin and the other free plug ins out there aren't any good. It's such a simple thing and I can't find a way around it. | I'm not sure, but if I understand correctly you should create a second menu which is only visible on your Spanish language page.
```
if (is_page($english_page_id)) {
wp_nav_menu( array('menu'=>$english_menu) );
}
if (is_page($spanish_page_id)) {
wp_nav_menu( array('menu'=>$spanish_menu) )
}
```
[`is_page()`](https://developer.wordpress.org/reference/functions/is_page/)
[`wp_nav_menu()`](https://developer.wordpress.org/reference/functions/wp_nav_menu/) |
297,024 | <p>I am looking for a way to remove/unhook all assets (css and javascript) files added to customize_controls_enqueue_scripts hook when the query string <code>mo-reset=true</code> is added to the customize url.</p>
| [
{
"answer_id": 297025,
"author": "Beee",
"author_id": 103402,
"author_profile": "https://wordpress.stackexchange.com/users/103402",
"pm_score": 0,
"selected": false,
"text": "<p>Check <a href=\"https://codex.wordpress.org/Function_Reference/wp_deregister_script\" rel=\"nofollow noreferrer\">wp_deregister_script</a>().</p>\n"
},
{
"answer_id": 297084,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <code>global $wp_scripts</code> and <code>global $wp_styles;</code> to get all registerd scripts and styles.</p>\n\n<p>Eg.</p>\n\n<p><a href=\"https://i.stack.imgur.com/7uDac.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7uDac.png\" alt=\"enter image description here\"></a></p>\n\n<p>All <strong>Scripts</strong></p>\n\n<pre><code>// All Scripts\nglobal $wp_scripts;\n\n$all_scripts = array();\n\nforeach( $wp_scripts->registered as $script ) :\n $all_scripts[$script->handle] = $script->src;\nendforeach;\n\n// echo '<pre>';\n// print_r( $all_scripts );\n// echo '</pre>';\n</code></pre>\n\n<p>All <strong>Styles</strong></p>\n\n<pre><code>// All Styles\nglobal $wp_styles;\n\n$all_styles = array();\n\nforeach( $wp_styles->registered as $style ) :\n $all_styles[$style->handle] = $style->src;\nendforeach;\n\n// echo '<pre>';\n// print_r( $all_styles );\n// echo '</pre>';\n</code></pre>\n"
}
]
| 2018/03/16 | [
"https://wordpress.stackexchange.com/questions/297024",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59917/"
]
| I am looking for a way to remove/unhook all assets (css and javascript) files added to customize\_controls\_enqueue\_scripts hook when the query string `mo-reset=true` is added to the customize url. | You can use the `global $wp_scripts` and `global $wp_styles;` to get all registerd scripts and styles.
Eg.
[](https://i.stack.imgur.com/7uDac.png)
All **Scripts**
```
// All Scripts
global $wp_scripts;
$all_scripts = array();
foreach( $wp_scripts->registered as $script ) :
$all_scripts[$script->handle] = $script->src;
endforeach;
// echo '<pre>';
// print_r( $all_scripts );
// echo '</pre>';
```
All **Styles**
```
// All Styles
global $wp_styles;
$all_styles = array();
foreach( $wp_styles->registered as $style ) :
$all_styles[$style->handle] = $style->src;
endforeach;
// echo '<pre>';
// print_r( $all_styles );
// echo '</pre>';
``` |
297,026 | <p>I need to hook after file uploaded to server, get the file path, and then prevent WordPress from saving the attachment post.</p>
<p>I found this filter <code>add_filter('attachment_fields_to_save', 'attachment_stuff');</code> but this is after the attachment post was created, I want to hook before the post save.</p>
<p><strong>Update 26.03.2018</strong></p>
<p>I ended up using a custom media endpoint to save the files without saving a attachment post. Full example below in <a href="https://wordpress.stackexchange.com/a/299006/62909">answer</a> </p>
| [
{
"answer_id": 297032,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Uploading the file and creating an attachment for it is handled by the function <a href=\"https://developer.wordpress.org/reference/functions/media_handle_upload/\" rel=\"nofollow noreferrer\"><code>media_handle_upload</code></a>. As you can see from the source, it first uploads the file, then starts gathering metadata (including some lengthy stuff for audio files) and then calls <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_attachment/\" rel=\"nofollow noreferrer\"><code>wp_insert_attachment</code></a> to create the attachment post. There is no place you can hook into.</p>\n\n<p>The latter function is just a placeholder for <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\"><code>wp_insert_post</code></a>. Here you have quite a lot of hooks to filter metadata. However, there is only one condition preventing the post to be created, where it says <code>if ( ! empty( $import_id ) )</code>. And there's no obvious way to mess with <code>$import_id</code>. So, you're stuck.</p>\n\n<p>Except that a little bit later in the function there is this call: <code>do_action( 'add_attachment', $post_ID );</code>. This fires just after an attachment post has been created. You can use this to immediately delete the post again:</p>\n\n<pre><code>add_action ('add_attachment', 'wpse297026_delete_post');\nfunction wpse297026_delete_post ($post_ID) {\n wp_delete_post ($post_ID);\n }\n</code></pre>\n\n<p>This will leave the uploaded file in its place, but WordPress will have lost track of it.</p>\n"
},
{
"answer_id": 297033,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>Based on your comment you appear to be using the REST API. There's no hook between uploading the file and creating the attachment post that could be used for this purpose in the API endpoint.</p>\n\n<p>The best you can do appears to be to use the <code>rest_insert_attachment</code> action. It provides callback functions with the <code>WP_Post</code> object for the attachment post, and the <code>WP_REST_Request</code> object representing the request. This action is called immediately after the attachment post is created, but before any metadata or sizes are generated. So you would hook into here, check the request for whatever flag you are using to identify media that shouldn't get saved as a post, get the path, then delete the attachment post.</p>\n\n<pre><code>function wpse_297026_rest_insert_attachment( $attachment, $request, $creating ) {\n // Only handle new attachments.\n if ( ! $creating ) {\n return;\n }\n\n // Check for parameter on request that tells us not to create an attachment post.\n if ( $request->get_param( 'flag' ) == true ) {\n // Get file path.\n $file = get_attached_file( $attachment->ID );\n\n // Do whatever you need to with the file path.\n\n // Delete attachment post.\n wp_delete_post( $attachment->ID );\n\n // Kill the request and send a 201 response.\n wp_die('', '', 201);\n }\n}\nadd_action( 'rest_insert_attachment', 'wpse_297026_rest_insert_attachment' )\n</code></pre>\n\n<p>I think it needs to be pointed out that if you're not creating attachments then you shouldn't be using the attachment endpoint. This is why we have to awkwardly kill the request in that code. Everything after <code>rest_insert_attachment</code> assumes the existence of an attachment post and most of the code for the controller for that endpoint is dedicated to creating and managing data that only makes sense for an attachment post. You should probably be creating your own endpoint for this sort of work.</p>\n"
},
{
"answer_id": 299006,
"author": "BenB",
"author_id": 62909,
"author_profile": "https://wordpress.stackexchange.com/users/62909",
"pm_score": 2,
"selected": false,
"text": "<p>I ended up using the code from wp media endpoint in a custom endpoint without saving the post part.</p>\n\n<p>Here is full example on twentyseventeen-child theme in case someone will need this.</p>\n\n<ol>\n<li><p>Add this to functions.php</p>\n\n<pre><code>$Custom_Media_Uploader = new Custom_Media_Uploader();\n$Custom_Media_Uploader->init();\n\nclass Custom_Media_Uploader {\n\n function init() {\n add_action( 'rest_api_init', [ $this, 'register_routes' ] );\n\n }\n\n\n function register_routes() {\n $version = '1';\n $namespace = 'custom-end-point/v' . $version;\n $base = 'media';\n register_rest_route( $namespace, '/' . $base, array(\n [\n 'methods' => WP_REST_Server::CREATABLE,\n 'callback' => [ $this, 'upload_file' ],\n 'permission_callback' => [ $this, 'file_upload_permissions' \n ],\n 'args' => [],\n ]\n ) );\n}\n\n function file_upload_permissions() {\n return is_user_logged_in();\n }\n\n function upload_file( $request ) {\n $params = $request->get_params();\n\n if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array(\n 'revision',\n 'attachment'\n ), true )\n ) {\n return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) );\n }\n // Get the file via $_FILES or raw data.\n $files = $request->get_file_params();\n $headers = $request->get_headers();\n if ( ! empty( $files ) ) {\n $file = $this->upload_from_file( $files, $headers );\n } else {\n $file = $this->upload_from_data( $request->get_body(), $headers );\n }\n if ( is_wp_error( $file ) ) {\n return $file;\n }\n $name = basename( $file['file'] );\n $name_parts = pathinfo( $name );\n $name = trim( substr( $name, 0, - ( 1 + strlen( $name_parts['extension'] ) ) ) );\n $url = $file['url'];\n $type = $file['type'];\n $file = $file['file'];\n\n return [ 'url' => $url, 'type' => $type ];\n }\n\n\n/**\n * Handles an upload via multipart/form-data ($_FILES).\n *\n * @since 4.7.0\n *\n * @param array $files Data from the `$_FILES` superglobal.\n * @param array $headers HTTP headers from the request.\n *\n * @return array|WP_Error Data from wp_handle_upload().\n */\n protected function upload_from_file( $files, $headers ) {\n\n if ( empty( $files ) ) {\n return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) );\n }\n// Verify hash, if given.\n if ( ! empty( $headers['content_md5'] ) ) {\n $content_md5 = array_shift( $headers['content_md5'] );\n $expected = trim( $content_md5 );\n $actual = md5_file( $files['file']['tmp_name'] );\n if ( $expected !== $actual ) {\n return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );\n }\n }\n // Pass off to WP to handle the actual upload.\n $overrides = array(\n 'test_form' => false,\n );\n // Bypasses is_uploaded_file() when running unit tests.\n if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {\n $overrides['action'] = 'wp_handle_mock_upload';\n }\n /** Include admin functions to get access to wp_handle_upload() */\n require_once ABSPATH . 'wp-admin/includes/admin.php';\n $file = wp_handle_upload( $files['file'], $overrides );\n if ( isset( $file['error'] ) ) {\n return new WP_Error( 'rest_upload_unknown_error', $file['error'], array( 'status' => 500 ) );\n }\n\n return $file;\n }\n}\n</code></pre></li>\n</ol>\n\n<p></p>\n\n<ol start=\"2\">\n<li><p>create a file on root of theme with the name page-upload.php </p>\n\n<pre><code><?php get_header(); ?>\n <div class=\"wrap\">\n <div id=\"primary\" class=\"content-area\">\n <main id=\"main\" class=\"site-main\" role=\"main\">\n <input type='file' onchange=\"uploadFile(this);\"/>\n <div style=\"display:none\" id=\"ajax-response\">\n <div><b>File URL: </b><span id=\"file-url\"></span></div>\n <div><b>File type: </b><span id=\"file-type\"></span></div>\n <div></div>\n </div>\n </main><!-- #main -->\n </div><!-- #primary -->\n</div><!-- .wrap -->\n\n<script>\nfunction uploadFile(input) {\n if (input.files && input.files[0]) {\n var file = input.files[0];\n var formData = new FormData();\n formData.append('file', file);\n\n // Fire the request.\n jQuery.ajax({\n url: '<?php echo esc_url_raw( rest_url() ) ?>custom-end-point/v1/media',\n method: 'POST',\n processData: false,\n contentType: false,\n beforeSend: function (xhr) {\n xhr.setRequestHeader('X-WP-Nonce', '<?php echo wp_create_nonce( 'wp_rest' ) ?>');\n },\n data: formData\n }).success(function (response) {\n jQuery('#file-url').text(response.url);\n jQuery('#file-type').text(response.type);\n jQuery('#ajax-response').show();\n console.log(response);\n }).error(function (response) {\n console.log(response);\n });\n\n }\n}\n</script>\n\n<?php get_footer();\n</code></pre></li>\n<li><p>Create and save a page with the title \"upload\" and navigate to it www.domain.com/upload, upload a file and you could see the returned URL and file type from the media endpoint after uploading a file.</p></li>\n</ol>\n\n<p>Ensure you logged in and permalinks are set to post-name to allow the end point to function.</p>\n"
}
]
| 2018/03/16 | [
"https://wordpress.stackexchange.com/questions/297026",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62909/"
]
| I need to hook after file uploaded to server, get the file path, and then prevent WordPress from saving the attachment post.
I found this filter `add_filter('attachment_fields_to_save', 'attachment_stuff');` but this is after the attachment post was created, I want to hook before the post save.
**Update 26.03.2018**
I ended up using a custom media endpoint to save the files without saving a attachment post. Full example below in [answer](https://wordpress.stackexchange.com/a/299006/62909) | Based on your comment you appear to be using the REST API. There's no hook between uploading the file and creating the attachment post that could be used for this purpose in the API endpoint.
The best you can do appears to be to use the `rest_insert_attachment` action. It provides callback functions with the `WP_Post` object for the attachment post, and the `WP_REST_Request` object representing the request. This action is called immediately after the attachment post is created, but before any metadata or sizes are generated. So you would hook into here, check the request for whatever flag you are using to identify media that shouldn't get saved as a post, get the path, then delete the attachment post.
```
function wpse_297026_rest_insert_attachment( $attachment, $request, $creating ) {
// Only handle new attachments.
if ( ! $creating ) {
return;
}
// Check for parameter on request that tells us not to create an attachment post.
if ( $request->get_param( 'flag' ) == true ) {
// Get file path.
$file = get_attached_file( $attachment->ID );
// Do whatever you need to with the file path.
// Delete attachment post.
wp_delete_post( $attachment->ID );
// Kill the request and send a 201 response.
wp_die('', '', 201);
}
}
add_action( 'rest_insert_attachment', 'wpse_297026_rest_insert_attachment' )
```
I think it needs to be pointed out that if you're not creating attachments then you shouldn't be using the attachment endpoint. This is why we have to awkwardly kill the request in that code. Everything after `rest_insert_attachment` assumes the existence of an attachment post and most of the code for the controller for that endpoint is dedicated to creating and managing data that only makes sense for an attachment post. You should probably be creating your own endpoint for this sort of work. |
297,041 | <p>Let me give you a scenario of what I'm trying to do. I have a custom post type "customer" and I can go in and "add new customer". Here I see my custom fields such as name, logo, review, etc. The problem is Wordpress generates a URL for this. This isn't meant to be a page so I just redirect all of my <a href="http://website.com/customers/" rel="noreferrer">http://website.com/customers/</a>* to somewhere else so that no one goes to these pages (for now).</p>
<p>Is there a way when registering my custom post types in the functions.php file (or some other way) to tell Wordpress to not generate a URL / actual page for it? It's really just a slot to hold my data.</p>
<p>My thoughts were maybe it has to do with:
'capability_type' => 'post',
or something similar that I'm over looking.</p>
<p>THANKS!</p>
| [
{
"answer_id": 297042,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 3,
"selected": false,
"text": "<p>One of the parameters for <code>register_post_type()</code> is <code>publicly_queryable</code>. Simply set this to false to prevent individual page creation. You may also wish to exclude from search, etc.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n\n<p>In the example given in the WP Codex, you can see this parameter is set to <code>true</code>. Depending on your exact needs, you can hide the post type altogether with the <code>public</code> param or control levels of visibility with the explicit parameters, such pas <code>publicly_queryable</code>.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Example\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type#Example</a></p>\n\n<p><strong>Example code from WP Codex</strong></p>\n\n<pre><code>add_action( 'init', 'codex_book_init' );\n/**\n * Register a book post type.\n *\n * @link http://codex.wordpress.org/Function_Reference/register_post_type\n */\nfunction codex_book_init() {\n $labels = array( /*removed for example*/ );\n\n $args = array(\n 'labels' => $labels,\n 'description' => __( 'Description.', 'your-plugin-textdomain' ),\n 'public' => true,\n 'publicly_queryable' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'book' ),\n 'capability_type' => 'post',\n 'has_archive' => true,\n 'hierarchical' => false,\n 'menu_position' => null,\n 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )\n );\n\n register_post_type( 'book', $args );\n}\n</code></pre>\n\n<p><strong>Post Type Archive</strong>\nIt is important to note here that setting publicly_queryable to false will also hide the archive page of that post type. In the example code above for the post type <code>book</code>, the archive page at <a href=\"https://yourdomain.com/book\" rel=\"noreferrer\">https://yourdomain.com/book</a> would also be removed.</p>\n"
},
{
"answer_id": 297049,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>will repeat what @jdm2112 said in (hopefully) clearer english and no code at all ;)</p>\n\n<p>Basically what you are looking for is a private CPT. This kind of CPT is useful for storing data in the DB in similar way to posts which gives you the advantage of (optional) still getting the same type of admin interface, and use the same query, meta and term APIs on it.</p>\n\n<p>\"Private\" is actually a misleading word, it is not that the content is private, but that wordpress will not try to publish it on the front end by itself. You can, if you want to, display the content on the front end but you will need to write the code for that by yourself. In your specific case a simplistic way to do that is to create a page template which displays all the posts in that CPT. This way you have flexible control on the address of the page and whatever SEO you might want to do in it.</p>\n\n<p>Just keep in mind that there is a lot of default functionality you might need to reinvent, and it might be simpler to just have the CPT public, and have a sort of \"see more clients\" call to action on the single CPT pages. </p>\n"
},
{
"answer_id": 297050,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": true,
"text": "<p>OK, so there are some arguments of <code>register_post_type</code> that you should use.</p>\n\n<p>The crucial arguments for you are:</p>\n\n<ul>\n<li><p><code>public</code> - Controls how the type is visible to authors (<code>show_in_nav_menus</code>, <code>show_ui</code>) and readers (<code>exclude_from_search</code>, <code>publicly_queryable</code>). If it's false, then <code>exclude_from_search</code> will be true, <code>publicly_queryable</code> -\nfalse, <code>show_in_nav_menus</code> - false, and <code>show_ui</code> - false. <strong>So the CPT will be hidden all the way.</strong></p></li>\n<li><p><code>exclude_from_search</code> - Whether to exclude posts with this post type from front end search results. Default: value of the opposite of <code>public</code> argument.</p></li>\n<li><p><code>publicly_queryable</code> - Whether queries can be performed on the front end as part of parse_request(). Default: value of <code>public</code> argument. <strong>So we have to et it true.</strong></p></li>\n<li><p>show_ui - Whether to generate a default UI for managing this post type in the admin. Default: value of <code>public</code> argument.</p></li>\n<li><p><code>rewrite</code> - Triggers the handling of rewrites for this post type. To prevent rewrites, set to false. Default: true and use $post_type as slug. <strong>So we have to set it false.</strong></p></li>\n</ul>\n\n<p>Below you can find the code:</p>\n\n<pre><code>$labels = array( /*removed for example*/ );\n\n$args = array(\n 'labels' => $labels,\n 'description' => __( 'Description.', 'your-plugin-textdomain' ),\n 'public' => false,\n 'show_ui' => true,\n 'rewrite' => false,\n 'capability_type' => 'post',\n 'hierarchical' => false,\n /* ... Any other arguments like menu_icon, and so on */\n 'supports' => array( /* list of supported fields */ )\n);\n\nregister_post_type( 'customer', $args );\n</code></pre>\n\n<p>This generator maybe helpful, if you don't want to learn all the arguments:\n<a href=\"https://generatewp.com/post-type/\" rel=\"noreferrer\">https://generatewp.com/post-type/</a></p>\n\n<p>And the list of all arguments, as always, you can find in Codex:\n<a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n"
}
]
| 2018/03/16 | [
"https://wordpress.stackexchange.com/questions/297041",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135049/"
]
| Let me give you a scenario of what I'm trying to do. I have a custom post type "customer" and I can go in and "add new customer". Here I see my custom fields such as name, logo, review, etc. The problem is Wordpress generates a URL for this. This isn't meant to be a page so I just redirect all of my <http://website.com/customers/>\* to somewhere else so that no one goes to these pages (for now).
Is there a way when registering my custom post types in the functions.php file (or some other way) to tell Wordpress to not generate a URL / actual page for it? It's really just a slot to hold my data.
My thoughts were maybe it has to do with:
'capability\_type' => 'post',
or something similar that I'm over looking.
THANKS! | OK, so there are some arguments of `register_post_type` that you should use.
The crucial arguments for you are:
* `public` - Controls how the type is visible to authors (`show_in_nav_menus`, `show_ui`) and readers (`exclude_from_search`, `publicly_queryable`). If it's false, then `exclude_from_search` will be true, `publicly_queryable` -
false, `show_in_nav_menus` - false, and `show_ui` - false. **So the CPT will be hidden all the way.**
* `exclude_from_search` - Whether to exclude posts with this post type from front end search results. Default: value of the opposite of `public` argument.
* `publicly_queryable` - Whether queries can be performed on the front end as part of parse\_request(). Default: value of `public` argument. **So we have to et it true.**
* show\_ui - Whether to generate a default UI for managing this post type in the admin. Default: value of `public` argument.
* `rewrite` - Triggers the handling of rewrites for this post type. To prevent rewrites, set to false. Default: true and use $post\_type as slug. **So we have to set it false.**
Below you can find the code:
```
$labels = array( /*removed for example*/ );
$args = array(
'labels' => $labels,
'description' => __( 'Description.', 'your-plugin-textdomain' ),
'public' => false,
'show_ui' => true,
'rewrite' => false,
'capability_type' => 'post',
'hierarchical' => false,
/* ... Any other arguments like menu_icon, and so on */
'supports' => array( /* list of supported fields */ )
);
register_post_type( 'customer', $args );
```
This generator maybe helpful, if you don't want to learn all the arguments:
<https://generatewp.com/post-type/>
And the list of all arguments, as always, you can find in Codex:
<https://codex.wordpress.org/Function_Reference/register_post_type> |
297,059 | <p>I've written a class to play about with ajax. I had originally used <code>check_admin_referer</code> (in <code>hello()</code>) without arguments but got this warning: "PHP Notice: check_admin_referer was called <strong>incorrectly</strong>. You should specify a nonce action to be verified by using the first parameter."</p>
<p>So I headed to the codex and have tried to follow the <a href="https://codex.wordpress.org/Function_Reference/check_admin_referer" rel="nofollow noreferrer">example</a>. However, the check fails. I'm now getting a <code>403</code>.</p>
<p>Here is my class:</p>
<pre><code>class StupidClass {
private $settings_page;
// scripts,
public function __construct(){
add_action('admin_menu', array($this, 'add_menu'));
add_action('admin_enqueue_scripts', array($this, 'load_scripts'));
add_action('wp_ajax_hello', array($this, 'hello'));
}
// setup
public function add_menu(){
$this->settings_page = add_menu_page( 'Menu item', 'settings page', 'edit_pages', 'settingspage', array($this, 'render_page'), false, 62 );
}
public function load_scripts($hook){
if ($this->settings_page !== $hook) {
return;
}
$path = plugin_dir_url( __FILE__ ) . 'stupid.js';
wp_enqueue_script( 'stupid_js', $path, array('jquery'));
}
// view
public function render_page(){
?>
<h1>This is the title</h1>
<form action="" id="stupid_form" method="post">
<?php wp_nonce_field('hello', 'token'); ?>
<input type="submit" value="hit me">
</form>
<div id="response"></div>
<?php
}
public function hello(){
check_admin_referer('hello', 'token');
wp_die();
}
}
</code></pre>
<p>The only reason I can think of is that the action name is incorrect because I am not pointing to the instance method but I'm new to PHP and WP, and my Google foo is failing me.</p>
<p>What am I doing wrong. How do I get <code>check_admin_referer()</code> to pass?</p>
<p><strong>Update</strong></p>
<p>Here is the JS:</p>
<pre><code>jQuery(document).ready(function($){
data = {
action: 'hello'
}
$('#stupid_form').submit(function(){
$.post(ajaxurl, data, function(response){
$('#response').html(response);
});
return false;
});
});
</code></pre>
| [
{
"answer_id": 298099,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>In the JS script, include the <em>nonce</em> in <code>data</code>, as in the following example:</p>\n\n<pre><code>jQuery(document).ready(function($){\n data = {\n action: 'hello',\n token: $( '#token' ).val()\n }\n $('#stupid_form').submit(function(){\n $.post(ajaxurl, data, function(response){\n $('#response').html(response);\n });\n return false;\n });\n});\n</code></pre>\n\n<p><strong>Additional Note</strong></p>\n\n<pre><code><?php wp_nonce_field('hello', 'token'); ?>\n</code></pre>\n\n<p>generates a hidden <code>input</code> with a markup similar to:</p>\n\n<pre><code><input type=\"hidden\" id=\"token\" name=\"token\" value=\"d9e3867a0e\" />\n</code></pre>\n\n<p>i.e. the <em>nonce name</em> becomes the <code>name</code> as well as <code>id</code> of the <code>input</code>.</p>\n\n<p>That explains the <code>token: $( '#token' ).val()</code> in the code I provided, where the format is <code>NONCE_NAME: $( '#NONCE_NAME' ).val()</code>.</p>\n\n<p>However, you may also target the <code>name</code> like so: <code>token: $( 'input[name=\"token\"]' ).val()</code></p>\n"
},
{
"answer_id": 298103,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>As the name implies <code>check_admin_referer</code> checks that the referer was an admin page. Wordpress usually will add a referer field as an hidden input to the admin forms, and you can do the same, but basically it should just not be used in AJAX unless your ajax is limited to admin side. Just use nonce verification instead. </p>\n\n<p>In any case die-ing (which is what <code>check_admin_referer</code> does) is not the best strategy when handling AJAX requests and you most likely will want to have some more customized \"error\" indication and message.</p>\n"
}
]
| 2018/03/17 | [
"https://wordpress.stackexchange.com/questions/297059",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74293/"
]
| I've written a class to play about with ajax. I had originally used `check_admin_referer` (in `hello()`) without arguments but got this warning: "PHP Notice: check\_admin\_referer was called **incorrectly**. You should specify a nonce action to be verified by using the first parameter."
So I headed to the codex and have tried to follow the [example](https://codex.wordpress.org/Function_Reference/check_admin_referer). However, the check fails. I'm now getting a `403`.
Here is my class:
```
class StupidClass {
private $settings_page;
// scripts,
public function __construct(){
add_action('admin_menu', array($this, 'add_menu'));
add_action('admin_enqueue_scripts', array($this, 'load_scripts'));
add_action('wp_ajax_hello', array($this, 'hello'));
}
// setup
public function add_menu(){
$this->settings_page = add_menu_page( 'Menu item', 'settings page', 'edit_pages', 'settingspage', array($this, 'render_page'), false, 62 );
}
public function load_scripts($hook){
if ($this->settings_page !== $hook) {
return;
}
$path = plugin_dir_url( __FILE__ ) . 'stupid.js';
wp_enqueue_script( 'stupid_js', $path, array('jquery'));
}
// view
public function render_page(){
?>
<h1>This is the title</h1>
<form action="" id="stupid_form" method="post">
<?php wp_nonce_field('hello', 'token'); ?>
<input type="submit" value="hit me">
</form>
<div id="response"></div>
<?php
}
public function hello(){
check_admin_referer('hello', 'token');
wp_die();
}
}
```
The only reason I can think of is that the action name is incorrect because I am not pointing to the instance method but I'm new to PHP and WP, and my Google foo is failing me.
What am I doing wrong. How do I get `check_admin_referer()` to pass?
**Update**
Here is the JS:
```
jQuery(document).ready(function($){
data = {
action: 'hello'
}
$('#stupid_form').submit(function(){
$.post(ajaxurl, data, function(response){
$('#response').html(response);
});
return false;
});
});
``` | In the JS script, include the *nonce* in `data`, as in the following example:
```
jQuery(document).ready(function($){
data = {
action: 'hello',
token: $( '#token' ).val()
}
$('#stupid_form').submit(function(){
$.post(ajaxurl, data, function(response){
$('#response').html(response);
});
return false;
});
});
```
**Additional Note**
```
<?php wp_nonce_field('hello', 'token'); ?>
```
generates a hidden `input` with a markup similar to:
```
<input type="hidden" id="token" name="token" value="d9e3867a0e" />
```
i.e. the *nonce name* becomes the `name` as well as `id` of the `input`.
That explains the `token: $( '#token' ).val()` in the code I provided, where the format is `NONCE_NAME: $( '#NONCE_NAME' ).val()`.
However, you may also target the `name` like so: `token: $( 'input[name="token"]' ).val()` |
297,063 | <p>I am creating a clothing store. The clothing are variable products based on size (xs, s, m, l, xl etc..). I am trying to create filters to display products that are in stock, based on a filter. So, clicking the "xs" filter should show products that both have the XS variation, and have that variation in stock.</p>
<p>So far, I've got something like this:</p>
<pre><code>$query_args = array(
'post_type' => 'product', 'product_variation',
'posts_per_page' => 12,
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'pa_sizes',
'field' => 'term_id',
'terms' => 'xs',
),
),
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'outofstock',
'compare' => '='
),
)
);
$query = new WP_Query($query_args);
</code></pre>
<p>I know right now it's searching for "outofstock" but that was just a test, and not even this comes up with any products, even though I have created some products with some sizes out of stock.</p>
| [
{
"answer_id": 298099,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>In the JS script, include the <em>nonce</em> in <code>data</code>, as in the following example:</p>\n\n<pre><code>jQuery(document).ready(function($){\n data = {\n action: 'hello',\n token: $( '#token' ).val()\n }\n $('#stupid_form').submit(function(){\n $.post(ajaxurl, data, function(response){\n $('#response').html(response);\n });\n return false;\n });\n});\n</code></pre>\n\n<p><strong>Additional Note</strong></p>\n\n<pre><code><?php wp_nonce_field('hello', 'token'); ?>\n</code></pre>\n\n<p>generates a hidden <code>input</code> with a markup similar to:</p>\n\n<pre><code><input type=\"hidden\" id=\"token\" name=\"token\" value=\"d9e3867a0e\" />\n</code></pre>\n\n<p>i.e. the <em>nonce name</em> becomes the <code>name</code> as well as <code>id</code> of the <code>input</code>.</p>\n\n<p>That explains the <code>token: $( '#token' ).val()</code> in the code I provided, where the format is <code>NONCE_NAME: $( '#NONCE_NAME' ).val()</code>.</p>\n\n<p>However, you may also target the <code>name</code> like so: <code>token: $( 'input[name=\"token\"]' ).val()</code></p>\n"
},
{
"answer_id": 298103,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>As the name implies <code>check_admin_referer</code> checks that the referer was an admin page. Wordpress usually will add a referer field as an hidden input to the admin forms, and you can do the same, but basically it should just not be used in AJAX unless your ajax is limited to admin side. Just use nonce verification instead. </p>\n\n<p>In any case die-ing (which is what <code>check_admin_referer</code> does) is not the best strategy when handling AJAX requests and you most likely will want to have some more customized \"error\" indication and message.</p>\n"
}
]
| 2018/03/17 | [
"https://wordpress.stackexchange.com/questions/297063",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94213/"
]
| I am creating a clothing store. The clothing are variable products based on size (xs, s, m, l, xl etc..). I am trying to create filters to display products that are in stock, based on a filter. So, clicking the "xs" filter should show products that both have the XS variation, and have that variation in stock.
So far, I've got something like this:
```
$query_args = array(
'post_type' => 'product', 'product_variation',
'posts_per_page' => 12,
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'pa_sizes',
'field' => 'term_id',
'terms' => 'xs',
),
),
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'outofstock',
'compare' => '='
),
)
);
$query = new WP_Query($query_args);
```
I know right now it's searching for "outofstock" but that was just a test, and not even this comes up with any products, even though I have created some products with some sizes out of stock. | In the JS script, include the *nonce* in `data`, as in the following example:
```
jQuery(document).ready(function($){
data = {
action: 'hello',
token: $( '#token' ).val()
}
$('#stupid_form').submit(function(){
$.post(ajaxurl, data, function(response){
$('#response').html(response);
});
return false;
});
});
```
**Additional Note**
```
<?php wp_nonce_field('hello', 'token'); ?>
```
generates a hidden `input` with a markup similar to:
```
<input type="hidden" id="token" name="token" value="d9e3867a0e" />
```
i.e. the *nonce name* becomes the `name` as well as `id` of the `input`.
That explains the `token: $( '#token' ).val()` in the code I provided, where the format is `NONCE_NAME: $( '#NONCE_NAME' ).val()`.
However, you may also target the `name` like so: `token: $( 'input[name="token"]' ).val()` |
297,069 | <p>I use the All In One Seo Pack on my multisite, but this plugin have admin pages, what is not fall under the rule what restrict the plugin pages from my users, so I using the <code>remove_cap( $cap );</code> about 'edit_plugins', 'install_plugins', 'upload_plugins', but this not solving my issue. I want restrict this pages on my network's subsites:</p>
<pre><code> wp-admin/admin.php?page=all-in-one-seo-pack%2Faioseop_class.php
wp-admin/admin.php?page=all-in-one-seo-pack%2Fmodules%2Faioseop_performance.php
wp-admin/admin.php?page=all-in-one-seo-pack%2Fmodules%2Faioseop_sitemap.php
</code></pre>
| [
{
"answer_id": 297078,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 1,
"selected": false,
"text": "<p>To remove from the admin menu, you could use <a href=\"https://codex.wordpress.org/Function_Reference/remove_menu_page\" rel=\"nofollow noreferrer\">remove_menu_page()</a>: </p>\n\n<pre><code>add_action( 'admin_menu', function ( ) {\n if (is_super_admin()) \n return;\n remove_menu_page();\n // or remove_submenu_page( ...\n},99);\n</code></pre>\n\n<p>If for some reason the page still exists, it's just missing it's menu link, you could check the <a href=\"https://codex.wordpress.org/Function_Reference/get_current_screen\" rel=\"nofollow noreferrer\">get_current_screen()</a> to see if the page is being viewed, and prevent access:</p>\n\n<pre><code>add_action( 'admin_notices', function ( ) {\n if (is_super_admin()) \n return;\n $screen = get_current_screen();\n if ($screen->parent_base == 'all-in-one-seo-pack') { // or wtv\n wp_die('get out');\n }\n},99);\n</code></pre>\n"
},
{
"answer_id": 298359,
"author": "Galgóczi Levente",
"author_id": 134567,
"author_profile": "https://wordpress.stackexchange.com/users/134567",
"pm_score": 1,
"selected": true,
"text": "<p>You can restrict any pages from your users with this code, you can know only an any part of the url. (The example restrict the all pages of AIOSP (so the all url-s on the backend what associated with the keys: all-in-one-seo-pack or aioseop) what are wriggle out of from the <code>remove_cap( 'edit_plugins', 'install_plugins', 'upload_plugins' );</code> rules):</p>\n\n<pre><code> add_action( 'current_screen', 'restrict_screen' );\n function restrict_screen() {\n if ( is_admin() ) {\n if (is_super_admin()) \n return;\n $current_screen = \"https://\".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];\n $find_restrict = 'all-in-one-seo-pack';\n $find_restrict2 = 'aioseop';\n $match = strpos( $current_screen, $find_restrict );\n $match2 = strpos( $current_screen, $find_restrict2 );\n if( $match == TRUE || $match2 == TRUE ) {\n // wp_die('get out');\n $current_admin = get_admin_url() . 'index.php';\n header('Location: ' . $current_admin . '', true, 301);\n }\n } \n }\n</code></pre>\n\n<p>If you want using this code to an another url, rewrite the $find_restrict, $find_restrict2 to your url's part keys or add new \"find_restrict\" to the code. This code redirect your users to their current site's backend index. (Or you can use the <code>wp_die('get out');</code>)</p>\n"
}
]
| 2018/03/17 | [
"https://wordpress.stackexchange.com/questions/297069",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134567/"
]
| I use the All In One Seo Pack on my multisite, but this plugin have admin pages, what is not fall under the rule what restrict the plugin pages from my users, so I using the `remove_cap( $cap );` about 'edit\_plugins', 'install\_plugins', 'upload\_plugins', but this not solving my issue. I want restrict this pages on my network's subsites:
```
wp-admin/admin.php?page=all-in-one-seo-pack%2Faioseop_class.php
wp-admin/admin.php?page=all-in-one-seo-pack%2Fmodules%2Faioseop_performance.php
wp-admin/admin.php?page=all-in-one-seo-pack%2Fmodules%2Faioseop_sitemap.php
``` | You can restrict any pages from your users with this code, you can know only an any part of the url. (The example restrict the all pages of AIOSP (so the all url-s on the backend what associated with the keys: all-in-one-seo-pack or aioseop) what are wriggle out of from the `remove_cap( 'edit_plugins', 'install_plugins', 'upload_plugins' );` rules):
```
add_action( 'current_screen', 'restrict_screen' );
function restrict_screen() {
if ( is_admin() ) {
if (is_super_admin())
return;
$current_screen = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$find_restrict = 'all-in-one-seo-pack';
$find_restrict2 = 'aioseop';
$match = strpos( $current_screen, $find_restrict );
$match2 = strpos( $current_screen, $find_restrict2 );
if( $match == TRUE || $match2 == TRUE ) {
// wp_die('get out');
$current_admin = get_admin_url() . 'index.php';
header('Location: ' . $current_admin . '', true, 301);
}
}
}
```
If you want using this code to an another url, rewrite the $find\_restrict, $find\_restrict2 to your url's part keys or add new "find\_restrict" to the code. This code redirect your users to their current site's backend index. (Or you can use the `wp_die('get out');`) |
298,111 | <p>Currently I am using <code>AJAX</code> to request a simple <code>JSON</code> response from an external API. The problem is, that the API key is exposed. I'm aware the best method is to process this through <code>admin-ajax</code> and set call the url through PHP. What is the most secure method to do this, and how can this be requested through PHP?</p>
<pre><code>$.ajax({
type: "GET",
url: "https://link.to/api/v2/link?time=day&key=(APIKEYHERE)&response_type=json",
data: dataString,
dataType: "json",
//if received a response from the server
success: function(response) {
console.log(response);
},
});
</code></pre>
| [
{
"answer_id": 298112,
"author": "JBoulhous",
"author_id": 137648,
"author_profile": "https://wordpress.stackexchange.com/users/137648",
"pm_score": 0,
"selected": false,
"text": "<p><strong>It depends on what the external API offers</strong>, basically <strong>read/write access</strong> to some data.<br>\nI think: </p>\n\n<ul>\n<li>If your website visitor is <strong>allowed</strong> those access/permissions on that data, it is <strong>ok</strong>. </li>\n<li>If your website visitor is <strong>not allowed</strong> those access/permissions on that data, it is <strong>not ok</strong>.</li>\n</ul>\n\n<p>Think of Google and Facebook, they provide <strong>app</strong> and <strong>user</strong> api keys.<br>\nThat will depends on your use case.<br>\nBut i can say that <strong>if the external API data access is sensible you should do that on the server and go throw <code>AJAX</code> or <code>REST</code></strong>.</p>\n"
},
{
"answer_id": 298145,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>I would break this problem in to 2 parts.</p>\n\n<p>First, you could sent an Ajax request to your server, sending only the <code>dataString</code> variable. </p>\n\n<p>Then, you can use either <code>cURL</code> or <a href=\"https://codex.wordpress.org/Function_Reference/wp_remote_get\" rel=\"nofollow noreferrer\"><code>wp_remote_get()</code></a> on the server to access the real API.</p>\n\n<p>This could be the only solution, if you want to avoid playing hide and seek with hashes and writing tons of code just to make it hard for the users to find the API key.</p>\n"
}
]
| 2018/03/17 | [
"https://wordpress.stackexchange.com/questions/298111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87036/"
]
| Currently I am using `AJAX` to request a simple `JSON` response from an external API. The problem is, that the API key is exposed. I'm aware the best method is to process this through `admin-ajax` and set call the url through PHP. What is the most secure method to do this, and how can this be requested through PHP?
```
$.ajax({
type: "GET",
url: "https://link.to/api/v2/link?time=day&key=(APIKEYHERE)&response_type=json",
data: dataString,
dataType: "json",
//if received a response from the server
success: function(response) {
console.log(response);
},
});
``` | I would break this problem in to 2 parts.
First, you could sent an Ajax request to your server, sending only the `dataString` variable.
Then, you can use either `cURL` or [`wp_remote_get()`](https://codex.wordpress.org/Function_Reference/wp_remote_get) on the server to access the real API.
This could be the only solution, if you want to avoid playing hide and seek with hashes and writing tons of code just to make it hard for the users to find the API key. |
298,132 | <p>I need your help with multiple values in meta_query. I have a checkbox filter. This is the query I came up:</p>
<p>But, I'm worried that query is not optimized, and that it will slow down the site. </p>
<p>I read the solution asked in this question:
<a href="https://wordpress.stackexchange.com/questions/250147/meta-query-with-multiple-values">meta_query with multiple values</a>
But, when I implement that solution I have the following error:
"<strong><em>Warning: trim() expects parameter 1 to be string</em></strong>".</p>
<p>Is there any way how to optimize this query?</p>
<p>I will appreciate any help.</p>
<p>Thank you.</p>
<pre><code>$args = array(
'post_type' => 'post' ,
'meta_key' => $meta_value,
'orderby' => $sort . ' date',
'order' => $order_sort,
'posts_per_page' => 10,
'cat' => $category,
'paged' => $paged,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'checkboxes',
'value' => $face,
'compare' => 'LIKE'
),
array(
'key' => 'checkboxes',
'value' => $twitter,
'compare' => 'LIKE'
),
array(
'key' => 'checkboxes',
'value' => $telegram,
'compare' => 'LIKE'
),
array(
'key' => 'checkboxes',
'value' => $reddit,
'compare' => 'LIKE'
),
array(
'key' => 'checkboxes',
'value' => $email,
'compare' => 'LIKE'
),
array(
'key' => 'checkboxes',
'value' => $phone,
'compare' => 'LIKE'
),
)
);
</code></pre>
| [
{
"answer_id": 298142,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>Without some other info it's pretty tough to give any solution to your this above issue. But it seems like your <code>$face</code>, <code>$twitter</code>, <code>$telegram</code> etc. data are coming in a form of <code>object</code> or other datatype(not <code>array</code> or <code>string</code>). But <code>meta_query</code>'s <code>value</code> only accepts <code>string</code> and <code>array</code>. So, based on this assumption I would suggest you to make sure that all those data of yours should be a <strong><em>one dimensional</em></strong> <code>array</code> of the values you want to filter or simple <code>string</code>.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 298146,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Post meta data was never designed to be used efficiently in queries. Using it with <code>LIKE</code> based matching will only make it more horrible.</p>\n\n<p>You need to rethink your DB. For example use taxonomy terms to indicate which social network is associated with a post.</p>\n"
}
]
| 2018/03/18 | [
"https://wordpress.stackexchange.com/questions/298132",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137724/"
]
| I need your help with multiple values in meta\_query. I have a checkbox filter. This is the query I came up:
But, I'm worried that query is not optimized, and that it will slow down the site.
I read the solution asked in this question:
[meta\_query with multiple values](https://wordpress.stackexchange.com/questions/250147/meta-query-with-multiple-values)
But, when I implement that solution I have the following error:
"***Warning: trim() expects parameter 1 to be string***".
Is there any way how to optimize this query?
I will appreciate any help.
Thank you.
```
$args = array(
'post_type' => 'post' ,
'meta_key' => $meta_value,
'orderby' => $sort . ' date',
'order' => $order_sort,
'posts_per_page' => 10,
'cat' => $category,
'paged' => $paged,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'checkboxes',
'value' => $face,
'compare' => 'LIKE'
),
array(
'key' => 'checkboxes',
'value' => $twitter,
'compare' => 'LIKE'
),
array(
'key' => 'checkboxes',
'value' => $telegram,
'compare' => 'LIKE'
),
array(
'key' => 'checkboxes',
'value' => $reddit,
'compare' => 'LIKE'
),
array(
'key' => 'checkboxes',
'value' => $email,
'compare' => 'LIKE'
),
array(
'key' => 'checkboxes',
'value' => $phone,
'compare' => 'LIKE'
),
)
);
``` | Post meta data was never designed to be used efficiently in queries. Using it with `LIKE` based matching will only make it more horrible.
You need to rethink your DB. For example use taxonomy terms to indicate which social network is associated with a post. |
298,154 | <p>I will use an $variable who is outside the function.
In the shortcode function.</p>
<p>This is what i will do:</p>
<pre><code>function shortcodevariable( $atts ){
return 'echo $variable';
}
add_shortcode('variable', 'shortcodevariable');
</code></pre>
<p>I think we need an array but I dont now how, can somebody help?</p>
<p>Thank you very much.</p>
| [
{
"answer_id": 298165,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": -1,
"selected": false,
"text": "<p>You have missing <code>shortcode_atts</code> and passing arguments in a shortcode. E.g </p>\n\n<pre><code>function shortcodevariable( $atts ){\n\n $data = shortcode_atts( array(\n 'attribute-1' => '',\n 'attribute-2' => '', \n ), $data );\n\n return $data['attribute-1'];\n}\nadd_shortcode('variable', 'shortcodevariable');\n</code></pre>\n\n<p><strong>Usage</strong></p>\n\n<p>In a post, pages etc.</p>\n\n<pre><code>[variable attribute-1='okay']\n</code></pre>\n\n<p>In php file </p>\n\n<pre><code>echo do_shortcode ( \"[variable attribute-1='<?Php echo $variable; ?>']\" );\n</code></pre>\n\n<p>Recently I have created the post <a href=\"https://wp.me/p4Ams0-hC\" rel=\"nofollow noreferrer\">Create a simple shortcode in WordPress</a>.</p>\n"
},
{
"answer_id": 298494,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using PHP > 5.3, then you can use a closure on the <code>the_content</code> filter. This filter needs to be added after the <code>$variable</code> has been defined and before the <code>the_content</code> filter has fired.</p>\n\n<pre><code>add_filter( 'the_content', function( $content ) use ( $variable ) {\n return str_replace( '[variable][/variable]', $variable, $content );\n} );\n</code></pre>\n\n<p>Shortcodes are process by core on <code>the_content</code> hook at a priority of 11. So any priority 10 or less will be run before that. If you want the callback to be run before <code>wpautop</code>, use a priority less than 10.</p>\n\n<p>There's no reason to <code>add_shortcode()</code> because this code replaces the shortcode with the variable before <code>do_shortcode()</code> is run.</p>\n\n<p>Filters should ideally be placed in the themes functions.php file, but if for some reason <code>$variable</code> isn't available to functions.php, then this little hack should work.</p>\n"
},
{
"answer_id": 317939,
"author": "Joe",
"author_id": 153214,
"author_profile": "https://wordpress.stackexchange.com/users/153214",
"pm_score": 0,
"selected": false,
"text": "<p>I just discovered the solution to use external variables within shortcodes.</p>\n\n<pre><code>function show_shortcode_variable(){\n global $variable;\n return $variable;\n}\nadd_shortcode('variable', 'show_shortcode_variable');\n</code></pre>\n\n<p>So if your <code>$variable = \"foo\";</code> and someone types this in Wordpress:</p>\n\n<pre><code>[variable]\n</code></pre>\n\n<p>... Then they'll see this output on their page or post:</p>\n\n<pre><code>foo\n</code></pre>\n\n<p>Your code is mostly okay, but you don't need the <code>echo</code> at the end, and you need to define the variable as <code>global</code> within the function.</p>\n\n<p>Does that help?</p>\n"
}
]
| 2018/03/18 | [
"https://wordpress.stackexchange.com/questions/298154",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/139888/"
]
| I will use an $variable who is outside the function.
In the shortcode function.
This is what i will do:
```
function shortcodevariable( $atts ){
return 'echo $variable';
}
add_shortcode('variable', 'shortcodevariable');
```
I think we need an array but I dont now how, can somebody help?
Thank you very much. | If you're using PHP > 5.3, then you can use a closure on the `the_content` filter. This filter needs to be added after the `$variable` has been defined and before the `the_content` filter has fired.
```
add_filter( 'the_content', function( $content ) use ( $variable ) {
return str_replace( '[variable][/variable]', $variable, $content );
} );
```
Shortcodes are process by core on `the_content` hook at a priority of 11. So any priority 10 or less will be run before that. If you want the callback to be run before `wpautop`, use a priority less than 10.
There's no reason to `add_shortcode()` because this code replaces the shortcode with the variable before `do_shortcode()` is run.
Filters should ideally be placed in the themes functions.php file, but if for some reason `$variable` isn't available to functions.php, then this little hack should work. |
298,155 | <p>I’m trying to add a custom field to image and gallery edit screen.</p>
<p>I’m aware there are similar questions here, although answers either don’t work with the current version or they add field only to <strong>upload</strong> screen while I need a field to be visible in all <strong>edit</strong> screens (see below).</p>
<p>For this, I believe, you’ll have to mess with <em>backbone.js</em> as <code>attachment_fields_to_edit</code> only adds to upload screen.</p>
<h2>Adding field with attachment_fields_to_edit</h2>
<p><a href="https://i.stack.imgur.com/sb4otm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sb4otm.png" alt=""></a></p>
<p>↑ This is upload image screeen. Here <strong>Style</strong> is added with <code>attachment_fields_to_edit</code> filter, and my_field is added with ACF plugin. </p>
<h2>But they are missing in edit screen in the post</h2>
<p><a href="https://i.stack.imgur.com/XUyV9m.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XUyV9m.png" alt="enter image description here"></a></p>
<p>↑ Click edit on the actual post</p>
<p><a href="https://i.stack.imgur.com/wiJ43m.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/wiJ43m.jpg" alt="enter image description here"></a></p>
<p>↑ No style & my_field fields!</p>
<h2>The question</h2>
<p>How to add fields to still have them on the edit screen? Ideally answer will include adding fields to gallery edit screen if it’s a similar process</p>
<p>This question is really important for me so <strong>I’ll be adding a 100 rep</strong> bounty when it’s available. </p>
<p>Thanks! </p>
| [
{
"answer_id": 299527,
"author": "Mr Rethman",
"author_id": 27393,
"author_profile": "https://wordpress.stackexchange.com/users/27393",
"pm_score": 0,
"selected": false,
"text": "<p>In my my own personal implementations of this functionality (without ACF), this is how I was able to achieve it using a combination of <code>attachment_fields_to_edit</code> and <code>attachment_fields_to_save</code>. View <a href=\"https://gist.github.com/jaredrethman/68090e4cdfe82ec1cb61ba1d8d3fa6e7\" rel=\"nofollow noreferrer\">GIST</a></p>\n\n<p>Usage:</p>\n\n<pre><code>add_action( 'after_setup_theme', 'thumbnail_meta' );\n\nfunction thumbnail_meta(){\n Thumbnail_Meta::create( [\n 'html_thumbnail_meta_id' => [\n 'label' => __( '<strong>Featured Settings:</strong>' ),\n 'input' => 'html'\n ],\n 'checkbox_thumbnail_meta_id' => [\n 'label' => __( 'Checkbox?' ),\n 'input' => 'checkbox'\n ],\n 'url_thumbnail_meta_id' => [\n 'label' => __( 'Link:' ),\n 'type' => 'url',\n ],\n 'select_thumbnail_meta_id' => [\n 'label' => __( 'Display' ),\n 'input' => 'select',\n 'options' => [\n 'none' => '-- None --',\n 'top' => 'Content Top',\n 'right' => 'Content Right',\n 'left' => 'Content Left',\n 'bottom' => 'Content bottom'\n ]\n ]\n ] );\n }\n</code></pre>\n\n<p>However - can't say for sure what the issue is without seeing your code. </p>\n"
},
{
"answer_id": 307585,
"author": "Outsource WordPress",
"author_id": 146288,
"author_profile": "https://wordpress.stackexchange.com/users/146288",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the working code (working fine for me), did you tried this? Just add to theme 'functions.php' and change the custom field names as needed.</p>\n\n<pre>//function to add custom media field\nfunction custom_media_add_media_custom_field( $form_fields, $post ) {\n $field_value = get_post_meta( $post->ID, 'custom_media_style', true );\n\n $form_fields['custom_media_style'] = array(\n 'value' => $field_value ? $field_value : '',\n 'label' => __( 'Style' ),\n 'helps' => __( 'Enter your style' ),\n 'input' => 'textarea'\n );\n\n return $form_fields;\n}\nadd_filter( 'attachment_fields_to_edit', 'custom_media_add_media_custom_field', null, 2 );\n\n//save your custom media field\nfunction custom_media_save_attachment( $attachment_id ) {\n if ( isset( $_REQUEST['attachments'][ $attachment_id ]['custom_media_style'] ) ) {\n $custom_media_style = $_REQUEST['attachments'][ $attachment_id ]['custom_media_style'];\n update_post_meta( $attachment_id, 'custom_media_style', $custom_media_style );\n\n }\n}\nadd_action( 'edit_attachment', 'custom_media_save_attachment' );</pre>\n"
},
{
"answer_id": 307768,
"author": "Saran",
"author_id": 25868,
"author_profile": "https://wordpress.stackexchange.com/users/25868",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an example code for adding photographer name and url in media editing screen.</p>\n\n<pre><code>function be_attachment_field_credit( $form_fields, $post ) {\n $form_fields['be-photographer-name'] = array(\n 'label' => 'Photographer Name',\n 'input' => 'text',\n 'value' => get_post_meta( $post->ID, 'be_photographer_name', true ),\n 'helps' => 'If provided, photo credit will be displayed',\n );\n\n $form_fields['be-photographer-url'] = array(\n 'label' => 'Photographer URL',\n 'input' => 'text',\n 'value' => get_post_meta( $post->ID, 'be_photographer_url', true ),\n 'helps' => 'If provided, photographer name will link here',\n );\n\n return $form_fields;\n}\n\nadd_filter( 'attachment_fields_to_edit', 'be_attachment_field_credit', 10, 2 );\n\n/**\n * Save values of Photographer Name and URL in media uploader\n *\n * @param $post array, the post data for database\n * @param $attachment array, attachment fields from $_POST form\n * @return $post array, modified post data\n */\n\nfunction be_attachment_field_credit_save( $post, $attachment ) {\n if( isset( $attachment['be-photographer-name'] ) )\n update_post_meta( $post['ID'], 'be_photographer_name', $attachment['be-photographer-name'] );\n\n if( isset( $attachment['be-photographer-url'] ) )\n update_post_meta( $post['ID'], 'be_photographer_url', $attachment['be-photographer-url'] );\n\n return $post;\n}\n\nadd_filter( 'attachment_fields_to_save', 'be_attachment_field_credit_save', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 368045,
"author": "PapaSoft",
"author_id": 97253,
"author_profile": "https://wordpress.stackexchange.com/users/97253",
"pm_score": 0,
"selected": false,
"text": "<p>The popup window You're trying to work with is rendered with js template inside <strong>wp-includes/media-template.php</strong>. Search for <strong>tmpl-image-details</strong>.</p>\n\n<p>And yes, all we can do is to overwrite this template in our theme or plugin.\nThis might be the way You're looking for:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/268157/97253\">https://wordpress.stackexchange.com/a/268157/97253</a></p>\n\n<p>Now I'm in progress of saving the field data and showing it then on frontend. Hopefully, I'll edit this post when finish that.</p>\n"
}
]
| 2018/03/18 | [
"https://wordpress.stackexchange.com/questions/298155",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121208/"
]
| I’m trying to add a custom field to image and gallery edit screen.
I’m aware there are similar questions here, although answers either don’t work with the current version or they add field only to **upload** screen while I need a field to be visible in all **edit** screens (see below).
For this, I believe, you’ll have to mess with *backbone.js* as `attachment_fields_to_edit` only adds to upload screen.
Adding field with attachment\_fields\_to\_edit
----------------------------------------------
[](https://i.stack.imgur.com/sb4otm.png)
↑ This is upload image screeen. Here **Style** is added with `attachment_fields_to_edit` filter, and my\_field is added with ACF plugin.
But they are missing in edit screen in the post
-----------------------------------------------
[](https://i.stack.imgur.com/XUyV9m.png)
↑ Click edit on the actual post
[](https://i.stack.imgur.com/wiJ43m.jpg)
↑ No style & my\_field fields!
The question
------------
How to add fields to still have them on the edit screen? Ideally answer will include adding fields to gallery edit screen if it’s a similar process
This question is really important for me so **I’ll be adding a 100 rep** bounty when it’s available.
Thanks! | Here is the working code (working fine for me), did you tried this? Just add to theme 'functions.php' and change the custom field names as needed.
```
//function to add custom media field
function custom_media_add_media_custom_field( $form_fields, $post ) {
$field_value = get_post_meta( $post->ID, 'custom_media_style', true );
$form_fields['custom_media_style'] = array(
'value' => $field_value ? $field_value : '',
'label' => __( 'Style' ),
'helps' => __( 'Enter your style' ),
'input' => 'textarea'
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'custom_media_add_media_custom_field', null, 2 );
//save your custom media field
function custom_media_save_attachment( $attachment_id ) {
if ( isset( $_REQUEST['attachments'][ $attachment_id ]['custom_media_style'] ) ) {
$custom_media_style = $_REQUEST['attachments'][ $attachment_id ]['custom_media_style'];
update_post_meta( $attachment_id, 'custom_media_style', $custom_media_style );
}
}
add_action( 'edit_attachment', 'custom_media_save_attachment' );
``` |
298,225 | <p>I'm playing with Gutenberg ahead of its inclusion in core, and I'd like to know how to extend the existing gallery block to change its display. For example, instead of a grid of thumbnails I'd like to show a slideshow of images. Is it possible? If so, how? Any help would be appreciated.</p>
| [
{
"answer_id": 298441,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 5,
"selected": true,
"text": "<p>Ok, I've been playing with this for a little bit and have managed to change the output of the Gallery block, with the following caveats:</p>\n\n<ul>\n<li>The preview does not match the output. I think this is possible but appears to be a bit more involved.</li>\n<li>Certain classes and markup are required in the output for the block to be able to parse the content and keep it editable. These classes have front-end styles that will need to be dealt with. I'm not sure at this point if there is a way to filter how the block does this. If it were possible it might not even be a good idea if it means Gallery blocks are broken when a theme or plugin is deactivated. A totally new block would probably be the way to go for situations where this would be required.</li>\n<li>I'm not really sure how image sizes work at this stage.</li>\n<li>The method of JavaScript hooks used might not be relevant in the final release. Gutenberg uses <a href=\"https://www.npmjs.com/package/@wordpress/hooks\" rel=\"noreferrer\"><code>@wordpress/hooks</code></a> while discussion about what hooks system to use in Core <a href=\"https://core.trac.wordpress.org/ticket/21170\" rel=\"noreferrer\">is ongoing</a>.</li>\n<li>Since the output of Blocks is saved as HTML, not a shortcode or meta, it won't be possible to modify the output of existing Galleries without editing them.</li>\n</ul>\n\n<p>The first thing we need to do is register a script. This is done with <code>wp_enqueue_scripts()</code>, but on the <code>enqueue_block_editor_assets</code> hook. </p>\n\n<p>The script should have the <code>wp-blocks</code> script as a dependency. It is almost certainly already loaded in the editor, but making it a dependency presumably ensures it is loaded before our script.</p>\n\n<pre><code>function wpse_298225_enqueue_block_assets() {\n wp_enqueue_script(\n 'wpse-298225-gallery-block',\n get_theme_file_uri( 'block.js' ),\n ['wp-blocks']\n );\n}\nadd_action( 'enqueue_block_editor_assets', 'wpse_298225_enqueue_block_assets' );\n</code></pre>\n\n<p>The HTML for a block's output is handled by the <code>save()</code> method of the block. You can see the Gallery block's in <a href=\"https://github.com/WordPress/gutenberg/blob/master/blocks/library/gallery/index.js\" rel=\"noreferrer\">this file</a>.</p>\n\n<p>At this stage (March 2018) Gutenberg supports a filter on the save method of blocks, <a href=\"https://github.com/WordPress/gutenberg/blob/master/docs/extensibility.md#blocksgetsaveelement\" rel=\"noreferrer\"><code>blocks.getSaveElement</code></a>. We can add a hook to this in JavaScript like this:</p>\n\n<pre><code>wp.hooks.addFilter(\n 'blocks.getSaveElement',\n 'wpse-298225',\n wpse298225GallerySaveElement\n)\n</code></pre>\n\n<p>The first argument is the hook name, the 2nd argument is - I think - a namespace, and the last argument is the callback function.</p>\n\n<p>Since we are replacing the <code>save()</code> method of the block, we need to return an new element. However, this is not a normal HTML element we need to return. We need to return a <em>React</em> element.</p>\n\n<p>When you look at the original block’s <code>save()</code> method what you see is JSX. React, which Gutenberg uses under-the-hood, supports it for rendering elements. See <a href=\"https://reactjs.org/docs/introducing-jsx.html\" rel=\"noreferrer\">this article</a> for more on that. </p>\n\n<p>JSX normally requires a build step, but since I'm not introducing a build step for this example, we need a way to create an element without JSX. React provides this with <code>createElement()</code>. WordPress provides a wrapper for this and other react functionality in the form of <code>wp.element</code>. So to use <code>createElement()</code> we use <code>wp.element.createElement()</code>.</p>\n\n<p>In the callback function for <code>blocks.getSaveElement</code> we get:</p>\n\n<ul>\n<li><code>element</code> The original Element created by the block.</li>\n<li><code>blockType</code> An object representing the block being used.</li>\n<li><code>attributes</code> The properties of the block instance. In our example this includes the images in gallery and settings like the number of columns.</li>\n</ul>\n\n<p>So our callback function needs to:</p>\n\n<ul>\n<li>Return the original element for non-block galleries.</li>\n<li>Take the attributes, particularly the images, and create a new React element out of them representing the gallery.</li>\n</ul>\n\n<p>Here is a complete example that simply outputs a <code>ul</code> with a class, <code>my-gallery</code>, and <code>li</code>s for each image with the class <code>my-gallery-item</code> and and <code>img</code> in each one with the <code>src</code> set to the image URL.</p>\n\n<pre><code>function wpse298225GallerySaveElement( element, blockType, attributes ) {\n if ( blockType.name !== 'core/gallery' ) {\n return element;\n }\n\n var newElement = wp.element.createElement(\n 'ul',\n {\n 'className': 'wp-block-gallery my-gallery',\n },\n attributes.images.map(\n function( image ) {\n return wp.element.createElement(\n 'li',\n {\n 'className': 'blocks-gallery-item my-gallery-item',\n },\n wp.element.createElement(\n 'img',\n {\n 'src': image.url,\n }\n )\n )\n }\n )\n )\n\n return newElement\n}\n</code></pre>\n\n<p>Some things to take note of:</p>\n\n<ul>\n<li>The original gallery block finds images by looking for <code>ul.wp-block-gallery .blocks-gallery-item</code>, so this markup and those classes are required for editing the block to be possible. This markup is also used for the default styling.</li>\n<li><code>attributes.images.map</code> is looping over each image and returning an array of child elements as the content for the main element. Inside these elements there is another child element for the image itself.</li>\n</ul>\n"
},
{
"answer_id": 328640,
"author": "Jeff Wilkerson",
"author_id": 120771,
"author_profile": "https://wordpress.stackexchange.com/users/120771",
"pm_score": 2,
"selected": false,
"text": "<p>Here to provide an updated answer. I found <a href=\"https://wordpress.stackexchange.com/questions/313795/validation-error-extending-gutenberg-gallery-block?rq=1\">this post extremely helpful</a> in answering the question of how to extend the Gallery Block.</p>\n\n<p>In short, its advisable to just create a new block rather than extending an existing. From the post in my link above:</p>\n\n<blockquote>\n <p>if you modify the HTML of a block [by extending], it won't be recognized as the original block. Rather than trying to manipulate a core block it seems like unregistering the core block and registering a new replacement block in its place would be a safer approach - that way you're ensuring users of the site use your particular customized gallery, which will validate because it defines its own HTML structure.</p>\n</blockquote>\n\n<p>The link above also references <a href=\"https://github.com/ahmadawais/create-guten-block\" rel=\"nofollow noreferrer\">The Create-Guten_Block plugin</a> which is a command-line tool that will generate everything you need to get you started with Block creation. The tool is very easy to use, and easy setup. </p>\n\n<p>With these resources, I was able to figure out how to develop a custom gallery block in a short time</p>\n"
}
]
| 2018/03/19 | [
"https://wordpress.stackexchange.com/questions/298225",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33049/"
]
| I'm playing with Gutenberg ahead of its inclusion in core, and I'd like to know how to extend the existing gallery block to change its display. For example, instead of a grid of thumbnails I'd like to show a slideshow of images. Is it possible? If so, how? Any help would be appreciated. | Ok, I've been playing with this for a little bit and have managed to change the output of the Gallery block, with the following caveats:
* The preview does not match the output. I think this is possible but appears to be a bit more involved.
* Certain classes and markup are required in the output for the block to be able to parse the content and keep it editable. These classes have front-end styles that will need to be dealt with. I'm not sure at this point if there is a way to filter how the block does this. If it were possible it might not even be a good idea if it means Gallery blocks are broken when a theme or plugin is deactivated. A totally new block would probably be the way to go for situations where this would be required.
* I'm not really sure how image sizes work at this stage.
* The method of JavaScript hooks used might not be relevant in the final release. Gutenberg uses [`@wordpress/hooks`](https://www.npmjs.com/package/@wordpress/hooks) while discussion about what hooks system to use in Core [is ongoing](https://core.trac.wordpress.org/ticket/21170).
* Since the output of Blocks is saved as HTML, not a shortcode or meta, it won't be possible to modify the output of existing Galleries without editing them.
The first thing we need to do is register a script. This is done with `wp_enqueue_scripts()`, but on the `enqueue_block_editor_assets` hook.
The script should have the `wp-blocks` script as a dependency. It is almost certainly already loaded in the editor, but making it a dependency presumably ensures it is loaded before our script.
```
function wpse_298225_enqueue_block_assets() {
wp_enqueue_script(
'wpse-298225-gallery-block',
get_theme_file_uri( 'block.js' ),
['wp-blocks']
);
}
add_action( 'enqueue_block_editor_assets', 'wpse_298225_enqueue_block_assets' );
```
The HTML for a block's output is handled by the `save()` method of the block. You can see the Gallery block's in [this file](https://github.com/WordPress/gutenberg/blob/master/blocks/library/gallery/index.js).
At this stage (March 2018) Gutenberg supports a filter on the save method of blocks, [`blocks.getSaveElement`](https://github.com/WordPress/gutenberg/blob/master/docs/extensibility.md#blocksgetsaveelement). We can add a hook to this in JavaScript like this:
```
wp.hooks.addFilter(
'blocks.getSaveElement',
'wpse-298225',
wpse298225GallerySaveElement
)
```
The first argument is the hook name, the 2nd argument is - I think - a namespace, and the last argument is the callback function.
Since we are replacing the `save()` method of the block, we need to return an new element. However, this is not a normal HTML element we need to return. We need to return a *React* element.
When you look at the original block’s `save()` method what you see is JSX. React, which Gutenberg uses under-the-hood, supports it for rendering elements. See [this article](https://reactjs.org/docs/introducing-jsx.html) for more on that.
JSX normally requires a build step, but since I'm not introducing a build step for this example, we need a way to create an element without JSX. React provides this with `createElement()`. WordPress provides a wrapper for this and other react functionality in the form of `wp.element`. So to use `createElement()` we use `wp.element.createElement()`.
In the callback function for `blocks.getSaveElement` we get:
* `element` The original Element created by the block.
* `blockType` An object representing the block being used.
* `attributes` The properties of the block instance. In our example this includes the images in gallery and settings like the number of columns.
So our callback function needs to:
* Return the original element for non-block galleries.
* Take the attributes, particularly the images, and create a new React element out of them representing the gallery.
Here is a complete example that simply outputs a `ul` with a class, `my-gallery`, and `li`s for each image with the class `my-gallery-item` and and `img` in each one with the `src` set to the image URL.
```
function wpse298225GallerySaveElement( element, blockType, attributes ) {
if ( blockType.name !== 'core/gallery' ) {
return element;
}
var newElement = wp.element.createElement(
'ul',
{
'className': 'wp-block-gallery my-gallery',
},
attributes.images.map(
function( image ) {
return wp.element.createElement(
'li',
{
'className': 'blocks-gallery-item my-gallery-item',
},
wp.element.createElement(
'img',
{
'src': image.url,
}
)
)
}
)
)
return newElement
}
```
Some things to take note of:
* The original gallery block finds images by looking for `ul.wp-block-gallery .blocks-gallery-item`, so this markup and those classes are required for editing the block to be possible. This markup is also used for the default styling.
* `attributes.images.map` is looping over each image and returning an array of child elements as the content for the main element. Inside these elements there is another child element for the image itself. |
298,238 | <p>I'm looking to add a formatted text at the bottom of each excerpt text when I read an archive page. The code is the same for all the posts.</p>
<p>I have found for the category based archive page by modifying the category.php file in my child theme folder. But i don't know where to write my code for the date based archive or for the all blog archive page of my theme.</p>
<p>Thank for your help.</p>
| [
{
"answer_id": 298245,
"author": "Amol Sawant",
"author_id": 138676,
"author_profile": "https://wordpress.stackexchange.com/users/138676",
"pm_score": 1,
"selected": false,
"text": "<p>Open archive.php from your theme's directory the code will look like this </p>\n\n<pre><code><?php\n/*\nTemplate Name: Archives\n*/\nget_header(); ?>\n\n<div id=\"container\">\n <div id=\"content\" role=\"main\">\n\n <?php the_post(); ?>\n <h1 class=\"entry-title\"><?php the_title(); ?></h1>\n\n <?php get_search_form(); ?>\n\n <h2>Archives by Month:</h2>\n <ul>\n <?php wp_get_archives('type=monthly'); ?>\n </ul>\n\n <h2>Archives by Subject:</h2>\n <ul>\n <?php wp_list_categories(); ?>\n </ul>\n\n </div><!-- #content -->\n</div><!-- #container -->\n\n<?php get_sidebar(); ?>\n<?php get_footer(); ?>\n</code></pre>\n\n<p>the add your html code between </p>\n\n<pre><code></div><!-- #content -->\n</code></pre>\n\n<p>Your code goes here .......</p>\n\n<pre><code></div><!-- #container -->\n</code></pre>\n\n<p>.............................................................................</p>\n\n<p>upvote my answer i..</p>\n"
},
{
"answer_id": 298461,
"author": "Kuldip Z",
"author_id": 140107,
"author_profile": "https://wordpress.stackexchange.com/users/140107",
"pm_score": 0,
"selected": false,
"text": "<p>You need to copy archive.php of parent theme and then paste into child theme. Now do your required changes into child theme's archive.php</p>\n"
}
]
| 2018/03/19 | [
"https://wordpress.stackexchange.com/questions/298238",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/139939/"
]
| I'm looking to add a formatted text at the bottom of each excerpt text when I read an archive page. The code is the same for all the posts.
I have found for the category based archive page by modifying the category.php file in my child theme folder. But i don't know where to write my code for the date based archive or for the all blog archive page of my theme.
Thank for your help. | Open archive.php from your theme's directory the code will look like this
```
<?php
/*
Template Name: Archives
*/
get_header(); ?>
<div id="container">
<div id="content" role="main">
<?php the_post(); ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php get_search_form(); ?>
<h2>Archives by Month:</h2>
<ul>
<?php wp_get_archives('type=monthly'); ?>
</ul>
<h2>Archives by Subject:</h2>
<ul>
<?php wp_list_categories(); ?>
</ul>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
```
the add your html code between
```
</div><!-- #content -->
```
Your code goes here .......
```
</div><!-- #container -->
```
.............................................................................
upvote my answer i.. |
298,241 | <p>I want to check plugin version using following API</p>
<pre><code>https://api.wordpress.org/stats/plugin/1.0/{slug}
</code></pre>
<p>For that how can I get Slug of All Active Plugins ?</p>
| [
{
"answer_id": 298243,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>If your are not on a multisite installation, you can have activated plugins with this code : </p>\n\n<pre><code>$active_plugins = get_option( 'active_plugins', array() );\n</code></pre>\n"
},
{
"answer_id": 298244,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 2,
"selected": true,
"text": "<p>Use option <code>active_plugins</code> to get all plugin init files. e.g.</p>\n\n<pre><code>$current = get_option( 'active_plugins', array() );\n// print_r( $current );\n</code></pre>\n\n<p>Here, <code>htmlpress</code> is the plugin slug.</p>\n\n<p><a href=\"https://i.stack.imgur.com/J4fBJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/J4fBJ.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 298253,
"author": "Cristian",
"author_id": 121995,
"author_profile": "https://wordpress.stackexchange.com/users/121995",
"pm_score": 1,
"selected": false,
"text": "<p>You can use this code:</p>\n\n<pre><code> <?php \n\n// Check if get_plugins() function exists. This is required on the front end of the\n// site, since it is in a file that is normally only loaded in the admin.\nif ( ! function_exists( 'get_plugins' ) ) {\n require_once ABSPATH . 'wp-admin/includes/plugin.php';\n}\n\n$all_plugins = get_plugins();\n\nprint_r( $all_plugins);\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code> Array\n (\n [hello-dolly/hello.php] => Array\n (\n [Name] => Hello Dolly\n [PluginURI] => http://wordpress.org/extend/plugins/hello-dolly/\n [Version] => 1.6\n [Description] => This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.\n [Author] => Matt Mullenweg\n [AuthorURI] => http://ma.tt/\n [TextDomain] => \n [DomainPath] => \n [Network] => \n [Title] => Hello Dolly\n [AuthorName] => Matt Mullenweg\n\n )\n</code></pre>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Function_Reference/get_plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_plugins</a></p>\n"
}
]
| 2018/03/19 | [
"https://wordpress.stackexchange.com/questions/298241",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110795/"
]
| I want to check plugin version using following API
```
https://api.wordpress.org/stats/plugin/1.0/{slug}
```
For that how can I get Slug of All Active Plugins ? | Use option `active_plugins` to get all plugin init files. e.g.
```
$current = get_option( 'active_plugins', array() );
// print_r( $current );
```
Here, `htmlpress` is the plugin slug.
[](https://i.stack.imgur.com/J4fBJ.png) |
298,251 | <p>I want to check latest version of plugin is available or not. For that I required current version of active plugins. How can I get current version of all active plugins programmatically ?</p>
| [
{
"answer_id": 298252,
"author": "Cristian",
"author_id": 121995,
"author_profile": "https://wordpress.stackexchange.com/users/121995",
"pm_score": -1,
"selected": false,
"text": "<p>You can use this code:</p>\n\n<pre><code><?php \n\n// Check if get_plugins() function exists. This is required on the front end of the\n// site, since it is in a file that is normally only loaded in the admin.\nif ( ! function_exists( 'get_plugins' ) ) {\n require_once ABSPATH . 'wp-admin/includes/plugin.php';\n}\n\n$all_plugins = get_plugins();\nprint_r( $all_plugins );\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 298323,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 3,
"selected": true,
"text": "<h1>Problem Analysis</h1>\n\n<p>To get information about installed plugins, which provides plugin's version, we'll use <code>get_plugins()</code> function. Keep in mind, that this function is available in back end only, so our code must reside there. Data, returned from this function, does not tell us, which plugins are active. To filter out active plugins, we'll use <code>get_option('active_plugins')</code> function. It will return a simple array, consisting of keys to array returned by <code>get_plugins()</code> function.</p>\n\n<h1>Code</h1>\n\n<p>The best illustration for our method will be the actual code. We'll create a dashboard widget, displaying three-column table, showing active plugin's name, its current version, and its newest version in WordPress repository. Let's create <code>myDashboardWidget.php</code> file, and put the code below, in it. </p>\n\n<pre><code><?php\nif(is_admin()) { // make sure, the following code runs in back end\n\n // returns version of the plugin represented by $slug, from repository\n function getPluginVersionFromRepository($slug) {\n $url = \"https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&request[slugs][]={$slug}\";\n $response = wp_remote_get($url); // WPOrg API call \n $plugins = json_decode($response['body']);\n\n // traverse $response object\n foreach($plugins as $key => $plugin) {\n $version = $plugin->version;\n }\n return $version;\n }\n\n // dashboard widget's callback\n function activePluginsVersions() {\n $allPlugins = get_plugins(); // associative array of all installed plugins\n $activePlugins = get_option('active_plugins'); // simple array of active plugins\n\n // building active plugins table\n echo '<table width=\"100%\">';\n echo '<thead>';\n echo '<tr>';\n echo '<th width=\"50%\" style=\"text-align:left\">Plugin</th>';\n echo '<th width=\"20%\" style=\"text-align:left\">currVer</th>';\n echo '<th width=\"20%\" style=\"text-align:left\">repoVer</th>';\n echo '</tr>';\n echo '</thead>';\n echo '<tbody>';\n\n // traversing $allPlugins array\n foreach($allPlugins as $key => $value) {\n if(in_array($key, $activePlugins)) { // display active only\n echo '<tr>';\n echo \"<td>{$value['Name']}</td>\";\n echo \"<td>{$value['Version']}</td>\";\n $slug = explode('/',$key)[0]; // get active plugin's slug\n\n // get newest version of active plugin from repository\n $repoVersion = getPluginVersionFromRepository($slug);\n\n echo \"<td>{$repoVersion}</td>\";\n echo '</tr>';\n }\n }\n echo '</tbody>';\n echo '</table>';\n } \n\n // widget's registration\n function fpwAddDashboardWidget() {\n wp_add_dashboard_widget(\n 'active_plugins_versions', // widget's ID\n 'Active Plugins Versions', // widget's title\n 'activePluginsVersions' // widget's callback (content)\n ); \n }\n add_action('wp_dashboard_setup', 'fpwAddDashboardWidget');\n}\n</code></pre>\n\n<p>Now, place this file in <code>/wp-content/mu-plugins/</code> directory.</p>\n\n<h1>Code Explained</h1>\n\n<p>Read comments within <code>myDashboardWidget.php</code> file.</p>\n\n<p><strong>Note:</strong> if there is no version shown in third column of the table, the plugin is not in repository (either premium, or discontinued).</p>\n\n<h1>Code Efficiency</h1>\n\n<p>Efficiency of this sample code can be much improved. The WPOrg API request is made for each plugin. <code>/plugins/info/1.2/</code> version of the API, allows getting info for all plugin slugs with one request only.</p>\n"
},
{
"answer_id": 412636,
"author": "Anders madsen",
"author_id": 228692,
"author_profile": "https://wordpress.stackexchange.com/users/228692",
"pm_score": 0,
"selected": false,
"text": "<p>There are several ways to get all active plugins.</p>\n<p>In order to see an output of all your current active plugins to develop some code that might be different from mine, you can get a var_export for some test data as well with this:</p>\n<pre><code>if(is_admin())\n{\n $allPlugins = get_plugins();\n $allActivePlugins = []; //prepare array for all Active plugins\n $activePlugins = get_option('active_plugins', array());\n foreach($allPlugins as $plugin => $pluginData)\n {\n //Wordpress made a function for this called "is_plugin_active" can be used as such: is_plugin_active($plugin)\n if(in_array($plugin, $activePlugins)) )\n {\n $allActivePlugins[$plugin] = $pluginData;\n echo 'Active plugin '.$pluginData['name'].' version: '.$pluginData['version'].'<br>';\n //Do something with the active plugin\n }\n\n }\n\n //List all active plugins in a var export\n echo '<pre>';\n echo var_export($allActivePlugins, true);\n echo '</pre>';\n}\n</code></pre>\n<p>In the foreach loop after the if statement, you can do something with each plugin.</p>\n<p>Put this code any place where you want to output something in the wordpress admin area</p>\n<p>Var Export output will output something like this</p>\n<pre><code> array (\n 'transients-manager/transients-manager.php' =>\n array (\n 'Name' => 'Transients Manager',\n 'PluginURI' => 'https://wordpress.org/plugins/transients-manager/',\n 'Version' => '2.0.2',\n 'Description' => 'Provides a familiar interface to view, search, edit, and delete Transients.',\n 'Author' => 'WPBeginner',\n 'AuthorURI' => 'https://www.wpbeginner.com',\n 'TextDomain' => 'transients-manager',\n 'DomainPath' => '',\n 'Network' => false,\n 'RequiresWP' => '5.3',\n 'RequiresPHP' => '5.6.20',\n 'UpdateURI' => '',\n 'Title' => 'Transients Manager',\n 'AuthorName' => 'WPBeginner',\n ),\n )\n \n</code></pre>\n<p>I felt like the accepted answer was a bit too long and there was a lot of code that just took up space and wasn't needed, adjust this code to your use case.</p>\n<p>I also included a section for getting new versions.</p>\n<h2>New versions for plugins</h2>\n<p>When it comes to getting available updates, Instead of the accepted answer, I recommend checking the transient called "update_plugins" which contains a list of currently available updates.</p>\n<p>If any premium plugin has available updates, they will also put them here, there is literally no reason to query the Wordpress.org Plugin API since wordpress already does this for all plugins, you can force an update check by deleting the ('update_plugins') transient and reload any page via a browser, as it's populated with each load and I suspect it's through an ajax call, so my suggestion is to do it with an Iframe as I haven't found where in the wordpress source code it makes this check and don't have time to further dig right now.</p>\n<p>if you do this with custom code you just have more code to maintain instead of using what's already available.</p>\n<p>This is how to get the transient</p>\n<pre><code>$transient = get_transient('update_plugins');\n</code></pre>\n<p>To check for new updates, in the above code you go into the for each loop and you can do this:</p>\n<pre><code>if(isset($transient->response[$plugin]))\n{\n //There is an update for this plugin\n $newInfo = $transient->response[$plugin];\n echo 'New version for plugin '.$newInfo->name.' version: '.$newInfo->new_version.'<br>';\n}\n</code></pre>\n<p>The full code uses admin pages in this example, more about those here: <a href=\"https://codex.wordpress.org/Administration_Menus\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Administration_Menus</a></p>\n<p>Here is The full code from this would therefore be divided up into 2 files/pages, I have not included admin page code to make the code a bit more readable</p>\n<pre><code><?php\ndelete_transient('update_plugins');\nif(isset($_GET['is-transient-deleted']) && $_GET['is-transient-deleted'] == 1)\n{\n?>\n<meta http-equiv="refresh" content="0; url='https://example.com/wp-admin/admin.php?my-page-with-plugin-work'" />\n<?\n}\nelse\n{\n?>\n<meta http-equiv="refresh" content="0; url='https://example.com/wp-admin/admin.php?my-redirecter?is-transient-deleted=1'" />\n<?php\n}\n</code></pre>\n<pre><code>if(is_admin())\n{\n $allPlugins = get_plugins();\n $allActivePlugins = []; //prepare array for all Active plugins\n $activePlugins = get_option('active_plugins', array());\n $transient = get_transient('update_plugins');\n foreach($allPlugins as $plugin => $pluginData)\n {\n //Wordpress made a function for this called "is_plugin_active" can be used as such: is_plugin_active($plugin)\n if(in_array($plugin, $activePlugins)) )\n {\n $allActivePlugins[$plugin] = $pluginData;\n //Do something with the active plugin\n if(isset($transient->response[$plugin]))\n {\n //There is an update for this plugin\n $newInfo = $transient->response[$plugin];\n echo 'New version for plugin '.$newInfo->name.' version: '.$newInfo->new_version.'<br>';\n }\n else\n {\n echo 'No new version for plugin '.$pluginData['name'].' version: '.$pluginData['version'].'<br>';\n }\n }\n\n }\n}\n</code></pre>\n"
}
]
| 2018/03/19 | [
"https://wordpress.stackexchange.com/questions/298251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110795/"
]
| I want to check latest version of plugin is available or not. For that I required current version of active plugins. How can I get current version of all active plugins programmatically ? | Problem Analysis
================
To get information about installed plugins, which provides plugin's version, we'll use `get_plugins()` function. Keep in mind, that this function is available in back end only, so our code must reside there. Data, returned from this function, does not tell us, which plugins are active. To filter out active plugins, we'll use `get_option('active_plugins')` function. It will return a simple array, consisting of keys to array returned by `get_plugins()` function.
Code
====
The best illustration for our method will be the actual code. We'll create a dashboard widget, displaying three-column table, showing active plugin's name, its current version, and its newest version in WordPress repository. Let's create `myDashboardWidget.php` file, and put the code below, in it.
```
<?php
if(is_admin()) { // make sure, the following code runs in back end
// returns version of the plugin represented by $slug, from repository
function getPluginVersionFromRepository($slug) {
$url = "https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&request[slugs][]={$slug}";
$response = wp_remote_get($url); // WPOrg API call
$plugins = json_decode($response['body']);
// traverse $response object
foreach($plugins as $key => $plugin) {
$version = $plugin->version;
}
return $version;
}
// dashboard widget's callback
function activePluginsVersions() {
$allPlugins = get_plugins(); // associative array of all installed plugins
$activePlugins = get_option('active_plugins'); // simple array of active plugins
// building active plugins table
echo '<table width="100%">';
echo '<thead>';
echo '<tr>';
echo '<th width="50%" style="text-align:left">Plugin</th>';
echo '<th width="20%" style="text-align:left">currVer</th>';
echo '<th width="20%" style="text-align:left">repoVer</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
// traversing $allPlugins array
foreach($allPlugins as $key => $value) {
if(in_array($key, $activePlugins)) { // display active only
echo '<tr>';
echo "<td>{$value['Name']}</td>";
echo "<td>{$value['Version']}</td>";
$slug = explode('/',$key)[0]; // get active plugin's slug
// get newest version of active plugin from repository
$repoVersion = getPluginVersionFromRepository($slug);
echo "<td>{$repoVersion}</td>";
echo '</tr>';
}
}
echo '</tbody>';
echo '</table>';
}
// widget's registration
function fpwAddDashboardWidget() {
wp_add_dashboard_widget(
'active_plugins_versions', // widget's ID
'Active Plugins Versions', // widget's title
'activePluginsVersions' // widget's callback (content)
);
}
add_action('wp_dashboard_setup', 'fpwAddDashboardWidget');
}
```
Now, place this file in `/wp-content/mu-plugins/` directory.
Code Explained
==============
Read comments within `myDashboardWidget.php` file.
**Note:** if there is no version shown in third column of the table, the plugin is not in repository (either premium, or discontinued).
Code Efficiency
===============
Efficiency of this sample code can be much improved. The WPOrg API request is made for each plugin. `/plugins/info/1.2/` version of the API, allows getting info for all plugin slugs with one request only. |
298,297 | <p>I'm trying to upload files using AJAX and I'm hooking in my functions so they get called within admin-ajax. I can't get it to work tough, and I didn't have any idea what was wrong or where to look at all. I narrowed it down, however, by modifying admin-ajax.php a little bit:</p>
<pre><code>// Require an action parameter
if ( empty( $_REQUEST['action'] ) ) {
$response = array(
'error' => 'no action parameter',
'req' => var_export( $_REQUEST, true )
);
wp_send_json( $response );
wp_die( '0', 400 );
}
</code></pre>
<p>My AJAX request has dataType: 'json' in it, so my success function does get called(if I remove the $response declaration and the call to wp_send_json, the error one gets called, returning the entire page as a response with the statusText being "parsererror").</p>
<p>Anyway, here's my AJAX script:</p>
<pre><code> $( '#user-file' ).change( function( event ) {
var formData = new FormData();
formData.append( "userfile", $(this)[0].files[0] );
formData.append( "action", "vibesoft_files_upload" );
formData.append( "_wpnonce", vbsoft.nonce_upload );
console.log( formData );
$.ajax({
type: "post",
url: vbsoft.ajax_url,
data: formData,
contentType: "multipart/form-data",
processData: false,
dataType: 'json',
success: function( data ) {
if ( data.error != 'none' ) {
console.log( 'Error: ' + data.error );
console.log( 'Request: ' + data.req );
return;
}
</code></pre>
<p>It's not the entire function, which is wrapped inside <code>(function($) { ... })(jQuery);</code> so I can use $ instead of jQuery. The <code>console.log( 'Request: ' + data.req );</code> outputs:</p>
<pre><code>Request: array(
)
</code></pre>
<p>I also tried outputting the $_POST and $_FILES and they, too, are empty arrays. If I send them back using(instead of the JSON return):</p>
<pre><code>var_dump( $_REQUEST );
exit;
</code></pre>
<p>I get <code>array(0) {}</code> back in the console.</p>
<p>So, yeah, I have no idea why am I getting an empty array...</p>
| [
{
"answer_id": 298300,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>Here's the problem:</p>\n\n<pre><code> var formData = new FormData();\n formData.append( \"userfile\", $(this)[0].files[0] );\n formData.append( \"action\", \"vibesoft_files_upload\" );\n formData.append( \"_wpnonce\", vbsoft.nonce_upload );\n\n console.log( formData );\n\n $.ajax({\n type: \"post\",\n url: vbsoft.ajax_url,\n data: formData,\n</code></pre>\n\n<p>Specifically:</p>\n\n<pre><code> var formData = new FormData();\n</code></pre>\n\n<p>Nowhere in the jQuery documentation does it say that <code>data</code> accepts a <code>FormData</code> object for the <code>data</code> parameter:</p>\n\n<blockquote>\n <p>data Type: PlainObject or String or Array Data to be sent to the\n server. It is converted to a query string, if not already a string.\n It's appended to the url for GET-requests. See processData option to\n prevent this automatic processing. Object must be Key/Value pairs. If\n value is an Array, jQuery serializes multiple values with same key\n based on the value of the traditional setting (described below).</p>\n</blockquote>\n\n<p><a href=\"https://api.jquery.com/jQuery.ajax/\" rel=\"nofollow noreferrer\">https://api.jquery.com/jQuery.ajax/</a></p>\n\n<p>The solution is to instead use an object, e.g.:</p>\n\n<pre><code>var formData = {\n \"userfile\": $(this)[0].files[0],\n \"action\": \"vibesoft_files_upload\",\n \"_wpnonce\": vbsoft.nonce_upload\n};\n</code></pre>\n\n<p>Keep in mind that if you'd used the much easier REST API, and specified the fields required, the API would have told you point blank what the problem was and which fields were missing. The REST API is much easier to use, with far fewer gotchas and hangups to trip over</p>\n\n<p>So much so, there's already a core endpoint that might be able to do what you're trying to do, see <a href=\"https://developer.wordpress.org/rest-api/reference/media/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/reference/media/</a></p>\n"
},
{
"answer_id": 298368,
"author": "Tarik Druskic",
"author_id": 139991,
"author_profile": "https://wordpress.stackexchange.com/users/139991",
"pm_score": 0,
"selected": false,
"text": "<p>Solved it!</p>\n\n<p>I ended up using the FormData object and changing the $.ajax call to:</p>\n\n<pre><code>$.ajax({\n method: 'post',\n processData: false,\n contentType: false,\n cache: false,\n data: form_data,\n enctype: 'multipart/form-data',\n url: custom.ajaxURL,\n</code></pre>\n"
}
]
| 2018/03/20 | [
"https://wordpress.stackexchange.com/questions/298297",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/139991/"
]
| I'm trying to upload files using AJAX and I'm hooking in my functions so they get called within admin-ajax. I can't get it to work tough, and I didn't have any idea what was wrong or where to look at all. I narrowed it down, however, by modifying admin-ajax.php a little bit:
```
// Require an action parameter
if ( empty( $_REQUEST['action'] ) ) {
$response = array(
'error' => 'no action parameter',
'req' => var_export( $_REQUEST, true )
);
wp_send_json( $response );
wp_die( '0', 400 );
}
```
My AJAX request has dataType: 'json' in it, so my success function does get called(if I remove the $response declaration and the call to wp\_send\_json, the error one gets called, returning the entire page as a response with the statusText being "parsererror").
Anyway, here's my AJAX script:
```
$( '#user-file' ).change( function( event ) {
var formData = new FormData();
formData.append( "userfile", $(this)[0].files[0] );
formData.append( "action", "vibesoft_files_upload" );
formData.append( "_wpnonce", vbsoft.nonce_upload );
console.log( formData );
$.ajax({
type: "post",
url: vbsoft.ajax_url,
data: formData,
contentType: "multipart/form-data",
processData: false,
dataType: 'json',
success: function( data ) {
if ( data.error != 'none' ) {
console.log( 'Error: ' + data.error );
console.log( 'Request: ' + data.req );
return;
}
```
It's not the entire function, which is wrapped inside `(function($) { ... })(jQuery);` so I can use $ instead of jQuery. The `console.log( 'Request: ' + data.req );` outputs:
```
Request: array(
)
```
I also tried outputting the $\_POST and $\_FILES and they, too, are empty arrays. If I send them back using(instead of the JSON return):
```
var_dump( $_REQUEST );
exit;
```
I get `array(0) {}` back in the console.
So, yeah, I have no idea why am I getting an empty array... | Here's the problem:
```
var formData = new FormData();
formData.append( "userfile", $(this)[0].files[0] );
formData.append( "action", "vibesoft_files_upload" );
formData.append( "_wpnonce", vbsoft.nonce_upload );
console.log( formData );
$.ajax({
type: "post",
url: vbsoft.ajax_url,
data: formData,
```
Specifically:
```
var formData = new FormData();
```
Nowhere in the jQuery documentation does it say that `data` accepts a `FormData` object for the `data` parameter:
>
> data Type: PlainObject or String or Array Data to be sent to the
> server. It is converted to a query string, if not already a string.
> It's appended to the url for GET-requests. See processData option to
> prevent this automatic processing. Object must be Key/Value pairs. If
> value is an Array, jQuery serializes multiple values with same key
> based on the value of the traditional setting (described below).
>
>
>
<https://api.jquery.com/jQuery.ajax/>
The solution is to instead use an object, e.g.:
```
var formData = {
"userfile": $(this)[0].files[0],
"action": "vibesoft_files_upload",
"_wpnonce": vbsoft.nonce_upload
};
```
Keep in mind that if you'd used the much easier REST API, and specified the fields required, the API would have told you point blank what the problem was and which fields were missing. The REST API is much easier to use, with far fewer gotchas and hangups to trip over
So much so, there's already a core endpoint that might be able to do what you're trying to do, see <https://developer.wordpress.org/rest-api/reference/media/> |
298,324 | <pre><code><?php
// Get the assigned tag_id
$tag_ids = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );
// Check if there is any tag_ids, if print wp_tag_cloud
if ( $tag_ids ) {
wp_tag_cloud( array(
'unit' => 'px', // font sizing choice (pt, em, px, etc)
'include' => $tag_ids, // ID's of tags to include, displays none except these
) );
}
?>
</code></pre>
| [
{
"answer_id": 298325,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>If you're outside the loop, use <a href=\"https://developer.wordpress.org/reference/functions/get_the_tag_list/\" rel=\"nofollow noreferrer\"><code>get_the_tag_list()</code></a>.</p>\n\n<pre><code>get_the_tag_list( '', ', ', '', $post->ID );\n</code></pre>\n\n<p>Or if you're inside the loop just use <a href=\"https://developer.wordpress.org/reference/functions/the_tags/\" rel=\"nofollow noreferrer\"><code>the_tags()</code></a>:</p>\n\n<pre><code>the_tags();\n</code></pre>\n"
},
{
"answer_id": 298592,
"author": "Anastis",
"author_id": 75475,
"author_profile": "https://wordpress.stackexchange.com/users/75475",
"pm_score": 1,
"selected": false,
"text": "<p><code>wp_tag_cloud()</code> accepts a <code>separator</code> parameter, so you can modify your call like this:</p>\n\n<pre><code>wp_tag_cloud( array(\n 'separator' => \", \", // Default value: \"\\n\"\n 'unit' => 'px', // font sizing choice (pt, em, px, etc)\n 'include' => $tag_ids, // ID's of tags to include, displays none except these\n) );\n</code></pre>\n"
}
]
| 2018/03/20 | [
"https://wordpress.stackexchange.com/questions/298324",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137481/"
]
| ```
<?php
// Get the assigned tag_id
$tag_ids = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );
// Check if there is any tag_ids, if print wp_tag_cloud
if ( $tag_ids ) {
wp_tag_cloud( array(
'unit' => 'px', // font sizing choice (pt, em, px, etc)
'include' => $tag_ids, // ID's of tags to include, displays none except these
) );
}
?>
``` | `wp_tag_cloud()` accepts a `separator` parameter, so you can modify your call like this:
```
wp_tag_cloud( array(
'separator' => ", ", // Default value: "\n"
'unit' => 'px', // font sizing choice (pt, em, px, etc)
'include' => $tag_ids, // ID's of tags to include, displays none except these
) );
``` |
298,355 | <p>I am trying to make a simple Gutenberg block which implements <code><InspectorControls></code>, but I'm getting a React error no matter which I component I use.</p>
<pre><code>const { __ } = wp.i18n;
const {
registerBlockType,
RichText,
AlignmentToolbar,
BlockControls,
InspectorControls,
TextControl
} = wp.blocks;
registerBlockType( 'gutenberg-examples/example-04-controls-esnext', {
title: __( 'Example: Controls (esnext)' ),
icon: 'universal-access-alt',
category: 'layout',
attributes: {
content: {
type: 'array',
selector: 'p',
},
},
edit: props => {
const {
attributes: {
content,
alignment,
text
},
focus,
className,
setFocus
} = props;
const onChangeContent = newContent => {
props.setAttributes( { content: newContent } );
};
const onChangeAlignment = newAlignment => {
props.setAttributes( { alignment: newAlignment } );
};
const onChangeText = newText => {
props.setAttributes( { text: newText } );
};
return (
<div>
{
!! focus && (
<InspectorControls>
<AlignmentToolbar
value={ alignment }
onChange={ onChangeAlignment }
/>
<TextControl
label='Additional CSS Class'
value={ text }
onChange={ onChangeText }
/>
</InspectorControls>
)
}
<RichText
className={ className }
style={ { textAlign: alignment } }
onChange={ onChangeContent }
value={ content }
focus={ focus }
onFocus={ setFocus }
/>
</div>
);
},
save: props => {
// ignore for now
}
} );
</code></pre>
<p>I'm using the 'create-guten-block' development kit.</p>
<p>Error:</p>
<pre><code>react-dom.min.3583f8be.js:162 Error: Minified React error #130; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=130&args[]=undefined&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at l (react-dom.min.3583f8be.js:12)
at qc (react-dom.min.3583f8be.js:43)
at K (react-dom.min.3583f8be.js:53)
at n (react-dom.min.3583f8be.js:57)
at react-dom.min.3583f8be.js:62
at f (react-dom.min.3583f8be.js:130)
at beginWork (react-dom.min.3583f8be.js:136)
at d (react-dom.min.3583f8be.js:158)
at f (react-dom.min.3583f8be.js:159)
at g (react-dom.min.3583f8be.js:159)
</code></pre>
| [
{
"answer_id": 298361,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p><code>InspectorControls</code> is deprecated as of v2.4</p>\n\n<p><a href=\"https://github.com/WordPress/gutenberg/blob/9ebb918176c1efd0c41561d67ea3273bae5d3d6a/docs/deprecated.md#L15\" rel=\"noreferrer\">https://github.com/WordPress/gutenberg/blob/9ebb918176c1efd0c41561d67ea3273bae5d3d6a/docs/deprecated.md#L15</a></p>\n\n<blockquote>\n <p>wp.blocks.InspectorControls.* components removed. Please use wp.components.* components instead.</p>\n</blockquote>\n\n<p>This is right at the top of your code:</p>\n\n<pre><code>const {\n registerBlockType,\n RichText,\n AlignmentToolbar,\n BlockControls,\n InspectorControls,\n TextControl\n} = wp.blocks;\n</code></pre>\n\n<p>Specifically:</p>\n\n<pre><code>const {\n ...\n InspectorControls,\n ...\n} = wp.blocks;\n</code></pre>\n\n<p>This is deprecated and won't work, as the deprecated doc on the Gutenberg repo says so:</p>\n\n<blockquote>\n <p>wp.blocks.InspectorControls.* components removed. Please use wp.components.* components instead.</p>\n</blockquote>\n"
},
{
"answer_id": 298395,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 4,
"selected": true,
"text": "<p><code>TextControl</code> is from <code>wp.components</code> not <code>wp.blocks</code>.</p>\n\n<pre><code>const {\n registerBlockType,\n RichText,\n AlignmentToolbar,\n BlockControls,\n InspectorControls,\n} = wp.blocks;\nconst {\n TextControl\n} = wp.components;\n</code></pre>\n\n<p>Changing that I was able to get your block to work fine instead of error in <code>Gutenberg 2.2.0</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/1axFc.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/1axFc.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 338523,
"author": "davi_singh",
"author_id": 158053,
"author_profile": "https://wordpress.stackexchange.com/users/158053",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure how many people also got stuck here. There are 2 files you need to edit, if your folder structure for the plugin is as follows</p>\n\n<pre><code>my-guten-block\n|-> /src\n||-> block.js\n|-> plugin.php\n</code></pre>\n\n<p>The <code>plugin.php</code> file you will need to add the dependency of <code>wp-editor</code> when enqueuing the script</p>\n\n<pre><code>const dependencies = array('wp-editor');\n\nwp_enqueue_script( handle: 'my-guten-block',\n src: plugin_dir_url(__FILE__) . 'src/block.js',\n dependencies)\n</code></pre>\n\n<p>Then you can add to the <code>block.js</code> file</p>\n\n<p><code>const { InspectorControls } = wp.editor</code></p>\n\n<p>And use as needed.</p>\n"
}
]
| 2018/03/20 | [
"https://wordpress.stackexchange.com/questions/298355",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111172/"
]
| I am trying to make a simple Gutenberg block which implements `<InspectorControls>`, but I'm getting a React error no matter which I component I use.
```
const { __ } = wp.i18n;
const {
registerBlockType,
RichText,
AlignmentToolbar,
BlockControls,
InspectorControls,
TextControl
} = wp.blocks;
registerBlockType( 'gutenberg-examples/example-04-controls-esnext', {
title: __( 'Example: Controls (esnext)' ),
icon: 'universal-access-alt',
category: 'layout',
attributes: {
content: {
type: 'array',
selector: 'p',
},
},
edit: props => {
const {
attributes: {
content,
alignment,
text
},
focus,
className,
setFocus
} = props;
const onChangeContent = newContent => {
props.setAttributes( { content: newContent } );
};
const onChangeAlignment = newAlignment => {
props.setAttributes( { alignment: newAlignment } );
};
const onChangeText = newText => {
props.setAttributes( { text: newText } );
};
return (
<div>
{
!! focus && (
<InspectorControls>
<AlignmentToolbar
value={ alignment }
onChange={ onChangeAlignment }
/>
<TextControl
label='Additional CSS Class'
value={ text }
onChange={ onChangeText }
/>
</InspectorControls>
)
}
<RichText
className={ className }
style={ { textAlign: alignment } }
onChange={ onChangeContent }
value={ content }
focus={ focus }
onFocus={ setFocus }
/>
</div>
);
},
save: props => {
// ignore for now
}
} );
```
I'm using the 'create-guten-block' development kit.
Error:
```
react-dom.min.3583f8be.js:162 Error: Minified React error #130; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=130&args[]=undefined&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at l (react-dom.min.3583f8be.js:12)
at qc (react-dom.min.3583f8be.js:43)
at K (react-dom.min.3583f8be.js:53)
at n (react-dom.min.3583f8be.js:57)
at react-dom.min.3583f8be.js:62
at f (react-dom.min.3583f8be.js:130)
at beginWork (react-dom.min.3583f8be.js:136)
at d (react-dom.min.3583f8be.js:158)
at f (react-dom.min.3583f8be.js:159)
at g (react-dom.min.3583f8be.js:159)
``` | `TextControl` is from `wp.components` not `wp.blocks`.
```
const {
registerBlockType,
RichText,
AlignmentToolbar,
BlockControls,
InspectorControls,
} = wp.blocks;
const {
TextControl
} = wp.components;
```
Changing that I was able to get your block to work fine instead of error in `Gutenberg 2.2.0`.
[](https://i.stack.imgur.com/1axFc.png) |
298,364 | <p>I want to add metabox to pull list of custom posts and select any two of them on edit or add post screen. And At last when the post is published display them on single post page. Please help me!
Any help will be appreciated....</p>
<pre><code> add_action( 'add_meta_boxes', function () {
add_meta_box(
'yourcustom_sectionid',
__( ' Custom Offer Section', 'yourtextdomain' ),
function ( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'yourcustom_noncename' );
$cstm = get_post_meta(get_the_ID(),'yourcustom_meta',true);
echo "<pre>".print_r($cstm,true)."</pre>";
$getPostsToSelect = get_posts('post_type=offers&numberposts=-1');
foreach ($getPostsToSelect as $aPostsToSelect) {
?>
<label>
<input
type='checkbox'
name='yourcustom_meta[]'
class='postsToSelect'
value='<?php echo $aPostsToSelect->ID ?>'
/>
<?php echo $aPostsToSelect->post_title ?>
</label><br />
<?php
}
},
'listing'
);
} );
</code></pre>
<p><strong>and then below:</strong></p>
<pre><code>echo "<script type='text/javascript'>
var limit = 2;
jQuery('input.single-checkbox').on('change', function(evt) {
if(jQuery('input.single-checkbox:checked').length > limit) {
this.checked = false;
}
});
</script>";
</code></pre>
<p><em>but the jquery does not seems to work to select the two checked boxes...</em>
<em>and after that problem please help me printing the the two selected checked posts.</em></p>
<p>the result i obtained till now is with 4 custom posts named offer
in the image shown below
<a href="https://i.stack.imgur.com/D2cW6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D2cW6.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 298372,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 3,
"selected": true,
"text": "<p>You can add a metabox in the edit screen with</p>\n\n<pre><code>add_action( 'add_meta_boxes', function () {\n add_meta_box(\n 'yourcustom_sectionid', \n __( ' Custom Meta Box', 'yourtextdomain' ), \n function ( $post ) {\n wp_nonce_field( plugin_basename( __FILE__ ), 'yourcustom_noncename' );\n $cstm = get_post_meta(get_the_ID(),'yourcustom_meta',true);\n echo \"<pre>\".print_r($cstm,true).\"</pre>\";\n }, \n 'page'\n );\n} );\n</code></pre>\n\n<p>You can query posts with <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> and add some check boxes inside that metabox</p>\n\n<pre><code>$getPostsToSelect = get_posts('post_type=post&numberposts=-1');\nforeach ($getPostsToSelect as $aPostsToSelect) {\n ?>\n <label>\n <input \n type='checkbox' \n name='yourcustom_meta[]' \n class='postsToSelect'\n value='<?php echo $aPostsToSelect->ID ?>'\n /> \n <?php echo $aPostsToSelect->post_title ?>\n </label><br />\n <?php\n}\n</code></pre>\n\n<p>You'd than need some jQuery to restrict to only 2 selected. It'd be somthing like</p>\n\n<pre><code>var limit = 2;\njQuery('input.single-checkbox').on('change', function(evt) {\n if(jQuery('input.single-checkbox:checked').length > limit) {\n this.checked = false;\n }\n});\n</code></pre>\n\n<p>You'd save it all with somthing like : </p>\n\n<pre><code>add_action( 'save_post', function ( $post_id ) {\n\n if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )\n return;\n if ( !wp_verify_nonce( $_POST['yourcustom_noncename'], plugin_basename( __FILE__ ) ) )\n return;\n if ( 'page' == $_POST['post_type'] ) { // not the Post Type\n if ( !current_user_can( 'edit_page', $post_id ) )\n return;\n } else {\n if ( !current_user_can( 'edit_post', $post_id ) )\n return;\n }\n\n update_post_meta($post_id,'yourcustom_meta',$_POST['yourcustom_meta']);\n});\n</code></pre>\n\n<p>Then in your <code>single.php</code>, or wherever your loop is that you want them to show, you'd just call them up:</p>\n\n<pre><code>$cstm = get_post_meta(get_the_ID(),'yourcustom_meta',true);\nforeach ($cstm as $aPostToDisplay) {\n echo \"<pre>{$aPostToDisplay->ID} - {$aPostToDisplay->post_title}</pre>\";\n}\n</code></pre>\n\n<p>Please note that I free handed this (not tested), so copy/paste will not work.. It's more of a logic guid. </p>\n\n<p>I've assumed without double checking that <code>name='yourcustom_meta[]'</code> will pass only the checked ones to <code>$_POST['yourcustom_meta']</code>, but you might want to confirm that.</p>\n\n<p>I've also used anonymous functions, which probably shouldn't be used if this is a for-public plugin/theme.</p>\n"
},
{
"answer_id": 342529,
"author": "Kolawole Emmanuel Izzy",
"author_id": 148083,
"author_profile": "https://wordpress.stackexchange.com/users/148083",
"pm_score": 1,
"selected": false,
"text": "<p>I know this question has been asked for a while but below is my own contribution;</p>\n\n<pre><code>add_action( 'add_meta_boxes', function () {\n add_meta_box(\n 'yourcustom_sectionid', \n __( ' Custom Meta Box', 'yourtextdomain' ), \n 'enter_your_callback_function_here', \n 'posttype_id',\n 'side',\n 'default'\n );\n } );\n\nfunction enter_your_callback_function_here( $post ) {\n wp_nonce_field( 'saving_postlist_data', 'postlist_metabox_wpnonce' );\n\n $value = get_post_meta( $post->ID, '_add_your_meta_key', true );\n\n echo \"<pre>\".print_r($value,true).\"</pre>\";//This is for testing purpose, remove when you're done, this is just to see that your selection is added to the array\n\n $getAllPostsToSelect = get_posts('post_type=PostTypeToGetListFrom&numberposts=-1');\n\n ?>\n <div class=\"List_wrapper\">\n <?php foreach ($getAllPostsToSelect as $dPostsToSelect): ?>\n <label>\n <input \n type='checkbox' \n name='_add_your_meta_key[]' \n class='postsToSelect'\n value='<?php echo $dPostsToSelect->ID ?>'\n <?php if ($value && in_array($dPostsToSelect->ID, $value) ? { echo ' checked=\"checked\"'; } ?>\n /> \n <?php echo $dPostsToSelect->post_title ?>\n </label><br />\n <?php endforeach ?>\n </div>\n <?php\n}\n\n// //Save The custom Meta Data\nfunction why_not_save_the_postlist_data( $post_id ) {\n //If nonce is not set by wordpress\n if ( ! isset( $_POST['postlist_metabox_wpnonce'] ) ) {\n return;\n }\n\n //If nonce is not verified by wordpress\n if ( ! wp_verify_nonce( $_POST['postlist_metabox_wpnonce'], 'saving_postlist_data' ) ) {\n return;\n }\n\n //If wordpress is doing auto-save, dont save metabox\n if ( define('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {\n return;\n }\n\n //If user cant edit post\n if ( ! current_user_can( 'edit_post', $post_id )) {\n return;\n }\n\n $data = $_POST['_add_your_meta_key'];\n\n //Update the Data\n update_post_meta( $post_id, '_add_your_meta_key', $data );\n}\nadd_action( 'save_post', 'why_not_save_the_postlist_data' );\n</code></pre>\n\n<p>Tested and worked. and you would get something like this;</p>\n\n<p><a href=\"https://i.stack.imgur.com/EoLRy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EoLRy.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can style it as you want, below is the CSS i used to style that above screenshot;</p>\n\n<pre><code>#yourcustom_sectionid .inside {\n padding-bottom: 40px;\n}\n#yourcustom_sectionid .inside .List_wrapper {\n height: 150px;\n overflow-y: auto;\n border: 1px solid #dddddd;\n background: #fdfdfd;\n padding: 10px;\n}\n</code></pre>\n\n<p><br><br>\n<strong>FRONT-END DISPLAY</strong><br>\nThe array stores the post IDs of the custom post type, so to get the post name and link in front-end, you need to do something like this;</p>\n\n<pre><code>global $post;\n\n$arrayOfIDs = get_post_meta( $post->ID, '_add_your_meta_key', true );\n\n<ul class=\"anythingHere\">\n <?php foreach ($arrayOfIDs as $getPost) : ?>\n <li><a href=\"<?php echo get_permalink($getPost); ?>\"><?php echo get_the_title($getPost); ?></a></li> \n <?php endforeach; ?>\n</ul>\n</code></pre>\n\n<p>Then the Output will look like this, with some CSS styling;<br><br>\n<a href=\"https://i.stack.imgur.com/4GGKA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4GGKA.png\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2018/03/20 | [
"https://wordpress.stackexchange.com/questions/298364",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140003/"
]
| I want to add metabox to pull list of custom posts and select any two of them on edit or add post screen. And At last when the post is published display them on single post page. Please help me!
Any help will be appreciated....
```
add_action( 'add_meta_boxes', function () {
add_meta_box(
'yourcustom_sectionid',
__( ' Custom Offer Section', 'yourtextdomain' ),
function ( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'yourcustom_noncename' );
$cstm = get_post_meta(get_the_ID(),'yourcustom_meta',true);
echo "<pre>".print_r($cstm,true)."</pre>";
$getPostsToSelect = get_posts('post_type=offers&numberposts=-1');
foreach ($getPostsToSelect as $aPostsToSelect) {
?>
<label>
<input
type='checkbox'
name='yourcustom_meta[]'
class='postsToSelect'
value='<?php echo $aPostsToSelect->ID ?>'
/>
<?php echo $aPostsToSelect->post_title ?>
</label><br />
<?php
}
},
'listing'
);
} );
```
**and then below:**
```
echo "<script type='text/javascript'>
var limit = 2;
jQuery('input.single-checkbox').on('change', function(evt) {
if(jQuery('input.single-checkbox:checked').length > limit) {
this.checked = false;
}
});
</script>";
```
*but the jquery does not seems to work to select the two checked boxes...*
*and after that problem please help me printing the the two selected checked posts.*
the result i obtained till now is with 4 custom posts named offer
in the image shown below
[](https://i.stack.imgur.com/D2cW6.png) | You can add a metabox in the edit screen with
```
add_action( 'add_meta_boxes', function () {
add_meta_box(
'yourcustom_sectionid',
__( ' Custom Meta Box', 'yourtextdomain' ),
function ( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'yourcustom_noncename' );
$cstm = get_post_meta(get_the_ID(),'yourcustom_meta',true);
echo "<pre>".print_r($cstm,true)."</pre>";
},
'page'
);
} );
```
You can query posts with [`get_posts()`](https://codex.wordpress.org/Template_Tags/get_posts) and add some check boxes inside that metabox
```
$getPostsToSelect = get_posts('post_type=post&numberposts=-1');
foreach ($getPostsToSelect as $aPostsToSelect) {
?>
<label>
<input
type='checkbox'
name='yourcustom_meta[]'
class='postsToSelect'
value='<?php echo $aPostsToSelect->ID ?>'
/>
<?php echo $aPostsToSelect->post_title ?>
</label><br />
<?php
}
```
You'd than need some jQuery to restrict to only 2 selected. It'd be somthing like
```
var limit = 2;
jQuery('input.single-checkbox').on('change', function(evt) {
if(jQuery('input.single-checkbox:checked').length > limit) {
this.checked = false;
}
});
```
You'd save it all with somthing like :
```
add_action( 'save_post', function ( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !wp_verify_nonce( $_POST['yourcustom_noncename'], plugin_basename( __FILE__ ) ) )
return;
if ( 'page' == $_POST['post_type'] ) { // not the Post Type
if ( !current_user_can( 'edit_page', $post_id ) )
return;
} else {
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
update_post_meta($post_id,'yourcustom_meta',$_POST['yourcustom_meta']);
});
```
Then in your `single.php`, or wherever your loop is that you want them to show, you'd just call them up:
```
$cstm = get_post_meta(get_the_ID(),'yourcustom_meta',true);
foreach ($cstm as $aPostToDisplay) {
echo "<pre>{$aPostToDisplay->ID} - {$aPostToDisplay->post_title}</pre>";
}
```
Please note that I free handed this (not tested), so copy/paste will not work.. It's more of a logic guid.
I've assumed without double checking that `name='yourcustom_meta[]'` will pass only the checked ones to `$_POST['yourcustom_meta']`, but you might want to confirm that.
I've also used anonymous functions, which probably shouldn't be used if this is a for-public plugin/theme. |
298,445 | <p>I have created a new WordPress site in a folder inside of another WordPress site.</p>
<p>Example
- mainsite.com
- mainsite.com/secondsite</p>
<p>I have created a plugin and I use <code>$wpdb</code> to insert data to the database and the plugin inserts the data to the database of the first/parent site.</p>
<p>The code I use to include <code>$wpdb</code> is the following:</p>
<pre><code>$path = $_SERVER['DOCUMENT_ROOT'];
include $path . '/wp-load.php';
include $path . '/wp-config.php';
include $path . '/wp-includes/wp-db.php';
global $wpdb;
</code></pre>
<p>How can I fix that?</p>
| [
{
"answer_id": 298446,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p><code>$_SERVER['DOCUMENT_ROOT'];</code> is not going to include <code>secondsite</code>. So all the files, including <code>wp-config.php</code> with the database details, are coming from the root public directory.</p>\n\n<p>To get the current directory, including subdirectories, use any of these:</p>\n\n<pre><code>getcwd();\n\ndirname(__FILE__);\n\nbasename(__DIR__);\n</code></pre>\n\n<p>But if your file is in a deeper folder, you can't find the <code>secondsite</code> directory without specifying it (or scanning directories to find a WordPress installation). So you need to manually specify it like so:</p>\n\n<pre><code>$path = $_SERVER['DOCUMENT_ROOT'] . '/secondsite';\n</code></pre>\n\n<p>But your problem is that you're doing AJAX wrong. You shouldn't be sending AJAX requests directly to a file in your plugin. You should be <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/\" rel=\"nofollow noreferrer\">using the AJAX hooks</a> or <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">adding a custom endpoint to the REST API</a>.</p>\n"
},
{
"answer_id": 298476,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>There are to major problems with your code.</p>\n\n<p>First one is that you clearly include files of main/parent WordPress:</p>\n\n<pre><code>$path = $_SERVER['DOCUMENT_ROOT'];\ninclude $path . '/wp-load.php';\ninclude $path . '/wp-config.php';\n</code></pre>\n\n<p>The above part of code will include mainsite.com/wp-config.php, so the rest of your code will connect to DB of that site - that is what your code should be doing...</p>\n\n<p>If you'd like to connect to correct DB, then you should use something like this:</p>\n\n<pre><code>$path = $_SERVER['DOCUMENT_ROOT'] . '/secondsite'; // <- change it to proper folder name\ninclude $path . '/wp-load.php';\ninclude $path . '/wp-config.php';\ninclude $path . '/wp-includes/wp-db.php';\n\nglobal $wpdb;\n</code></pre>\n\n<p>Now, when used on secondsite, it will connect to correct DB, but... <strong>This code still isn't correct...</strong></p>\n\n<p>You should never create PHP files that will process requests this way. All AJAX requests should be processed by <code>wp-admin/admin-ajax.php</code> or by REST API.</p>\n\n<p>Here is article from Codex explaining how to use AJAX in plugins properly:\n<a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n"
}
]
| 2018/03/21 | [
"https://wordpress.stackexchange.com/questions/298445",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110915/"
]
| I have created a new WordPress site in a folder inside of another WordPress site.
Example
- mainsite.com
- mainsite.com/secondsite
I have created a plugin and I use `$wpdb` to insert data to the database and the plugin inserts the data to the database of the first/parent site.
The code I use to include `$wpdb` is the following:
```
$path = $_SERVER['DOCUMENT_ROOT'];
include $path . '/wp-load.php';
include $path . '/wp-config.php';
include $path . '/wp-includes/wp-db.php';
global $wpdb;
```
How can I fix that? | `$_SERVER['DOCUMENT_ROOT'];` is not going to include `secondsite`. So all the files, including `wp-config.php` with the database details, are coming from the root public directory.
To get the current directory, including subdirectories, use any of these:
```
getcwd();
dirname(__FILE__);
basename(__DIR__);
```
But if your file is in a deeper folder, you can't find the `secondsite` directory without specifying it (or scanning directories to find a WordPress installation). So you need to manually specify it like so:
```
$path = $_SERVER['DOCUMENT_ROOT'] . '/secondsite';
```
But your problem is that you're doing AJAX wrong. You shouldn't be sending AJAX requests directly to a file in your plugin. You should be [using the AJAX hooks](https://developer.wordpress.org/plugins/javascript/ajax/) or [adding a custom endpoint to the REST API](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/). |
298,451 | <p>Hello I'm currently developing a wordpress application. I have been able to accomplish almost everything the application needs. I was even able to use Jquery-Ajax to insert data into my custom database table and get a background feedback of the submission.</p>
<p>But where I'm stock right now is autopopulating my textfields based on a dropdown selection. I have read several articles online and the answer I saw here <a href="https://wordpress.stackexchange.com/questions/112998/why-is-my-ajax-call-not-working">Why is my AJAX call not working?</a> but I still can't fix the problem Below are my codes:</p>
<pre><code>/* Fetching file from the database*/
wp_enqueue_script('jquery');
function ajaxAutopopulate() {
// The $_REQUEST contains all the data sent via ajax
if ( isset( $_REQUEST['package'] ) ) {
$birdday = $_REQUEST['package']; // department day
global $wpdb;
// Let's take the data that was sent and do something with it
$results = $wpdb->get_results("SELECT body_weight, daily_intake, fcr FROM bird_weight WHERE day=$birdday");
$users_arr = array();
foreach ( $results as $result ) {
$bweight = $result->body_weight;
$dintake = $result->daily_intake;
$fcr = $result->fcr;
$users_arr[] = array("body_weight" => $bweight, "daily_intake" =>$dintake,"fcr"=>$fcr);
}
// encoding array to json format
echo json_encode( $users_arr);
} else {
echo "error";
}
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_ajaxAutopopulate', 'ajaxAutopopulate' );
add_action( 'wp_ajax_nopriv_ajaxAutopopulate', 'ajaxAutopopulate' );
//The Html Form on the frontend
echo
'<form action="" name="mybirdweight" method="post">
<div>
<select id="days" name="days">
<option value=" " > Select Your Bird Age</option>
<option value="1"> 1</option>
<option value="2"> 2</option>
</select>
</div>
<div>
<p>Body Weight</p>
<input id="bweight" type="text" name="bweight" value=""/>
</div>
<div>
<p>Daily Intake</p>
<input id="dintake" type="text" name="dintake" value=""/>
</div>
<div>
<p>FCR</p>
<input id="fcr" type="text" name="fcr" value=""/>
</div>
</form>';
//Here is the jquery-ajax javascript
/* the jquery ajax request*/
echo <<< END
<script type="text/javascript">
jQuery(document).ready(function(){
// On change of the dropdown do the ajax
jQuery("#days").change(function() {
var package = jQuery(this).val();
jQuery.ajax({
// Change the link to the file you are using
url: "/wp-admin/admin-ajax.php",
type: 'POST',
// This just sends the value of the dropdown
data: {package: package},
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var Vals =JSON.parse(response);
// These are the inputs that will populate
jQuery("input[name='bweight']").val(Vals.body_weight);
jQuery("input[name='dintake']").val(Vals.daily_intake);
jQuery("input[name='fcr']").val(Vals.fcr);
}
});
});
});
</script>
END;
</code></pre>
<p>Please where am I missing it?</p>
| [
{
"answer_id": 298455,
"author": "Sumit Parkash",
"author_id": 140109,
"author_profile": "https://wordpress.stackexchange.com/users/140109",
"pm_score": 1,
"selected": false,
"text": "<p>You need to change the data that you are sending in the ajax request.\nFor ajax to work in WordPress you need to send the <strong>action</strong> variable in ajax post request. \nChange </p>\n\n<pre><code>data: {package: package},\n</code></pre>\n\n<p>to </p>\n\n<pre><code>data: {action: 'ajaxAutopopulate', package: package}\n</code></pre>\n\n<p>Also you can use the wordpress default function </p>\n\n<pre><code>wp_send_json( $response ) \n</code></pre>\n\n<p>for encoding of data\nand</p>\n\n<pre><code> admin_url( 'admin-ajax.php' )\n</code></pre>\n\n<p>for the ajax file url.</p>\n\n<p>If you have your js code in a separate file , you may need to use</p>\n\n<pre><code>wp_localize_script\n</code></pre>\n\n<p>to pass the value to the js file</p>\n"
},
{
"answer_id": 299394,
"author": "Emekrus",
"author_id": 140101,
"author_profile": "https://wordpress.stackexchange.com/users/140101",
"pm_score": 0,
"selected": false,
"text": "<p>I wasn't successful with the jquery/Ajax autopopulate, so I have been able to get the Job done from the server side, using PHP to fetch the information I need to display, on form submission.</p>\n"
}
]
| 2018/03/21 | [
"https://wordpress.stackexchange.com/questions/298451",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140101/"
]
| Hello I'm currently developing a wordpress application. I have been able to accomplish almost everything the application needs. I was even able to use Jquery-Ajax to insert data into my custom database table and get a background feedback of the submission.
But where I'm stock right now is autopopulating my textfields based on a dropdown selection. I have read several articles online and the answer I saw here [Why is my AJAX call not working?](https://wordpress.stackexchange.com/questions/112998/why-is-my-ajax-call-not-working) but I still can't fix the problem Below are my codes:
```
/* Fetching file from the database*/
wp_enqueue_script('jquery');
function ajaxAutopopulate() {
// The $_REQUEST contains all the data sent via ajax
if ( isset( $_REQUEST['package'] ) ) {
$birdday = $_REQUEST['package']; // department day
global $wpdb;
// Let's take the data that was sent and do something with it
$results = $wpdb->get_results("SELECT body_weight, daily_intake, fcr FROM bird_weight WHERE day=$birdday");
$users_arr = array();
foreach ( $results as $result ) {
$bweight = $result->body_weight;
$dintake = $result->daily_intake;
$fcr = $result->fcr;
$users_arr[] = array("body_weight" => $bweight, "daily_intake" =>$dintake,"fcr"=>$fcr);
}
// encoding array to json format
echo json_encode( $users_arr);
} else {
echo "error";
}
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_ajaxAutopopulate', 'ajaxAutopopulate' );
add_action( 'wp_ajax_nopriv_ajaxAutopopulate', 'ajaxAutopopulate' );
//The Html Form on the frontend
echo
'<form action="" name="mybirdweight" method="post">
<div>
<select id="days" name="days">
<option value=" " > Select Your Bird Age</option>
<option value="1"> 1</option>
<option value="2"> 2</option>
</select>
</div>
<div>
<p>Body Weight</p>
<input id="bweight" type="text" name="bweight" value=""/>
</div>
<div>
<p>Daily Intake</p>
<input id="dintake" type="text" name="dintake" value=""/>
</div>
<div>
<p>FCR</p>
<input id="fcr" type="text" name="fcr" value=""/>
</div>
</form>';
//Here is the jquery-ajax javascript
/* the jquery ajax request*/
echo <<< END
<script type="text/javascript">
jQuery(document).ready(function(){
// On change of the dropdown do the ajax
jQuery("#days").change(function() {
var package = jQuery(this).val();
jQuery.ajax({
// Change the link to the file you are using
url: "/wp-admin/admin-ajax.php",
type: 'POST',
// This just sends the value of the dropdown
data: {package: package},
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var Vals =JSON.parse(response);
// These are the inputs that will populate
jQuery("input[name='bweight']").val(Vals.body_weight);
jQuery("input[name='dintake']").val(Vals.daily_intake);
jQuery("input[name='fcr']").val(Vals.fcr);
}
});
});
});
</script>
END;
```
Please where am I missing it? | You need to change the data that you are sending in the ajax request.
For ajax to work in WordPress you need to send the **action** variable in ajax post request.
Change
```
data: {package: package},
```
to
```
data: {action: 'ajaxAutopopulate', package: package}
```
Also you can use the wordpress default function
```
wp_send_json( $response )
```
for encoding of data
and
```
admin_url( 'admin-ajax.php' )
```
for the ajax file url.
If you have your js code in a separate file , you may need to use
```
wp_localize_script
```
to pass the value to the js file |
298,453 | <p>I'm currently working with php 7.2 and when I use get_the_content() or get_the_excerpt() outside of a single template, in the functions.php for example, I get the following Warning:</p>
<p><em>Warning: count(): Parameter must be an array or an object that implements Countable in /Applications/MAMP/htdocs/wordpress/wp-kona/wp-includes/post-template.php on line 284</em></p>
<p>What's wrong with it? Is it a wordpress core bug? Am I missing something.</p>
| [
{
"answer_id": 320699,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 0,
"selected": false,
"text": "<p>This bug related to WordPress core bug\n<a href=\"https://core.trac.wordpress.org/ticket/42814\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/42814</a></p>\n\n<p>Most often it occurs when you call the function <code>get_the_excerpt</code> or <code>get_the_content</code> outside the Loop provided that excerpt or content is empty.</p>\n\n<p>So to fix it yourself you should find error place and check excerpt/content existing manually.</p>\n\n<p>For example:</p>\n\n<pre><code>if(has_excerpt($post_id)) {\n $meta[] = sprintf('<meta name=\"description\" content=\"%s\">',\n get_the_excerpt($post_id)\n );\n}\n</code></pre>\n"
},
{
"answer_id": 324581,
"author": "John Zenith",
"author_id": 136579,
"author_profile": "https://wordpress.stackexchange.com/users/136579",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, I already knew the cause of what you're experiencing:</p>\n\n<h1>The $page and $pages global variable have not been set up and a call to <code>get_the_content</code> or <code>get_the_excerpt</code> would return that error: count(pages)</h1>\n\n<p>That said, pages global variable is set to null, calling count(pages) triggers that error because a null value cannot be counted.</p>\n\n<p>To fix this, one can easily tell that you're calling <code>get_the_content</code> or <code>get_the_excerpt</code> outside the loop.</p>\n\n<p>So you have to set up the post data correctly before usage, that's what the loop is meant to do:</p>\n\n<pre>\nwhile ( have_post(): the_post() ) :\n // get_the_content() or get_the_excerpt() will work fine now\n the_content();\nendwhile;\n</pre>\n"
},
{
"answer_id": 330316,
"author": "Dimitar Radev Radev",
"author_id": 35852,
"author_profile": "https://wordpress.stackexchange.com/users/35852",
"pm_score": 0,
"selected": false,
"text": "<p>If someone bumps in to this issue, the solution is to get the_content from the meta field and run it trough the_content filter like this:</p>\n\n<p><code>apply_filters('the_content', get_post_field('post_content', $post->id));</code></p>\n\n<p>I made a short video explayining the whole thing if you wait untill the TLDR section...\n<a href=\"https://www.youtube.com/watch?v=vMguTNzFoUk\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=vMguTNzFoUk</a></p>\n"
},
{
"answer_id": 333373,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 1,
"selected": false,
"text": "<p>As of v5.2, this will no longer be an issue. <code>get_the_content()</code> and <code>wp_trim_excerpt()</code> are getting an optional new parameter (third and second respectively) of <code>$post</code> so you can use it outside the loop, bringing it in line with the functionality of all the other <code>get_the_*</code> functions. It only took 16 years... <a href=\"https://core.trac.wordpress.org/changeset/44941\" rel=\"nofollow noreferrer\">Reference on Trac</a></p>\n"
}
]
| 2018/03/21 | [
"https://wordpress.stackexchange.com/questions/298453",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28159/"
]
| I'm currently working with php 7.2 and when I use get\_the\_content() or get\_the\_excerpt() outside of a single template, in the functions.php for example, I get the following Warning:
*Warning: count(): Parameter must be an array or an object that implements Countable in /Applications/MAMP/htdocs/wordpress/wp-kona/wp-includes/post-template.php on line 284*
What's wrong with it? Is it a wordpress core bug? Am I missing something. | Yes, I already knew the cause of what you're experiencing:
The $page and $pages global variable have not been set up and a call to `get_the_content` or `get_the_excerpt` would return that error: count(pages)
====================================================================================================================================================
That said, pages global variable is set to null, calling count(pages) triggers that error because a null value cannot be counted.
To fix this, one can easily tell that you're calling `get_the_content` or `get_the_excerpt` outside the loop.
So you have to set up the post data correctly before usage, that's what the loop is meant to do:
```
while ( have_post(): the_post() ) :
// get_the_content() or get_the_excerpt() will work fine now
the_content();
endwhile;
``` |
298,459 | <p>I am simply trying to get rid of the Read More button on my blog posts.</p>
<p>I would like my blog to show my full article.</p>
| [
{
"answer_id": 320699,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 0,
"selected": false,
"text": "<p>This bug related to WordPress core bug\n<a href=\"https://core.trac.wordpress.org/ticket/42814\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/42814</a></p>\n\n<p>Most often it occurs when you call the function <code>get_the_excerpt</code> or <code>get_the_content</code> outside the Loop provided that excerpt or content is empty.</p>\n\n<p>So to fix it yourself you should find error place and check excerpt/content existing manually.</p>\n\n<p>For example:</p>\n\n<pre><code>if(has_excerpt($post_id)) {\n $meta[] = sprintf('<meta name=\"description\" content=\"%s\">',\n get_the_excerpt($post_id)\n );\n}\n</code></pre>\n"
},
{
"answer_id": 324581,
"author": "John Zenith",
"author_id": 136579,
"author_profile": "https://wordpress.stackexchange.com/users/136579",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, I already knew the cause of what you're experiencing:</p>\n\n<h1>The $page and $pages global variable have not been set up and a call to <code>get_the_content</code> or <code>get_the_excerpt</code> would return that error: count(pages)</h1>\n\n<p>That said, pages global variable is set to null, calling count(pages) triggers that error because a null value cannot be counted.</p>\n\n<p>To fix this, one can easily tell that you're calling <code>get_the_content</code> or <code>get_the_excerpt</code> outside the loop.</p>\n\n<p>So you have to set up the post data correctly before usage, that's what the loop is meant to do:</p>\n\n<pre>\nwhile ( have_post(): the_post() ) :\n // get_the_content() or get_the_excerpt() will work fine now\n the_content();\nendwhile;\n</pre>\n"
},
{
"answer_id": 330316,
"author": "Dimitar Radev Radev",
"author_id": 35852,
"author_profile": "https://wordpress.stackexchange.com/users/35852",
"pm_score": 0,
"selected": false,
"text": "<p>If someone bumps in to this issue, the solution is to get the_content from the meta field and run it trough the_content filter like this:</p>\n\n<p><code>apply_filters('the_content', get_post_field('post_content', $post->id));</code></p>\n\n<p>I made a short video explayining the whole thing if you wait untill the TLDR section...\n<a href=\"https://www.youtube.com/watch?v=vMguTNzFoUk\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=vMguTNzFoUk</a></p>\n"
},
{
"answer_id": 333373,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 1,
"selected": false,
"text": "<p>As of v5.2, this will no longer be an issue. <code>get_the_content()</code> and <code>wp_trim_excerpt()</code> are getting an optional new parameter (third and second respectively) of <code>$post</code> so you can use it outside the loop, bringing it in line with the functionality of all the other <code>get_the_*</code> functions. It only took 16 years... <a href=\"https://core.trac.wordpress.org/changeset/44941\" rel=\"nofollow noreferrer\">Reference on Trac</a></p>\n"
}
]
| 2018/03/21 | [
"https://wordpress.stackexchange.com/questions/298459",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140110/"
]
| I am simply trying to get rid of the Read More button on my blog posts.
I would like my blog to show my full article. | Yes, I already knew the cause of what you're experiencing:
The $page and $pages global variable have not been set up and a call to `get_the_content` or `get_the_excerpt` would return that error: count(pages)
====================================================================================================================================================
That said, pages global variable is set to null, calling count(pages) triggers that error because a null value cannot be counted.
To fix this, one can easily tell that you're calling `get_the_content` or `get_the_excerpt` outside the loop.
So you have to set up the post data correctly before usage, that's what the loop is meant to do:
```
while ( have_post(): the_post() ) :
// get_the_content() or get_the_excerpt() will work fine now
the_content();
endwhile;
``` |
298,481 | <p>I created my own contact form and I'm using <code>WP_List_Table</code> to display submitted forms in wp-admin. I edited <a href="https://github.com/pmbaldha/WP-Custom-List-Table-With-Database-Example" rel="nofollow noreferrer">this</a> example WP_List_Table from <strong>github</strong> and it works fine. </p>
<p>This is how I add my custom admin menu page:</p>
<pre><code>function contact_form_create() {
add_menu_page('Contact Forms', 'Contact Forms', 'administrator', 'contact-form', 'contact_form_page_handler');
}
add_action('admin_menu', 'contact_form_create');
</code></pre>
<p>But now I want to make a notification. So when visitor submit a contact form, then my table shows me a notification in wp-admin like this:</p>
<p><img src="https://s14.postimg.org/8kod08mcx/indir.png"></p>
| [
{
"answer_id": 298491,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": true,
"text": "<p>OK, so it has nothing to do with WP_List_Table, to be precise. All you need to do is to add some additional info during registration of your custom admin page.</p>\n\n<p>There are two classes used by WordPress to display these notification bubbles:</p>\n\n<ul>\n<li>update-plugins</li>\n<li>awaiting-mod</li>\n</ul>\n\n<p>Your notifications have nothing to do with plugins, so it will be nicer to use the second class. You should change your function like this:</p>\n\n<pre><code>function contact_form_create() {\n $notification_count = 2; // <- here you should get correct count of forms submitted since last visit\n\n add_menu_page(\n 'Contact Forms',\n $notification_count ? sprintf('Contact Forms <span class=\"awaiting-mod\">%d</span>', $notification_count) : 'Contact Forms',\n 'administrator', // <- it would be nicer to use capability in here 'manage_options' \n 'contact-form',\n 'contact_form_page_handler'\n );\n}\n\nadd_action('admin_menu', 'contact_form_create');\n</code></pre>\n\n<p>So the main change is that if there are some notifications to show, then we add <code><span class=\"awaiting-mod\">%d</span></code> to title of that page.</p>\n\n<p>The only thing you'll have to do now is to get correct number of form submits since last visit. The easiest way to do this would be store last ID of submited form record in your custom DB table as some option and counting new records based on this ID. But it's hard to say exactly how to count them, since I have no info about how you store this submitted forms and so on, so I leave this part to you.</p>\n"
},
{
"answer_id": 387099,
"author": "revive",
"author_id": 8645,
"author_profile": "https://wordpress.stackexchange.com/users/8645",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a (large) snippet I use for Gravity Forms specifically, but can be adapted to get the count from wherever you need it.</p>\n<p>This snippet gets the count for all the forms in the array() within the count_entries() call so the parent menu items shows ALL unread entries (from the form IDs in that array)</p>\n<p>Then as I build the menu, I change the ID in both the count_entries() call AND the URL - see comments in the snippet.</p>\n<pre><code>function register_my_custom_menu_page() {\n $search_criteria = array(\n 'status' => 'active', //Active forms \n 'field_filters' => array( //which fields to search\n array(\n 'key' => 'is_read', 'value' => false, // let's just get the count for entries that we haven't read yet.\n )\n )\n );\n\n // Add the form IDs to the array below, the parent menu will show ALL unread entries for these forms\n $notification_count = GFAPI::count_entries( array(1,4,5,6,11,13), $search_criteria );\n \n add_menu_page(\n 'Full Quote Form submissions', // Page Title\n // here we're going to use the var $notification_count to get ALL the form IDS and their counts... just for the parent menu item\n $notification_count ? sprintf( 'Quotes <span class="awaiting-mod">%d</span>', $notification_count ) : 'View Quotes',\n 'manage_options', // Capabilities \n 'admin.php?page=gf_entries&id=13', // menu slug\n '', // callback function\n 'dashicons-format-aside', // icon URL\n 6 // position\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'View Full Quotes', // name of the page\n // The ID on the next line, 13 in this example, matches the form ID in the URL on the LAST line. Notice we're NOT using the var $notification_count from above, as that contains the entry count for ALL the forms\n GFAPI::count_entries( 13, $search_criteria ) ? sprintf( 'Full Quotes <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 13, $search_criteria ) ) : 'Full Quotes',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call\n 'admin.php?page=gf_entries&id=13'\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'View Short Quotes', // name of the page\n // The ID on the next line, 1 in this example, matches the form ID in the URL on the LAST line. \n GFAPI::count_entries( 1, $search_criteria ) ? sprintf( 'Short Quotes <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 1, $search_criteria ) ) : 'Short Quotes',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call\n 'admin.php?page=gf_entries&id=1'\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'Sell Your Equipment', // name of the page\n // The ID on the next line, 5 in this example, matches the form ID in the URL on the LAST line. \n GFAPI::count_entries( 5, $search_criteria ) ? sprintf( 'Selling Equip <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 5, $search_criteria ) ) : 'Selling Equip',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call\n 'admin.php?page=gf_entries&id=5'\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'Equipment Wanted', // name of the page\n // The ID on the next line, 6 in this example, matches the form ID in the URL on the LAST line. \n GFAPI::count_entries( 6, $search_criteria ) ? sprintf( 'Equip Wanted <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 6, $search_criteria ) ) : 'Equip Wanted',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call \n 'admin.php?page=gf_entries&id=6'\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'Appraisal Requests', // name of the page\n // The ID on the next line, 11 in this example, matches the form ID in the URL on the LAST line. \n GFAPI::count_entries( 11, $search_criteria ) ? sprintf( 'Appraisal Requests <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 11, $search_criteria ) ) : 'Appraisal Requests',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call\n 'admin.php?page=gf_entries&id=11'\n );\n add_submenu_page( \n 'admin.php?page=gf_entries&id=13', // this needs to match menu slug of the parent\n 'Contact Form', // name of the page\n // The ID on the next line, 4 in this example, matches the form ID in the URL on the LAST line. \n GFAPI::count_entries( 4, $search_criteria ) ? sprintf( 'Contact Form <span class="awaiting-mod">%d</span>', GFAPI::count_entries( 4, $search_criteria ) ) : 'Contact Form',\n 'manage_options', \n // make sure to change the ID on the end of this URL to the form you want to point to, AND make sure it matches the ID two lines above in the count_entries() call\n 'admin.php?page=gf_entries&id=4'\n );\n \n}\nadd_action( 'admin_menu', 'register_my_custom_menu_page' );\n</code></pre>\n"
}
]
| 2018/03/21 | [
"https://wordpress.stackexchange.com/questions/298481",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133897/"
]
| I created my own contact form and I'm using `WP_List_Table` to display submitted forms in wp-admin. I edited [this](https://github.com/pmbaldha/WP-Custom-List-Table-With-Database-Example) example WP\_List\_Table from **github** and it works fine.
This is how I add my custom admin menu page:
```
function contact_form_create() {
add_menu_page('Contact Forms', 'Contact Forms', 'administrator', 'contact-form', 'contact_form_page_handler');
}
add_action('admin_menu', 'contact_form_create');
```
But now I want to make a notification. So when visitor submit a contact form, then my table shows me a notification in wp-admin like this:
 | OK, so it has nothing to do with WP\_List\_Table, to be precise. All you need to do is to add some additional info during registration of your custom admin page.
There are two classes used by WordPress to display these notification bubbles:
* update-plugins
* awaiting-mod
Your notifications have nothing to do with plugins, so it will be nicer to use the second class. You should change your function like this:
```
function contact_form_create() {
$notification_count = 2; // <- here you should get correct count of forms submitted since last visit
add_menu_page(
'Contact Forms',
$notification_count ? sprintf('Contact Forms <span class="awaiting-mod">%d</span>', $notification_count) : 'Contact Forms',
'administrator', // <- it would be nicer to use capability in here 'manage_options'
'contact-form',
'contact_form_page_handler'
);
}
add_action('admin_menu', 'contact_form_create');
```
So the main change is that if there are some notifications to show, then we add `<span class="awaiting-mod">%d</span>` to title of that page.
The only thing you'll have to do now is to get correct number of form submits since last visit. The easiest way to do this would be store last ID of submited form record in your custom DB table as some option and counting new records based on this ID. But it's hard to say exactly how to count them, since I have no info about how you store this submitted forms and so on, so I leave this part to you. |
298,525 | <p>I am using this query for my loop and it is working except when <code>meta_value</code> is empty. In this case it returns empty result. Instead I want to get all results when <code>meta_value</code> is empty.</p>
<p>Here is my code</p>
<pre><code>$query = new WP_Query( array(
'post_type' => 'my_post_type',
'meta_query' => array(
array(
'key' => 'state',
'value' => 'Alabama',
),
array(
'key' => 'country',
'value' => $region,
),
),
) );
</code></pre>
<p>I want to get all results in state Alabama when variable region will be empty. Any suggestion about this will be much appreciated.</p>
| [
{
"answer_id": 298531,
"author": "wplearner",
"author_id": 120693,
"author_profile": "https://wordpress.stackexchange.com/users/120693",
"pm_score": 0,
"selected": false,
"text": "<p>This code is working for me </p>\n\n<pre><code>$query = new WP_Query( array(\n 'post_type' => 'my_post_type',\n 'meta_query' => array(\n array(\n 'key' => 'state',\n 'value' => 'Alabama',\n ),\n array(\n 'key' => 'country',\n 'value' => $region,\n 'compare' => $region ? \"=\" : \"!=\",\n ),\n ),\n ));\n</code></pre>\n"
},
{
"answer_id": 298562,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>If I understand your question correctly, you want to query for region field only if <code>$region</code> variable is not empty? If so, this should work and it will be much prettier code than the one you suggested:</p>\n\n<pre><code>$meta_query = array(\n array(\n 'key' => 'state',\n 'value' => 'Alabama',\n ),\n);\n\nif ( $region ) {\n $meta_query[] = array(\n 'key' => 'country',\n 'value' => $region,\n );\n}\n\n$query = new WP_Query( array(\n 'post_type' => 'my_post_type',\n 'meta_query' => $meta_query\n) );\n</code></pre>\n"
}
]
| 2018/03/21 | [
"https://wordpress.stackexchange.com/questions/298525",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120693/"
]
| I am using this query for my loop and it is working except when `meta_value` is empty. In this case it returns empty result. Instead I want to get all results when `meta_value` is empty.
Here is my code
```
$query = new WP_Query( array(
'post_type' => 'my_post_type',
'meta_query' => array(
array(
'key' => 'state',
'value' => 'Alabama',
),
array(
'key' => 'country',
'value' => $region,
),
),
) );
```
I want to get all results in state Alabama when variable region will be empty. Any suggestion about this will be much appreciated. | If I understand your question correctly, you want to query for region field only if `$region` variable is not empty? If so, this should work and it will be much prettier code than the one you suggested:
```
$meta_query = array(
array(
'key' => 'state',
'value' => 'Alabama',
),
);
if ( $region ) {
$meta_query[] = array(
'key' => 'country',
'value' => $region,
);
}
$query = new WP_Query( array(
'post_type' => 'my_post_type',
'meta_query' => $meta_query
) );
``` |
298,551 | <p>Is there a wordpress function like - </p>
<p><strong>If someone recently commented in one of my posts (not other author post), I want his/her ID?</strong> </p>
<p>If there is no function like that, how can I achieve it? </p>
<hr>
<p>Actually, I am building a notification system and it will be something like this</p>
<p><strong><em>UserName</strong> is commented on your <strong>postTitle</strong>.</em></p>
| [
{
"answer_id": 298531,
"author": "wplearner",
"author_id": 120693,
"author_profile": "https://wordpress.stackexchange.com/users/120693",
"pm_score": 0,
"selected": false,
"text": "<p>This code is working for me </p>\n\n<pre><code>$query = new WP_Query( array(\n 'post_type' => 'my_post_type',\n 'meta_query' => array(\n array(\n 'key' => 'state',\n 'value' => 'Alabama',\n ),\n array(\n 'key' => 'country',\n 'value' => $region,\n 'compare' => $region ? \"=\" : \"!=\",\n ),\n ),\n ));\n</code></pre>\n"
},
{
"answer_id": 298562,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>If I understand your question correctly, you want to query for region field only if <code>$region</code> variable is not empty? If so, this should work and it will be much prettier code than the one you suggested:</p>\n\n<pre><code>$meta_query = array(\n array(\n 'key' => 'state',\n 'value' => 'Alabama',\n ),\n);\n\nif ( $region ) {\n $meta_query[] = array(\n 'key' => 'country',\n 'value' => $region,\n );\n}\n\n$query = new WP_Query( array(\n 'post_type' => 'my_post_type',\n 'meta_query' => $meta_query\n) );\n</code></pre>\n"
}
]
| 2018/03/22 | [
"https://wordpress.stackexchange.com/questions/298551",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121174/"
]
| Is there a wordpress function like -
**If someone recently commented in one of my posts (not other author post), I want his/her ID?**
If there is no function like that, how can I achieve it?
---
Actually, I am building a notification system and it will be something like this
***UserName*** is commented on your **postTitle**. | If I understand your question correctly, you want to query for region field only if `$region` variable is not empty? If so, this should work and it will be much prettier code than the one you suggested:
```
$meta_query = array(
array(
'key' => 'state',
'value' => 'Alabama',
),
);
if ( $region ) {
$meta_query[] = array(
'key' => 'country',
'value' => $region,
);
}
$query = new WP_Query( array(
'post_type' => 'my_post_type',
'meta_query' => $meta_query
) );
``` |
298,588 | <p>I'm using azure as a hosting service and I tried to create a new virtual directory for my subdomain.
So I created a folder in my ftp then I created directory in below image
<a href="https://i.stack.imgur.com/tHAuR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tHAuR.png" alt=""></a></p>
<p>Then I've edited my web.config file But unfortunately I got this error <code>The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.</code> So I deleted the directory and restored web.config to oldest but didn't worked. I've googled and I think the error that I got because of permalinks. But I didn't changed anything. So what is the problem please help web site not working only showing the error </p>
| [
{
"answer_id": 373806,
"author": "Ryan",
"author_id": 144151,
"author_profile": "https://wordpress.stackexchange.com/users/144151",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Caveat</strong><br />\nI know this question is a little out of date and our question/issue is technically regarding an <a href=\"https://azure.microsoft.com/en-us/blog/how-to-host-a-scalable-and-optimized-wordpress-for-azure-in-minutes/\" rel=\"nofollow noreferrer\">Azure Wordpress Resource</a> not a hosted environment... but I thought it might be helpful to answer for future readers.</p>\n<p><strong>Background/Issue</strong><br />\nWe spun up an <em>Azure Worpress resource</em> and migrated our site to it using <a href=\"https://updraftplus.com/\" rel=\"nofollow noreferrer\">updraft</a>. Once transferred and browsing the site we had the same issue:\n<code>The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.</code></p>\n<p><strong>Solution</strong><br />\n<a href=\"https://wordpress.stackexchange.com/users/736/tom-j-nowell\">Tom</a> mentioned above that it's an Azure issue. And looking further in, it's more specifically it ended up being an IIS <code>web.config</code> issue. Here are steps we took to correct it:</p>\n<p><strong>Getting to the web.config file</strong></p>\n<ol>\n<li><p>In the Azure portal go to the wordpress resource and then to <em>Advanced Tools</em>:</p>\n<p><a href=\"https://i.stack.imgur.com/kdKul.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kdKul.png\" alt=\"Azure Portal Wordpress Resource Navigation\" /></a></p>\n</li>\n<li><p>Once we got to the Kudu interface we navigated to the <em>Debug console</em> -> <em>PowerShell</em> (or <em>CMD</em> if you prefer). Then navigated to the root wordpress directory where the <code>web.config</code> lives:</p>\n<p><a href=\"https://i.stack.imgur.com/6Zex3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6Zex3.png\" alt=\"Kudu PowerShell directory view\" /></a></p>\n</li>\n</ol>\n<p><strong>Editing the web.config file</strong></p>\n<ol>\n<li><p>After opening it up the problem was pretty obvious. Somehow Azure spun up the wordpress resource without adding the correct rewrite rules. Or maybe our updraft transfer overwrote it...</p>\n<p><a href=\"https://i.stack.imgur.com/lZyF0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lZyF0.png\" alt=\"The culprit! A blank web.config file\" /></a></p>\n</li>\n<li><p>So we just added the appropriate rewrite rules. (for an <em>azure wordpress resource</em>)</p>\n<p><a href=\"https://i.stack.imgur.com/ZG53E.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZG53E.png\" alt=\"New web.config rewrite rules\" /></a></p>\n<pre><code> <?xml version="1.0" encoding="UTF-8"?>\n <configuration>\n <system.webServer>\n <rewrite>\n <rules>\n <rule name="WordPress: http://your-azure-site.azurewebsites.net" patternSyntax="Wildcard">\n <match url="*"/>\n <conditions>\n <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>\n <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>\n </conditions>\n <action type="Rewrite" url="index.php"/>\n </rule>\n </rules>\n </rewrite>\n </system.webServer>\n </configuration>\n</code></pre>\n</li>\n<li><p>Save it!</p>\n</li>\n</ol>\n<p>Once we saved it the wordpress pretty permalinks worked as expected!</p>\n"
},
{
"answer_id": 396441,
"author": "mehrana",
"author_id": 213198,
"author_profile": "https://wordpress.stackexchange.com/users/213198",
"pm_score": 0,
"selected": false,
"text": "<p>I have solved this problem by replacing the default web site configuration with my own site configuration</p>\n"
}
]
| 2018/03/22 | [
"https://wordpress.stackexchange.com/questions/298588",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134029/"
]
| I'm using azure as a hosting service and I tried to create a new virtual directory for my subdomain.
So I created a folder in my ftp then I created directory in below image
[](https://i.stack.imgur.com/tHAuR.png)
Then I've edited my web.config file But unfortunately I got this error `The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.` So I deleted the directory and restored web.config to oldest but didn't worked. I've googled and I think the error that I got because of permalinks. But I didn't changed anything. So what is the problem please help web site not working only showing the error | **Caveat**
I know this question is a little out of date and our question/issue is technically regarding an [Azure Wordpress Resource](https://azure.microsoft.com/en-us/blog/how-to-host-a-scalable-and-optimized-wordpress-for-azure-in-minutes/) not a hosted environment... but I thought it might be helpful to answer for future readers.
**Background/Issue**
We spun up an *Azure Worpress resource* and migrated our site to it using [updraft](https://updraftplus.com/). Once transferred and browsing the site we had the same issue:
`The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.`
**Solution**
[Tom](https://wordpress.stackexchange.com/users/736/tom-j-nowell) mentioned above that it's an Azure issue. And looking further in, it's more specifically it ended up being an IIS `web.config` issue. Here are steps we took to correct it:
**Getting to the web.config file**
1. In the Azure portal go to the wordpress resource and then to *Advanced Tools*:
[](https://i.stack.imgur.com/kdKul.png)
2. Once we got to the Kudu interface we navigated to the *Debug console* -> *PowerShell* (or *CMD* if you prefer). Then navigated to the root wordpress directory where the `web.config` lives:
[](https://i.stack.imgur.com/6Zex3.png)
**Editing the web.config file**
1. After opening it up the problem was pretty obvious. Somehow Azure spun up the wordpress resource without adding the correct rewrite rules. Or maybe our updraft transfer overwrote it...
[](https://i.stack.imgur.com/lZyF0.png)
2. So we just added the appropriate rewrite rules. (for an *azure wordpress resource*)
[](https://i.stack.imgur.com/ZG53E.png)
```
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="WordPress: http://your-azure-site.azurewebsites.net" patternSyntax="Wildcard">
<match url="*"/>
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
</conditions>
<action type="Rewrite" url="index.php"/>
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
```
3. Save it!
Once we saved it the wordpress pretty permalinks worked as expected! |
298,651 | <p>I'm attempting to make an archive template that will apply only to subcategories of a particular term. My structure looks something like this:</p>
<ul>
<li>Events (main taxonomy)
<ul>
<li>Tradeshow
<ul>
<li>Show subcat 1</li>
<li>Show subcat 2</li>
</ul></li>
<li>Other taxonomies</li>
</ul></li>
</ul>
<p>I want <code>Show subcat 1</code> and <code>Show subcat 2</code> (and any other subcategories) to all get the same archive template. This is one of my attempts at it, which is definitely not working. Here's the code from my <code>functions.php</code>.</p>
<pre><code> add_filter( 'template_include', 'kd_event_subcategory_archive' );
function kd_event_subcategory_archive( $template ) {
$term = get_queried_object()->term_id;
if ( $term->parent == 'tradeshow' ) {
$event_subcat = locate_template( 'taxonomy-tradeshow-subcategory.php' );
return $event_subcat;
}
return $template;
}
</code></pre>
<p>I can't seem to figure out how to properly check if a term is the child of my <code>tradeshow</code> term.</p>
| [
{
"answer_id": 298652,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 4,
"selected": true,
"text": "<p>There are two problems that have thwarted your check:</p>\n\n<pre><code> $term = get_queried_object()->term_id;\n if ( $term->parent == 'tradeshow' ) {\n</code></pre>\n\n<p>Starting with:</p>\n\n<pre><code> $term = get_queried_object()->term_id;\n</code></pre>\n\n<p>Here <code>$term</code> contains the ID of a term, not a term object. Lets assume this is term number 5, the result is:</p>\n\n<pre><code> $term = 5;\n if ( $term->parent == 'tradeshow' ) {\n</code></pre>\n\n<p>Which won't work. <code>$term</code> is a number, not an object, so you cant do <code>->parent</code> on it.</p>\n\n<p>The fix is to just use the queried object directly:</p>\n\n<pre><code> $term = get_queried_object();\n</code></pre>\n\n<p>Which leads us to the next problem:</p>\n\n<pre><code> if ( $term->parent == 'tradeshow' ) {\n</code></pre>\n\n<p>The parent isn't a string, it's a term ID. <code>0</code> if there is no parent, else it's the ID of the parent term, as shown if we look up <code>WP_Term</code>:</p>\n\n<pre><code>/**\n * ID of a term's parent term.\n *\n * @since 4.4.0\n * @var int\n */\npublic $parent = 0;\n</code></pre>\n\n<p>So you need to acquire the tradeshow term in advance to find out its ID. Usually, for these scenarios, developers will not hardcode the slug, but instead provide a setting that lists terms, and store the ID as an option to avoid this kind of lookup, and increase flexibility</p>\n\n<p>But in this case you can use the <code>get_term_by</code> function, e.g.</p>\n\n<pre><code>$tradeshow = get_term_by('slug', 'tradeshow', 'events')\n</code></pre>\n\n<p>Then using:</p>\n\n<pre><code>$tradeshow->term_id === $term->parent\n</code></pre>\n\n<h2>Problems and Advice</h2>\n\n<p>These are additional items I wanted to mention that are unrelated</p>\n\n<h3>Debugging</h3>\n\n<p>Using <code>var_dump</code>, a debugger, or some other tool to see what the contents of <code>$term</code> was would have revealed these problems.</p>\n\n<p>Additionally, PHP error logs will be full of warnings and notices pointing at the if statement for trying to do the equivalent of <code>5->parent</code> which makes no sense to PHP. Pay attention to error logs. I'd recommend using the query monitor plugin as an easy way to catch unexpected warnings</p>\n\n<h3>The Queried object isn't always a term</h3>\n\n<p>This code will run on every page load:</p>\n\n<pre><code>add_filter( 'template_include', 'kd_event_subcategory_archive' );\n\nfunction kd_event_subcategory_archive( $template ) {\n $term = get_queried_object()->term_id;\n if ( $term->parent == 'tradeshow' ) {\n</code></pre>\n\n<p>But what if the user visits a date archive or an author archive? Now the code runs anyway, generating errors. So this filter needs tests to check if the user is on a taxonomy archive, and that the taxonomy matches.</p>\n\n<p>It may even be a singular post, and if the trade show term has a term ID of 5, and you're on the post or page with ID 5, then you'll get a post showing on a taxonomy archive.</p>\n\n<p>I suspect though that it would be easier to use a separate taxonomy.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/get_queried_object</a></p>\n\n<blockquote>\n <ul>\n <li>if you're on a single post, it will return the post object</li>\n <li>if you're on a page, it will return the page object</li>\n <li>if you're on an archive page, it will return the post type object</li>\n <li>if you're on a category archive, it will return the category object</li>\n <li>if you're on an author archive, it will return the author object</li>\n <li>etc.</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 368822,
"author": "Jake",
"author_id": 169069,
"author_profile": "https://wordpress.stackexchange.com/users/169069",
"pm_score": 3,
"selected": false,
"text": "<p>All these answers are so overpowered and extremely long. I've just used this in 2 lines of code:</p>\n\n<pre><code>$term = get_queried_object();\n$is_parent = $term->parent == 0 ? true : false;\n</code></pre>\n\n<p>Essentially, this is just checking if the parent is 0, if it is, then it's the parent. Else, it will be a child.</p>\n\n<p>Super simple.</p>\n"
}
]
| 2018/03/23 | [
"https://wordpress.stackexchange.com/questions/298651",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118681/"
]
| I'm attempting to make an archive template that will apply only to subcategories of a particular term. My structure looks something like this:
* Events (main taxonomy)
+ Tradeshow
- Show subcat 1
- Show subcat 2
+ Other taxonomies
I want `Show subcat 1` and `Show subcat 2` (and any other subcategories) to all get the same archive template. This is one of my attempts at it, which is definitely not working. Here's the code from my `functions.php`.
```
add_filter( 'template_include', 'kd_event_subcategory_archive' );
function kd_event_subcategory_archive( $template ) {
$term = get_queried_object()->term_id;
if ( $term->parent == 'tradeshow' ) {
$event_subcat = locate_template( 'taxonomy-tradeshow-subcategory.php' );
return $event_subcat;
}
return $template;
}
```
I can't seem to figure out how to properly check if a term is the child of my `tradeshow` term. | There are two problems that have thwarted your check:
```
$term = get_queried_object()->term_id;
if ( $term->parent == 'tradeshow' ) {
```
Starting with:
```
$term = get_queried_object()->term_id;
```
Here `$term` contains the ID of a term, not a term object. Lets assume this is term number 5, the result is:
```
$term = 5;
if ( $term->parent == 'tradeshow' ) {
```
Which won't work. `$term` is a number, not an object, so you cant do `->parent` on it.
The fix is to just use the queried object directly:
```
$term = get_queried_object();
```
Which leads us to the next problem:
```
if ( $term->parent == 'tradeshow' ) {
```
The parent isn't a string, it's a term ID. `0` if there is no parent, else it's the ID of the parent term, as shown if we look up `WP_Term`:
```
/**
* ID of a term's parent term.
*
* @since 4.4.0
* @var int
*/
public $parent = 0;
```
So you need to acquire the tradeshow term in advance to find out its ID. Usually, for these scenarios, developers will not hardcode the slug, but instead provide a setting that lists terms, and store the ID as an option to avoid this kind of lookup, and increase flexibility
But in this case you can use the `get_term_by` function, e.g.
```
$tradeshow = get_term_by('slug', 'tradeshow', 'events')
```
Then using:
```
$tradeshow->term_id === $term->parent
```
Problems and Advice
-------------------
These are additional items I wanted to mention that are unrelated
### Debugging
Using `var_dump`, a debugger, or some other tool to see what the contents of `$term` was would have revealed these problems.
Additionally, PHP error logs will be full of warnings and notices pointing at the if statement for trying to do the equivalent of `5->parent` which makes no sense to PHP. Pay attention to error logs. I'd recommend using the query monitor plugin as an easy way to catch unexpected warnings
### The Queried object isn't always a term
This code will run on every page load:
```
add_filter( 'template_include', 'kd_event_subcategory_archive' );
function kd_event_subcategory_archive( $template ) {
$term = get_queried_object()->term_id;
if ( $term->parent == 'tradeshow' ) {
```
But what if the user visits a date archive or an author archive? Now the code runs anyway, generating errors. So this filter needs tests to check if the user is on a taxonomy archive, and that the taxonomy matches.
It may even be a singular post, and if the trade show term has a term ID of 5, and you're on the post or page with ID 5, then you'll get a post showing on a taxonomy archive.
I suspect though that it would be easier to use a separate taxonomy.
<https://codex.wordpress.org/Function_Reference/get_queried_object>
>
> * if you're on a single post, it will return the post object
> * if you're on a page, it will return the page object
> * if you're on an archive page, it will return the post type object
> * if you're on a category archive, it will return the category object
> * if you're on an author archive, it will return the author object
> * etc.
>
>
> |
298,710 | <p>When you enqueue scripts or styles with the following:</p>
<pre><code>function themeslug_enqueue_style() {
wp_enqueue_style( 'core', '/style.css', false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
</code></pre>
<p>You get the following:</p>
<pre><code><link rel='stylesheet' id='core-css' href='http://localhost:8080/wordpress/style.css?ver=4.9.4' type='text/css' media='all' />
</code></pre>
<p>Note that it appends the site url to the beginning, in this case <code>http://localhost:8080</code>. I'm trying to remove this so that it's relative to the file executing this. Usually this is done with <code>plugins_url</code> or <code>get_stylesheet_uri()</code>. However, I DO NOT want to use either of these, as it may be used as a plugin or included in the theme - and I want to keep the code the same for both.</p>
<p>Is there a way to do this?</p>
| [
{
"answer_id": 298696,
"author": "Dragos Micu",
"author_id": 110131,
"author_profile": "https://wordpress.stackexchange.com/users/110131",
"pm_score": 1,
"selected": false,
"text": "<p>There is a custom post type also called clients which is already using that slug. Try using a different slug/page name or work with the default archive page.</p>\n"
},
{
"answer_id": 298700,
"author": "Dilip Gupta",
"author_id": 110899,
"author_profile": "https://wordpress.stackexchange.com/users/110899",
"pm_score": 0,
"selected": false,
"text": "<p>you are using \"Sydney\" theme, please follow it's <a href=\"https://docs.athemes.com/category/8-sydney\" rel=\"nofollow noreferrer\">Sydney - Documentation</a>. They are using <code>client</code> as <code>custom post type</code>. </p>\n\n<p>You need to understand the theme's usage, most of the time, follow the documentation theme provides, it will help you understand how it works. </p>\n"
}
]
| 2018/03/23 | [
"https://wordpress.stackexchange.com/questions/298710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40536/"
]
| When you enqueue scripts or styles with the following:
```
function themeslug_enqueue_style() {
wp_enqueue_style( 'core', '/style.css', false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
```
You get the following:
```
<link rel='stylesheet' id='core-css' href='http://localhost:8080/wordpress/style.css?ver=4.9.4' type='text/css' media='all' />
```
Note that it appends the site url to the beginning, in this case `http://localhost:8080`. I'm trying to remove this so that it's relative to the file executing this. Usually this is done with `plugins_url` or `get_stylesheet_uri()`. However, I DO NOT want to use either of these, as it may be used as a plugin or included in the theme - and I want to keep the code the same for both.
Is there a way to do this? | There is a custom post type also called clients which is already using that slug. Try using a different slug/page name or work with the default archive page. |
298,723 | <p>I have been trying to figure out how i get the ressource on a WC-order, from the product line data, but i seem not to be able to figure this out in WC 3.0+ - pre that it was pretty easy.<br>
I have looked at both the booking meta data, the order meta data, and everything else i can think of, but still unable to find what im looking for.<br>
I have 1 Product with the ID 194 and that product have 2 ressources - and im looking to find the resource in the order line. </p>
<p>Code: </p>
<pre><code>$order = new WC_Order((int)$order_id);
$orderLine = array_values($order->get_items())[0];
</code></pre>
<p>Plugins: </p>
<ul>
<li>Updated WooCommerce</li>
<li>Updated WooCommerce-Booking </li>
</ul>
| [
{
"answer_id": 298828,
"author": "TurtleTread",
"author_id": 117263,
"author_profile": "https://wordpress.stackexchange.com/users/117263",
"pm_score": 1,
"selected": false,
"text": "<p>For existing orders, you need to use the <code>wc_get_order()</code> function.</p>\n"
},
{
"answer_id": 298907,
"author": "Mac",
"author_id": 116092,
"author_profile": "https://wordpress.stackexchange.com/users/116092",
"pm_score": 1,
"selected": true,
"text": "<p>So i found a \"solution\" even though it's not as good as i hoped - or atleast not as good as the way it was done pre 3.0. </p>\n\n<pre><code>$iOrderID = $_POST['iOrderID'];\n$aBookingQuery = new WP_Query( \n array( \n 'post_parent' => (int)$iOrderID,\n 'post_type' => 'wc_booking',\n 'posts_per_page' => 1 \n )\n );\n = $aBookingQuery->posts[0]->ID;\n$iBookingRessoureceID = get_post_meta($iBookingID)['_booking_resource_id'][0];\n</code></pre>\n\n<p>this gives you the ressource ID of said booked product.</p>\n"
}
]
| 2018/03/23 | [
"https://wordpress.stackexchange.com/questions/298723",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116092/"
]
| I have been trying to figure out how i get the ressource on a WC-order, from the product line data, but i seem not to be able to figure this out in WC 3.0+ - pre that it was pretty easy.
I have looked at both the booking meta data, the order meta data, and everything else i can think of, but still unable to find what im looking for.
I have 1 Product with the ID 194 and that product have 2 ressources - and im looking to find the resource in the order line.
Code:
```
$order = new WC_Order((int)$order_id);
$orderLine = array_values($order->get_items())[0];
```
Plugins:
* Updated WooCommerce
* Updated WooCommerce-Booking | So i found a "solution" even though it's not as good as i hoped - or atleast not as good as the way it was done pre 3.0.
```
$iOrderID = $_POST['iOrderID'];
$aBookingQuery = new WP_Query(
array(
'post_parent' => (int)$iOrderID,
'post_type' => 'wc_booking',
'posts_per_page' => 1
)
);
= $aBookingQuery->posts[0]->ID;
$iBookingRessoureceID = get_post_meta($iBookingID)['_booking_resource_id'][0];
```
this gives you the ressource ID of said booked product. |
298,734 | <p>The company I work for has an enterprise Wordpress site that was acquired from a different company. I don't know if there was a past hack or if it's just accumulated spam or what, but the <code>wp_redirection_404</code> table has grown to roughly 7GB. </p>
<p>I tried grepping the table for <em>Viagra</em>, <em>Versace</em>, <em>Nike</em>, etc. and got pages of results for each. It's obviously full of junk.</p>
<p>It doesn't appear to be doing anything. In fact, when downloading it locally to work on, I don't even bring that table, and I don't notice anything at all. Also, I do a procedure where I must download from a production site sync back into a staging site. Just the process of downloading and uploading usually takes 1.5 hours. By contrast - on another huge Wordpress site, syncing the database usually takes about 45 seconds.</p>
<p>Do I need this table for anything? Can I just empty it? Any sort of complicated scripting to filter legit values just seems too time consuming at this point, as even loading the sql to look at it can take a couple of minutes. Basically - is there anything in this table that I can't do without?</p>
<p>I'm not looking for anecdotal answers, but someone who really knows or at least has had experience with this exact situation.</p>
<p>Thanks</p>
| [
{
"answer_id": 298828,
"author": "TurtleTread",
"author_id": 117263,
"author_profile": "https://wordpress.stackexchange.com/users/117263",
"pm_score": 1,
"selected": false,
"text": "<p>For existing orders, you need to use the <code>wc_get_order()</code> function.</p>\n"
},
{
"answer_id": 298907,
"author": "Mac",
"author_id": 116092,
"author_profile": "https://wordpress.stackexchange.com/users/116092",
"pm_score": 1,
"selected": true,
"text": "<p>So i found a \"solution\" even though it's not as good as i hoped - or atleast not as good as the way it was done pre 3.0. </p>\n\n<pre><code>$iOrderID = $_POST['iOrderID'];\n$aBookingQuery = new WP_Query( \n array( \n 'post_parent' => (int)$iOrderID,\n 'post_type' => 'wc_booking',\n 'posts_per_page' => 1 \n )\n );\n = $aBookingQuery->posts[0]->ID;\n$iBookingRessoureceID = get_post_meta($iBookingID)['_booking_resource_id'][0];\n</code></pre>\n\n<p>this gives you the ressource ID of said booked product.</p>\n"
}
]
| 2018/03/23 | [
"https://wordpress.stackexchange.com/questions/298734",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65569/"
]
| The company I work for has an enterprise Wordpress site that was acquired from a different company. I don't know if there was a past hack or if it's just accumulated spam or what, but the `wp_redirection_404` table has grown to roughly 7GB.
I tried grepping the table for *Viagra*, *Versace*, *Nike*, etc. and got pages of results for each. It's obviously full of junk.
It doesn't appear to be doing anything. In fact, when downloading it locally to work on, I don't even bring that table, and I don't notice anything at all. Also, I do a procedure where I must download from a production site sync back into a staging site. Just the process of downloading and uploading usually takes 1.5 hours. By contrast - on another huge Wordpress site, syncing the database usually takes about 45 seconds.
Do I need this table for anything? Can I just empty it? Any sort of complicated scripting to filter legit values just seems too time consuming at this point, as even loading the sql to look at it can take a couple of minutes. Basically - is there anything in this table that I can't do without?
I'm not looking for anecdotal answers, but someone who really knows or at least has had experience with this exact situation.
Thanks | So i found a "solution" even though it's not as good as i hoped - or atleast not as good as the way it was done pre 3.0.
```
$iOrderID = $_POST['iOrderID'];
$aBookingQuery = new WP_Query(
array(
'post_parent' => (int)$iOrderID,
'post_type' => 'wc_booking',
'posts_per_page' => 1
)
);
= $aBookingQuery->posts[0]->ID;
$iBookingRessoureceID = get_post_meta($iBookingID)['_booking_resource_id'][0];
```
this gives you the ressource ID of said booked product. |
298,741 | <p>I'm building a theme, in which, I have 2 menus:</p>
<ol>
<li>Footer menu (<code>footer-menu</code>)</li>
<li>Main menu (<code>main-menu</code>)</li>
</ol>
<p>However, when I called the main one in the <code>header.php</code> file it uses the same links added in the footer navigation.</p>
<p>Please see my code.</p>
<p><strong>Registering the navs</strong></p>
<pre><code>register_nav_menus( array(
'main-menu' => esc_html__( 'Main', 'wd' ),
'footer-menu' => esc_html__( 'Footer', 'wd' ),
) );
</code></pre>
<p><strong>header.php</strong></p>
<pre><code><?php wp_nav_menu('main-menu'); ?>
</code></pre>
<p><strong>footer.php</strong></p>
<pre><code><?php wp_nav_menu('footer-menu'); ?>
</code></pre>
<p><strong>What am I doing wrong? This has never occured before. Ever.</strong></p>
| [
{
"answer_id": 298744,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p><code>wp_nav_menu</code> expects an array of arguments, not a string. If <code>main-menu</code> and <code>footer-menu</code> are theme locations, then you need to specify that in your arguments:</p>\n\n<pre><code>wp_nav_menu( array( 'theme_location' => 'main-menu' ) );\n</code></pre>\n"
},
{
"answer_id": 298746,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Just the fact that they have the same name doesn't mean that WP knows the menu \"main-menu\" goes in the location \"main-menu\". You will have to specify this, as you can see from the source code of <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu</code></a>:</p>\n\n<pre><code>$args = array (\n 'menu' => 'main-menu',\n 'theme_location' => 'main-menu',\n );\nwp_nav_menu ($args);\n</code></pre>\n"
}
]
| 2018/03/23 | [
"https://wordpress.stackexchange.com/questions/298741",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122279/"
]
| I'm building a theme, in which, I have 2 menus:
1. Footer menu (`footer-menu`)
2. Main menu (`main-menu`)
However, when I called the main one in the `header.php` file it uses the same links added in the footer navigation.
Please see my code.
**Registering the navs**
```
register_nav_menus( array(
'main-menu' => esc_html__( 'Main', 'wd' ),
'footer-menu' => esc_html__( 'Footer', 'wd' ),
) );
```
**header.php**
```
<?php wp_nav_menu('main-menu'); ?>
```
**footer.php**
```
<?php wp_nav_menu('footer-menu'); ?>
```
**What am I doing wrong? This has never occured before. Ever.** | Just the fact that they have the same name doesn't mean that WP knows the menu "main-menu" goes in the location "main-menu". You will have to specify this, as you can see from the source code of [`wp_nav_menu`](https://developer.wordpress.org/reference/functions/wp_nav_menu/):
```
$args = array (
'menu' => 'main-menu',
'theme_location' => 'main-menu',
);
wp_nav_menu ($args);
``` |
298,762 | <p>I have a javascript snippet that I want to inject into the footer of the page. It's a tracking code, let's say similar to Google analytics. It has no dependencies, it's a standalone snippet.</p>
<p>I can do something like this</p>
<pre><code>function render_tracking_code(){
wp_enqueue_script( 'depends-js', 'https://rdiv.com/dummy.js', array(), '0.01', true );
wp_add_inline_script( 'depends-js', 'aWholeBunchOfJavascriptCode' );
}
add_action( 'wp_enqueue_scripts', 'render_tracking_code' );
</code></pre>
<p>Seems a little stupid (dummy.js is a blank file), but works. Is there a way to skip the dependency?</p>
| [
{
"answer_id": 298766,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Update:</strong> WordPress added support for adding inline scripts and styles without a dependency in v5.0. See <a href=\"https://wordpress.stackexchange.com/a/311279/2807\">@birgire's answer for</a> implementations. </p>\n\n<p>When using <code>wp_add_inline_script()</code>, <code>WP_Scripts::print_inline_script()</code> will ultimately be used to output inline scripts. By design, <code>print_inline_script()</code> requires a valid dependency, <code>$handle</code>.</p>\n\n<p>Since there is no dependency in this case, <code>wp_add_inline_script()</code> is not the right tool for the job. Instead of creating a fake dependency file (and undesirable additional HTTP request), use <code>wp_head</code> or <code>wp_footer</code> to output the inline script:</p>\n\n<pre><code>add_action( 'wp_head', 'wpse_add_inline_script' );\nfunction wpse_add_inline_script() {\n echo '<script>' . PHP_EOL;\n\n // aWholeBunchOfJavascriptCode\n\n echo '</script>' . PHP_EOL;\n}\n</code></pre>\n\n<p>Generally, JavaScript should be added to a <code>.js</code> file and enqueued using <code>wp_enqueue_script()</code> on the <code>wp_enqueue_scripts</code> hook. Data can be made available to the script using <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"noreferrer\"><code>wp_localize_script()</code></a>. Sometimes it may still be necessary to add a script inline though.</p>\n"
},
{
"answer_id": 300656,
"author": "Morgan Estes",
"author_id": 26317,
"author_profile": "https://wordpress.stackexchange.com/users/26317",
"pm_score": 2,
"selected": false,
"text": "<p>One way to do this is to create a function that echoes your script inside a <code><script></code> tag, and hook it to the <a href=\"https://developer.wordpress.org/reference/hooks/wp_print_footer_scripts/\" rel=\"nofollow noreferrer\"><code>wp_print_footer_scripts</code></a> action. You should take care to escape anything that you don't strictly control, but this a generally safe and easy method otherwise.</p>\n\n<p>For example:</p>\n\n<pre><code>add_action( 'wp_print_footer_scripts', function () { \n ?>\n <script>\n (function myFunction() { \n /* your code here */\n })();\n </script>\n<?php \n} );\n</code></pre>\n"
},
{
"answer_id": 311279,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": false,
"text": "<h2><code>wp_add_inline_style()</code> - without dependency</h2>\n\n<p>The <code>wp_add_inline_style()</code> can be used without a source file dependency. </p>\n\n<p>Here's an <a href=\"https://wordpress.stackexchange.com/a/282868/26350\">example</a> from @Flix:</p>\n\n<pre><code>wp_register_style( 'dummy-handle', false );\nwp_enqueue_style( 'dummy-handle' );\nwp_add_inline_style( 'dummy-handle', '* { color: red; }' );\n</code></pre>\n\n<p>where we would hook this into the <code>wp_enqueue_scripts</code> action.</p>\n\n<h2><code>wp_add_inline_script()</code> - without dependency</h2>\n\n<p>According to ticket <a href=\"https://core.trac.wordpress.org/ticket/44551\" rel=\"noreferrer\">#43565</a>, similar will be supported for <code>wp_add_inline_script()</code> in version <strike><code>4.9.9</code></strike> <code>5.0</code> (thanks to @MarcioDuarte, @dev101 and @DaveRomsey for the verification in comments):</p>\n\n<pre><code>wp_register_script( 'dummy-handle-header', '' );\nwp_enqueue_script( 'dummy-handle-header' );\nwp_add_inline_script( 'dummy-handle-header', 'console.log( \"header\" );' );\n</code></pre>\n\n<p>that will display the following in the <em>header</em>, i.e.between the <code><head>...</head></code> tags:</p>\n\n<pre><code><script type='text/javascript'>\nconsole.log( \"header\" );\n</script>\n</code></pre>\n\n<p>To display it in the <em>footer</em>:</p>\n\n<pre><code>wp_register_script( 'dummy-handle-footer', '', [], '', true );\nwp_enqueue_script( 'dummy-handle-footer' );\nwp_add_inline_script( 'dummy-handle-footer', 'console.log( \"footer\" );' );\n</code></pre>\n\n<p>The default of <code>$position</code> input argument in <code>wp_add_inline_script()</code> is <code>'after'</code>. The <code>'before'</code> value prints it above <code>'after'</code>.</p>\n"
}
]
| 2018/03/23 | [
"https://wordpress.stackexchange.com/questions/298762",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45255/"
]
| I have a javascript snippet that I want to inject into the footer of the page. It's a tracking code, let's say similar to Google analytics. It has no dependencies, it's a standalone snippet.
I can do something like this
```
function render_tracking_code(){
wp_enqueue_script( 'depends-js', 'https://rdiv.com/dummy.js', array(), '0.01', true );
wp_add_inline_script( 'depends-js', 'aWholeBunchOfJavascriptCode' );
}
add_action( 'wp_enqueue_scripts', 'render_tracking_code' );
```
Seems a little stupid (dummy.js is a blank file), but works. Is there a way to skip the dependency? | `wp_add_inline_style()` - without dependency
--------------------------------------------
The `wp_add_inline_style()` can be used without a source file dependency.
Here's an [example](https://wordpress.stackexchange.com/a/282868/26350) from @Flix:
```
wp_register_style( 'dummy-handle', false );
wp_enqueue_style( 'dummy-handle' );
wp_add_inline_style( 'dummy-handle', '* { color: red; }' );
```
where we would hook this into the `wp_enqueue_scripts` action.
`wp_add_inline_script()` - without dependency
---------------------------------------------
According to ticket [#43565](https://core.trac.wordpress.org/ticket/44551), similar will be supported for `wp_add_inline_script()` in version `4.9.9` `5.0` (thanks to @MarcioDuarte, @dev101 and @DaveRomsey for the verification in comments):
```
wp_register_script( 'dummy-handle-header', '' );
wp_enqueue_script( 'dummy-handle-header' );
wp_add_inline_script( 'dummy-handle-header', 'console.log( "header" );' );
```
that will display the following in the *header*, i.e.between the `<head>...</head>` tags:
```
<script type='text/javascript'>
console.log( "header" );
</script>
```
To display it in the *footer*:
```
wp_register_script( 'dummy-handle-footer', '', [], '', true );
wp_enqueue_script( 'dummy-handle-footer' );
wp_add_inline_script( 'dummy-handle-footer', 'console.log( "footer" );' );
```
The default of `$position` input argument in `wp_add_inline_script()` is `'after'`. The `'before'` value prints it above `'after'`. |
298,767 | <p>I have a custom WP_Query inside of an archive. I know this is not ideal, but when I try switching it out for a pre_get_posts option, then my page just enters an infinite loop, so I'd rather stick with the WP Query. The problem is that pagination sends me to a 404 error on /page/2.</p>
<p>My query (it also has some taxonomy and meta queries added later)</p>
<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query_args = array(
'post_type' => 'product',
'posts_per_page' => 2,
'paged' => $paged,
);
</code></pre>
<p>Here is my pagination function</p>
<pre><code>function pagination($query){ ?>
<ul class="pagination">
<?php
$pages = paginate_links( array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'type' => 'array',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => '<span class ="fa fa-caret-left" aria-hidden="true"></span><span class="prev-text">Prev</span>',
'next_text' => '<span class="next-text">Next</span> <span class ="fa fa-caret-right" aria-hidden="true"></span>',
'add_args' => false,
'add_fragment' => '',
) );
if (is_array($pages)):
foreach ($pages as $p): ?>
<li class="pagination-item js-ajax-link-wrap">
<?php echo $p; ?>
</li>
<?php endforeach;
endif; ?>
</ul>
<?php
}
</code></pre>
<p>The pagination displays properly...the problem is when I go to "/page/2" it throws a 404 error.</p>
| [
{
"answer_id": 298775,
"author": "Jordan Carter",
"author_id": 94213,
"author_profile": "https://wordpress.stackexchange.com/users/94213",
"pm_score": 4,
"selected": true,
"text": "<p>Found the answer!!!</p>\n\n<p>Put this in functions.php (or a required file). Of course, change it to suit your needs. I needed something that only worked for product category archives.</p>\n\n<pre><code>function modify_product_cat_query( $query ) {\n if (!is_admin() && $query->is_tax(\"product_cat\")){\n $query->set('posts_per_page', 2);\n }\n}\nadd_action( 'pre_get_posts', 'modify_product_cat_query' );\n</code></pre>\n\n<p>I also took out the posts_per_page parameter from my WP_Query.</p>\n"
},
{
"answer_id": 324770,
"author": "Amin",
"author_id": 155255,
"author_profile": "https://wordpress.stackexchange.com/users/155255",
"pm_score": 0,
"selected": false,
"text": "<p>Also after I've disabled plugin of <strong><a href=\"https://wordpress.org/plugins/orbisius-simple-shortlink/\" rel=\"nofollow noreferrer\">orbisius simple shortlink</a></strong> problem solved!\nit override <em>site.com/page/123</em> links to be redirected to page ID.</p>\n"
}
]
| 2018/03/23 | [
"https://wordpress.stackexchange.com/questions/298767",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94213/"
]
| I have a custom WP\_Query inside of an archive. I know this is not ideal, but when I try switching it out for a pre\_get\_posts option, then my page just enters an infinite loop, so I'd rather stick with the WP Query. The problem is that pagination sends me to a 404 error on /page/2.
My query (it also has some taxonomy and meta queries added later)
```
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query_args = array(
'post_type' => 'product',
'posts_per_page' => 2,
'paged' => $paged,
);
```
Here is my pagination function
```
function pagination($query){ ?>
<ul class="pagination">
<?php
$pages = paginate_links( array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'type' => 'array',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => '<span class ="fa fa-caret-left" aria-hidden="true"></span><span class="prev-text">Prev</span>',
'next_text' => '<span class="next-text">Next</span> <span class ="fa fa-caret-right" aria-hidden="true"></span>',
'add_args' => false,
'add_fragment' => '',
) );
if (is_array($pages)):
foreach ($pages as $p): ?>
<li class="pagination-item js-ajax-link-wrap">
<?php echo $p; ?>
</li>
<?php endforeach;
endif; ?>
</ul>
<?php
}
```
The pagination displays properly...the problem is when I go to "/page/2" it throws a 404 error. | Found the answer!!!
Put this in functions.php (or a required file). Of course, change it to suit your needs. I needed something that only worked for product category archives.
```
function modify_product_cat_query( $query ) {
if (!is_admin() && $query->is_tax("product_cat")){
$query->set('posts_per_page', 2);
}
}
add_action( 'pre_get_posts', 'modify_product_cat_query' );
```
I also took out the posts\_per\_page parameter from my WP\_Query. |
298,819 | <p>For example, to redirect old URLs of the form:</p>
<p><code>/2016/10/mukunda-murari-kannada-songs-download.html</code></p>
<p>To</p>
<p><code>/mukunda-murari-kannada-songs-download.html</code></p>
<p>I have already changed the permalink structure in WordPress, but wish to redirect the old URLs to the new, in the most efficient way, in order to help preserve SEO.</p>
<p>This is my code:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ $1.html [L,R=301]
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
| [
{
"answer_id": 298820,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Why not change your permalinks to \"Post Name\" in Settings, Permalinks?</p>\n"
},
{
"answer_id": 298822,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": true,
"text": "<p>Assuming you have already changed the permalinks structure as @RickHellewell suggests, then you can do something like the following near the top of your <code>.htaccess</code> file (before the existing WP front-controller) to redirect the old URLs (with the stated format) in order to preserve SEO.</p>\n\n<pre><code>RewriteRule ^\\d{4}/\\d\\d/([a-z-]+\\.html)$ /$1 [R=301,L]\n</code></pre>\n\n\n"
}
]
| 2018/03/24 | [
"https://wordpress.stackexchange.com/questions/298819",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140381/"
]
| For example, to redirect old URLs of the form:
`/2016/10/mukunda-murari-kannada-songs-download.html`
To
`/mukunda-murari-kannada-songs-download.html`
I have already changed the permalink structure in WordPress, but wish to redirect the old URLs to the new, in the most efficient way, in order to help preserve SEO.
This is my code:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ $1.html [L,R=301]
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
``` | Assuming you have already changed the permalinks structure as @RickHellewell suggests, then you can do something like the following near the top of your `.htaccess` file (before the existing WP front-controller) to redirect the old URLs (with the stated format) in order to preserve SEO.
```
RewriteRule ^\d{4}/\d\d/([a-z-]+\.html)$ /$1 [R=301,L]
``` |
298,903 | <p>I'm creating a webshop, that imports a lot of products from a csv file. I need to link to available accessories etc., which individually is determined and imported by the respectable products SKU. </p>
<p>I know it is possible to get the product ID with a simple products SKU with this:</p>
<pre><code>wc_get_product_id_by_sku('PRODUCT_SKU');
</code></pre>
<p>Is there anyway to do the same, but with a variation sku?</p>
| [
{
"answer_id": 305918,
"author": "Tim",
"author_id": 118534,
"author_profile": "https://wordpress.stackexchange.com/users/118534",
"pm_score": 3,
"selected": false,
"text": "<p>I was stuck on a very similar problem. I couldn't find anything in the woocommerce code that would let you directly look up the parent product from the variation sku. \nBut, as product variations are stored in the <code>wp_posts</code> table with the type <code>product_variation</code>, and the SKUs are stored in the <code>wp_post_meta</code> table, it's easy to look up the product variation using a meta query with the <code>get_posts()</code> wordpress function. </p>\n\n<pre><code>$args = array(\n 'post_type' => 'product_variation',\n 'meta_query' => array(\n array(\n 'key' => '_sku',\n 'value' => 'PRODUCT_SKU',\n )\n )\n);\n$posts = get_posts( $args);\n</code></pre>\n\n<p>This should return your matching <code>product_variation</code> custom post type. </p>\n\n<p>Once you have this then you can look up the parent product using the column <code>post_parent</code> that WooCommerce uses to link a variation to the parent variable product. </p>\n\n<p>Turning that into a function is pretty straight forward:</p>\n\n<pre><code>function wc_get_product_id_by_variation_sku($sku) {\n $args = array(\n 'post_type' => 'product_variation',\n 'meta_query' => array(\n array(\n 'key' => '_sku',\n 'value' => $sku,\n )\n )\n );\n // Get the posts for the sku\n $posts = get_posts( $args);\n if ($posts) {\n return $posts[0]->post_parent;\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>I use this in my site and it works great. Hope that helps.</p>\n"
},
{
"answer_id": 366853,
"author": "abhiGT",
"author_id": 166992,
"author_profile": "https://wordpress.stackexchange.com/users/166992",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest way is to get Variation ID using <code>wc_get_product_id_by_sku</code> function then get post parent ID to get Product ID.</p>\n\n<pre><code>$variation_id = wc_get_product_id_by_sku('VARIATION_SKU');\n$product_id = wp_get_post_parent_id($variation_id);\n</code></pre>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298903",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140470/"
]
| I'm creating a webshop, that imports a lot of products from a csv file. I need to link to available accessories etc., which individually is determined and imported by the respectable products SKU.
I know it is possible to get the product ID with a simple products SKU with this:
```
wc_get_product_id_by_sku('PRODUCT_SKU');
```
Is there anyway to do the same, but with a variation sku? | I was stuck on a very similar problem. I couldn't find anything in the woocommerce code that would let you directly look up the parent product from the variation sku.
But, as product variations are stored in the `wp_posts` table with the type `product_variation`, and the SKUs are stored in the `wp_post_meta` table, it's easy to look up the product variation using a meta query with the `get_posts()` wordpress function.
```
$args = array(
'post_type' => 'product_variation',
'meta_query' => array(
array(
'key' => '_sku',
'value' => 'PRODUCT_SKU',
)
)
);
$posts = get_posts( $args);
```
This should return your matching `product_variation` custom post type.
Once you have this then you can look up the parent product using the column `post_parent` that WooCommerce uses to link a variation to the parent variable product.
Turning that into a function is pretty straight forward:
```
function wc_get_product_id_by_variation_sku($sku) {
$args = array(
'post_type' => 'product_variation',
'meta_query' => array(
array(
'key' => '_sku',
'value' => $sku,
)
)
);
// Get the posts for the sku
$posts = get_posts( $args);
if ($posts) {
return $posts[0]->post_parent;
} else {
return false;
}
}
```
I use this in my site and it works great. Hope that helps. |
298,916 | <p>I'm having some difficulty comparing between a negative and positive number. This code works fine when it's between two positive numbers but not when it's between a negative then a positive one.</p>
<p>This is part of my 'meta_query':</p>
<pre><code>array_push($metaQuery,
array('relation' => 'AND',
array(
'key' => 'longitude',
'value' => array($minlng, $maxlng),
'compare' => 'BETWEEN',
),
)
);
</code></pre>
<p>If for instance the $minlng is -1.5 and the $maxlng is 1.5. It will pass through values that equal -3.</p>
<p>Here is a var_dump of the meta_query if that is a help:</p>
<pre><code>array(1) {
[0]=>
array(2) {
["relation"]=>
string(3) "AND"
[0]=>
array(3) {
["key"]=>
string(9) "longitude"
["value"]=>
array(2) {
[0]=>
float(-0.989505008087)
[1]=>
float(1.31257480809)
}
["compare"]=>
string(7) "BETWEEN"
}
}
}
</code></pre>
| [
{
"answer_id": 298940,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 2,
"selected": false,
"text": "<p>I tried the following code: </p>\n\n<pre><code>$posts = get_posts([\n \"post_type\" => \"CUSTOM_POST_TYPE\",\n \"meta_query\" => [\n 'relation' => 'AND',\n [\n 'key' => 'longitude',\n 'value' => [-0.9895, 1.3125],\n 'compare' => 'BETWEEN',\n \"type\" => \"NUMERIC\",\n ],\n ],\n]);\n</code></pre>\n\n<p>When I remove <code>\"type\" => \"NUMERIC\"</code>, I could reproduced your problem because the comparison is string based.</p>\n\n<p>But when adding the type <code>NUMERIC</code>, the MySQL request contains <code>CAST(wp_postmeta.meta_value AS SIGNED) BETWEEN '-0.9895' AND '1.3125'</code> and the query returns the foreseen values.</p>\n"
},
{
"answer_id": 337352,
"author": "tinhbeng",
"author_id": 167589,
"author_profile": "https://wordpress.stackexchange.com/users/167589",
"pm_score": 2,
"selected": false,
"text": "<p>If you only use <code>\"type\" => \"NUMBER\"</code>, it will work but is ineffective, because it only takes the integer part to compare.\nYou can replace it with this code <code>\"type\" => \"DECIMAL(5,2)\"// 5:integer part length, 2:Decimal part length</code>.\nI used it and it works with me.</p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298916",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66977/"
]
| I'm having some difficulty comparing between a negative and positive number. This code works fine when it's between two positive numbers but not when it's between a negative then a positive one.
This is part of my 'meta\_query':
```
array_push($metaQuery,
array('relation' => 'AND',
array(
'key' => 'longitude',
'value' => array($minlng, $maxlng),
'compare' => 'BETWEEN',
),
)
);
```
If for instance the $minlng is -1.5 and the $maxlng is 1.5. It will pass through values that equal -3.
Here is a var\_dump of the meta\_query if that is a help:
```
array(1) {
[0]=>
array(2) {
["relation"]=>
string(3) "AND"
[0]=>
array(3) {
["key"]=>
string(9) "longitude"
["value"]=>
array(2) {
[0]=>
float(-0.989505008087)
[1]=>
float(1.31257480809)
}
["compare"]=>
string(7) "BETWEEN"
}
}
}
``` | I tried the following code:
```
$posts = get_posts([
"post_type" => "CUSTOM_POST_TYPE",
"meta_query" => [
'relation' => 'AND',
[
'key' => 'longitude',
'value' => [-0.9895, 1.3125],
'compare' => 'BETWEEN',
"type" => "NUMERIC",
],
],
]);
```
When I remove `"type" => "NUMERIC"`, I could reproduced your problem because the comparison is string based.
But when adding the type `NUMERIC`, the MySQL request contains `CAST(wp_postmeta.meta_value AS SIGNED) BETWEEN '-0.9895' AND '1.3125'` and the query returns the foreseen values. |
298,920 | <p><a href="https://i.stack.imgur.com/nSb4b.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/nSb4b.jpg" alt="Not Available"></a></p>
<p>I am trying to go to wp-admin, but after I login I keep seeing this. I already tried renaming plugin but still I can't login to wp-admin.</p>
| [
{
"answer_id": 298930,
"author": "Amol Sawant",
"author_id": 138676,
"author_profile": "https://wordpress.stackexchange.com/users/138676",
"pm_score": -1,
"selected": false,
"text": "<p>Do the following steps one by one and so you can check what causing you this error ...</p>\n\n<p>1) Rename .htaccess file </p>\n\n<p>2) rename theme folder </p>\n\n<p>3) rename pluginn folder </p>\n\n<p>Please upvote my answer ....</p>\n"
},
{
"answer_id": 299044,
"author": "Dvaeer",
"author_id": 92868,
"author_profile": "https://wordpress.stackexchange.com/users/92868",
"pm_score": 2,
"selected": false,
"text": "<p>There are different reasons why this can happen. In your case I think it may be a security plugin that has changed the deafult login URL to something else. </p>\n\n<p>When I go to <a href=\"http://www.philenglish.com.cn/wp-login.php\" rel=\"nofollow noreferrer\">http://www.philenglish.com.cn/wp-login.php</a> I get a 404 error, which is something such plugins also do: they make the default login URLs unavailable in an attempt to make your site more secure. </p>\n\n<p>If you don't know what the login URL is changed to, I would first disable any security plugins installed on the site. You mention you've already tried disabling plugins, but looking at your site's source code, I can see there are still plugins active. So I would double-check you've really disabled your plugins. </p>\n\n<p>An easy way would be to connect to your site through FTP and navigate to your plugins folder. Normally you would find this here: </p>\n\n<pre><code>wp-content > plugins\n</code></pre>\n\n<p>Your can either look in your plugins folder and find the plugin that might cause this issue. And then disable it by temporarily renaming the folder. </p>\n\n<p>Or you can disable all plugins at once by temporarily renaming the whole plugins folder.</p>\n\n<p>As an aside: this is the quickest way to disable plugins, but you may lose some settings when you reactivate your plugins. You can also <a href=\"https://perishablepress.com/quickly-disable-or-enable-all-wordpress-plugins-via-the-database/\" rel=\"nofollow noreferrer\">quickly disable all plugins through phpmyadmin while retaining options</a>. </p>\n\n<p>I hope this helps you. Good luck!</p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298920",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140483/"
]
| [](https://i.stack.imgur.com/nSb4b.jpg)
I am trying to go to wp-admin, but after I login I keep seeing this. I already tried renaming plugin but still I can't login to wp-admin. | There are different reasons why this can happen. In your case I think it may be a security plugin that has changed the deafult login URL to something else.
When I go to <http://www.philenglish.com.cn/wp-login.php> I get a 404 error, which is something such plugins also do: they make the default login URLs unavailable in an attempt to make your site more secure.
If you don't know what the login URL is changed to, I would first disable any security plugins installed on the site. You mention you've already tried disabling plugins, but looking at your site's source code, I can see there are still plugins active. So I would double-check you've really disabled your plugins.
An easy way would be to connect to your site through FTP and navigate to your plugins folder. Normally you would find this here:
```
wp-content > plugins
```
Your can either look in your plugins folder and find the plugin that might cause this issue. And then disable it by temporarily renaming the folder.
Or you can disable all plugins at once by temporarily renaming the whole plugins folder.
As an aside: this is the quickest way to disable plugins, but you may lose some settings when you reactivate your plugins. You can also [quickly disable all plugins through phpmyadmin while retaining options](https://perishablepress.com/quickly-disable-or-enable-all-wordpress-plugins-via-the-database/).
I hope this helps you. Good luck! |
298,928 | <p>We've got some custom endpoints set up that do various things, which we access via <code>/wp/wp-admin/admin-ajax.php?action=some_action</code></p>
<p>However whenever there is an error as we're developing, such as syntax, logical, fatal etc, we simply get "500 Internal Server Error"</p>
<p>Every other page on the site when there's an error, it gives us the PHP error.</p>
<p>We have to then open our PHP Log file to see the error.</p>
<p>Is there something in wordpress that disables displaying of errors on these URLs? and if so, how can we prevent this to allow rendering of the errors on the browser?</p>
| [
{
"answer_id": 298931,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": -1,
"selected": false,
"text": "<p>You can try the WP_Ajax_Response </p>\n\n<pre><code>$response = array(\n 'what'=>'stuff',\n 'action'=>'delete_something',\n 'id'=>new WP_Error('oops','I had an accident.'),\n 'data'=>'Whoops, there was a problem!'\n);\n$xmlResponse = new WP_Ajax_Response($response);\n$xmlResponse->send();\n</code></pre>\n\n<p>Read more <a href=\"https://codex.wordpress.org/Function_Reference/WP_Ajax_Response\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/WP_Ajax_Response</a></p>\n"
},
{
"answer_id": 299011,
"author": "Friss",
"author_id": 62392,
"author_profile": "https://wordpress.stackexchange.com/users/62392",
"pm_score": 2,
"selected": false,
"text": "<p>You can try to add these two lines at the very top of tour script file</p>\n\n<pre><code>error_reporting(E_ALL); \nini_set(\"display_errors\", 1);\n</code></pre>\n\n<p>It tells php to report all kind of errors and overrides its default settings to display them.</p>\n"
},
{
"answer_id": 307689,
"author": "Rahil Wazir",
"author_id": 36349,
"author_profile": "https://wordpress.stackexchange.com/users/36349",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress by default hide errors for ajax request call. This can be confirmed from the source file <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-includes/load.php#L353\" rel=\"nofollow noreferrer\"><code>wp-includes/load.php#L352</code></a>, here:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) || wp_doing_ajax() ) {\n @ini_set( 'display_errors', 0 );\n}\n</code></pre>\n\n<p>See the function <code>wp_doing_ajax()</code> is being used in the conditional statement thus the <code>display_errors</code> is being set.</p>\n\n<p>To workaround this, you need to turn on error reporting manually at top of your ajax function call as suggested by <a href=\"https://wordpress.stackexchange.com/a/299011/36349\">@Friss</a>.</p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298928",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116411/"
]
| We've got some custom endpoints set up that do various things, which we access via `/wp/wp-admin/admin-ajax.php?action=some_action`
However whenever there is an error as we're developing, such as syntax, logical, fatal etc, we simply get "500 Internal Server Error"
Every other page on the site when there's an error, it gives us the PHP error.
We have to then open our PHP Log file to see the error.
Is there something in wordpress that disables displaying of errors on these URLs? and if so, how can we prevent this to allow rendering of the errors on the browser? | WordPress by default hide errors for ajax request call. This can be confirmed from the source file [`wp-includes/load.php#L352`](https://core.trac.wordpress.org/browser/trunk/src/wp-includes/load.php#L353), here:
```php
if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) || wp_doing_ajax() ) {
@ini_set( 'display_errors', 0 );
}
```
See the function `wp_doing_ajax()` is being used in the conditional statement thus the `display_errors` is being set.
To workaround this, you need to turn on error reporting manually at top of your ajax function call as suggested by [@Friss](https://wordpress.stackexchange.com/a/299011/36349). |
298,937 | <p>I am trying to learn how to make themes for WordPress now I am unable to find how to make a <a href="https://i.stack.imgur.com/U6V7y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U6V7y.png" alt="enter image description here"></a>custom menu in admin panel related to theme option </p>
<p>want to show a menu in this admin panel </p>
| [
{
"answer_id": 298931,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": -1,
"selected": false,
"text": "<p>You can try the WP_Ajax_Response </p>\n\n<pre><code>$response = array(\n 'what'=>'stuff',\n 'action'=>'delete_something',\n 'id'=>new WP_Error('oops','I had an accident.'),\n 'data'=>'Whoops, there was a problem!'\n);\n$xmlResponse = new WP_Ajax_Response($response);\n$xmlResponse->send();\n</code></pre>\n\n<p>Read more <a href=\"https://codex.wordpress.org/Function_Reference/WP_Ajax_Response\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/WP_Ajax_Response</a></p>\n"
},
{
"answer_id": 299011,
"author": "Friss",
"author_id": 62392,
"author_profile": "https://wordpress.stackexchange.com/users/62392",
"pm_score": 2,
"selected": false,
"text": "<p>You can try to add these two lines at the very top of tour script file</p>\n\n<pre><code>error_reporting(E_ALL); \nini_set(\"display_errors\", 1);\n</code></pre>\n\n<p>It tells php to report all kind of errors and overrides its default settings to display them.</p>\n"
},
{
"answer_id": 307689,
"author": "Rahil Wazir",
"author_id": 36349,
"author_profile": "https://wordpress.stackexchange.com/users/36349",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress by default hide errors for ajax request call. This can be confirmed from the source file <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-includes/load.php#L353\" rel=\"nofollow noreferrer\"><code>wp-includes/load.php#L352</code></a>, here:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) || wp_doing_ajax() ) {\n @ini_set( 'display_errors', 0 );\n}\n</code></pre>\n\n<p>See the function <code>wp_doing_ajax()</code> is being used in the conditional statement thus the <code>display_errors</code> is being set.</p>\n\n<p>To workaround this, you need to turn on error reporting manually at top of your ajax function call as suggested by <a href=\"https://wordpress.stackexchange.com/a/299011/36349\">@Friss</a>.</p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298937",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140035/"
]
| I am trying to learn how to make themes for WordPress now I am unable to find how to make a [](https://i.stack.imgur.com/U6V7y.png)custom menu in admin panel related to theme option
want to show a menu in this admin panel | WordPress by default hide errors for ajax request call. This can be confirmed from the source file [`wp-includes/load.php#L352`](https://core.trac.wordpress.org/browser/trunk/src/wp-includes/load.php#L353), here:
```php
if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) || wp_doing_ajax() ) {
@ini_set( 'display_errors', 0 );
}
```
See the function `wp_doing_ajax()` is being used in the conditional statement thus the `display_errors` is being set.
To workaround this, you need to turn on error reporting manually at top of your ajax function call as suggested by [@Friss](https://wordpress.stackexchange.com/a/299011/36349). |
298,961 | <p>I am creating a field that needs to add a custom field to every post on a site. I am using the ACF plugin in my plugin to do so. I have followed <a href="https://www.smashingmagazine.com/2016/04/three-approaches-to-adding-configurable-fields-to-your-plugin/#approach-3-integrating-acf-advanced-custom-fields-into-your-plugin" rel="nofollow noreferrer">this tutorial</a> and am close. In the tutorial they add the custom fields to a settings back, but I want to add the custom field to every post. Here is the ACF-related code that I have:</p>
<pre><code><?php
// 1. customize ACF path
add_filter('acf/settings/path', 'my_acf_settings_path');
function my_acf_settings_path( $path ) {
// update path
$path = get_stylesheet_directory() . '/vendor/advanced-custom-fields/';
// return
return $path;
}
// 2. customize ACF dir
add_filter('acf/settings/dir', 'my_acf_settings_dir');
function my_acf_settings_dir( $dir ) {
// update path
$dir = get_stylesheet_directory_uri() . '/vendor/advanced-custom-fields/';
// return
return $dir;
}
// 3. Hide ACF field group menu item
add_filter('acf/settings/show_admin', '__return_false');
// 4. Include ACF
include_once( get_stylesheet_directory() . '/vendor/advanced-custom-fields/acf.php' );
// 5. Setup Custom Fields on post pages
$this->setup_options();
public function setup_options() {
if(function_exists("register_field_group")) {
register_field_group(array (
'id' => 'acf_field-id',
'title' => 'Field Name',
'fields' => array (
array (
'key' => 'field_5ab8f6946d890',
'label' => 'Label',
'name' => 'name',
'type' => 'wysiwyg',
'instructions' => '',
'default_value' => '',
'toolbar' => 'full',
'media_upload' => 'yes',
),
),
'location' => array (
array (
array (
'param' => 'post_type',
'operator' => '==',
'value' => 'post',
'order_no' => 0,
'group_no' => 0,
),
),
),
'options' => array (
'position' => 'normal',
'layout' => 'no_box',
'hide_on_screen' => array (
),
),
'menu_order' => 0,
));
}
}
</code></pre>
<p>I know my issue is in #5 above. I am not clear how to run the function to load that field for every post. Any insight? </p>
<p>Also, how would I then automatically output this field code in the single.php template before the post content. Can I use a WordPress function to do that as well?</p>
| [
{
"answer_id": 298931,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": -1,
"selected": false,
"text": "<p>You can try the WP_Ajax_Response </p>\n\n<pre><code>$response = array(\n 'what'=>'stuff',\n 'action'=>'delete_something',\n 'id'=>new WP_Error('oops','I had an accident.'),\n 'data'=>'Whoops, there was a problem!'\n);\n$xmlResponse = new WP_Ajax_Response($response);\n$xmlResponse->send();\n</code></pre>\n\n<p>Read more <a href=\"https://codex.wordpress.org/Function_Reference/WP_Ajax_Response\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/WP_Ajax_Response</a></p>\n"
},
{
"answer_id": 299011,
"author": "Friss",
"author_id": 62392,
"author_profile": "https://wordpress.stackexchange.com/users/62392",
"pm_score": 2,
"selected": false,
"text": "<p>You can try to add these two lines at the very top of tour script file</p>\n\n<pre><code>error_reporting(E_ALL); \nini_set(\"display_errors\", 1);\n</code></pre>\n\n<p>It tells php to report all kind of errors and overrides its default settings to display them.</p>\n"
},
{
"answer_id": 307689,
"author": "Rahil Wazir",
"author_id": 36349,
"author_profile": "https://wordpress.stackexchange.com/users/36349",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress by default hide errors for ajax request call. This can be confirmed from the source file <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-includes/load.php#L353\" rel=\"nofollow noreferrer\"><code>wp-includes/load.php#L352</code></a>, here:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) || wp_doing_ajax() ) {\n @ini_set( 'display_errors', 0 );\n}\n</code></pre>\n\n<p>See the function <code>wp_doing_ajax()</code> is being used in the conditional statement thus the <code>display_errors</code> is being set.</p>\n\n<p>To workaround this, you need to turn on error reporting manually at top of your ajax function call as suggested by <a href=\"https://wordpress.stackexchange.com/a/299011/36349\">@Friss</a>.</p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298961",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31284/"
]
| I am creating a field that needs to add a custom field to every post on a site. I am using the ACF plugin in my plugin to do so. I have followed [this tutorial](https://www.smashingmagazine.com/2016/04/three-approaches-to-adding-configurable-fields-to-your-plugin/#approach-3-integrating-acf-advanced-custom-fields-into-your-plugin) and am close. In the tutorial they add the custom fields to a settings back, but I want to add the custom field to every post. Here is the ACF-related code that I have:
```
<?php
// 1. customize ACF path
add_filter('acf/settings/path', 'my_acf_settings_path');
function my_acf_settings_path( $path ) {
// update path
$path = get_stylesheet_directory() . '/vendor/advanced-custom-fields/';
// return
return $path;
}
// 2. customize ACF dir
add_filter('acf/settings/dir', 'my_acf_settings_dir');
function my_acf_settings_dir( $dir ) {
// update path
$dir = get_stylesheet_directory_uri() . '/vendor/advanced-custom-fields/';
// return
return $dir;
}
// 3. Hide ACF field group menu item
add_filter('acf/settings/show_admin', '__return_false');
// 4. Include ACF
include_once( get_stylesheet_directory() . '/vendor/advanced-custom-fields/acf.php' );
// 5. Setup Custom Fields on post pages
$this->setup_options();
public function setup_options() {
if(function_exists("register_field_group")) {
register_field_group(array (
'id' => 'acf_field-id',
'title' => 'Field Name',
'fields' => array (
array (
'key' => 'field_5ab8f6946d890',
'label' => 'Label',
'name' => 'name',
'type' => 'wysiwyg',
'instructions' => '',
'default_value' => '',
'toolbar' => 'full',
'media_upload' => 'yes',
),
),
'location' => array (
array (
array (
'param' => 'post_type',
'operator' => '==',
'value' => 'post',
'order_no' => 0,
'group_no' => 0,
),
),
),
'options' => array (
'position' => 'normal',
'layout' => 'no_box',
'hide_on_screen' => array (
),
),
'menu_order' => 0,
));
}
}
```
I know my issue is in #5 above. I am not clear how to run the function to load that field for every post. Any insight?
Also, how would I then automatically output this field code in the single.php template before the post content. Can I use a WordPress function to do that as well? | WordPress by default hide errors for ajax request call. This can be confirmed from the source file [`wp-includes/load.php#L352`](https://core.trac.wordpress.org/browser/trunk/src/wp-includes/load.php#L353), here:
```php
if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) || wp_doing_ajax() ) {
@ini_set( 'display_errors', 0 );
}
```
See the function `wp_doing_ajax()` is being used in the conditional statement thus the `display_errors` is being set.
To workaround this, you need to turn on error reporting manually at top of your ajax function call as suggested by [@Friss](https://wordpress.stackexchange.com/a/299011/36349). |
298,963 | <p>I want to know use of <strong>esc_attr()</strong>?
how it is used?
Any example would be highly help!</p>
<pre><code>esc_attr( $variable )
</code></pre>
| [
{
"answer_id": 298964,
"author": "Niv Asraf",
"author_id": 125474,
"author_profile": "https://wordpress.stackexchange.com/users/125474",
"pm_score": 4,
"selected": true,
"text": "<p>esc_attr() is written specifically for escaping a string that is to be used as an html attribute, which means also escaping single and double-quote characters etc.</p>\n\n<p>In general, it's better to use the data validation API that WP provides rather than the generic PHP functions.</p>\n"
},
{
"answer_id": 355195,
"author": "Arif Rahman",
"author_id": 150838,
"author_profile": "https://wordpress.stackexchange.com/users/150838",
"pm_score": 1,
"selected": false,
"text": "<p>esc_attr() is writing for escaping a string that is to be used as an html attribute.\nWhen escaping the values of attributes that accept URIs (like href and src), it is important to pass the value through esc_url().</p>\n\n<p>Note: that when using esc_url(), you don’t need to also use esc_attr().</p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298963",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140003/"
]
| I want to know use of **esc\_attr()**?
how it is used?
Any example would be highly help!
```
esc_attr( $variable )
``` | esc\_attr() is written specifically for escaping a string that is to be used as an html attribute, which means also escaping single and double-quote characters etc.
In general, it's better to use the data validation API that WP provides rather than the generic PHP functions. |
298,971 | <p>I'm working on a custom theme. For my comment section, if the user role is administrator I want to display "Admin", if subscriber "Subscriber", etc.</p>
<p>The problem is, I will add this code and "Admin" shows beside all users even if not admin (I've tried changing the role, this is just an admin example):</p>
<pre><code>if ( current_user_can( 'administrator' ) ) {
echo '<div class="admin-tag"></div>';
}
</code></pre>
<p>Here is another one I tried, did not work at all:</p>
<pre><code>if( current_user_can( 'administrator' ) ) {
echo 'Admin';
} else if ( current_user_can( 'subscriber' ) ) {
echo 'Subscriber';
}
</code></pre>
| [
{
"answer_id": 298973,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 2,
"selected": false,
"text": "<p>You are passing a role name, <code>administrator</code>, to <code>current_user_can</code>. Looking at <a href=\"https://codex.wordpress.org/Function_Reference/current_user_can\" rel=\"nofollow noreferrer\">the Codex page</a> this is supported but not guaranteed to work, and should generally be avoided:</p>\n\n<blockquote>\n <p>Passing role names to current_user_can() is discouraged as this is not guaranteed to work correctly (see #22624).</p>\n</blockquote>\n\n<p>Instead, you should use a capability:</p>\n\n<pre><code>if ( current_user_can( 'manage_options' ) ) {\n echo 'Admin';\n} else if ( current_user_can( 'edit_pages' ) ) {\n echo 'Editor';\n} else if ( current_user_can( 'publish_posts' ) ) {\n echo 'Author';\n} else if ( current_user_can( 'read' ) ) {\n echo 'Subscriber';\n}\n</code></pre>\n\n<p>You can find a list of capabilities and roles types <a href=\"https://codex.wordpress.org/Roles_and_Capabilities#Capability_vs._Role_Table\" rel=\"nofollow noreferrer\">on the Codex</a> as well.</p>\n\n<p><strong>Updated</strong> This addresses the case of looping over the users to display each user's role:</p>\n\n<pre><code>foreach ( $comment_users as $user_id ) {\n wp23234_show_user_role( $user_id );\n}\n\nfunction wp23234_show_user_role( $user_id ) {\n $data = get_userdata( $user_id );\n $roles = $data->roles;\n\n if ( in_array( $roles, 'administrator' ) ) {\n echo 'Administrator';\n } else if ( in_array( $roles, 'editor' ) ) {\n echo 'Editor';\n } else if ( in_array( $roles, 'author' ) ) {\n echo 'Author';\n } else if ( in_array ( $roles, 'subscriber' ) ) {\n echo 'Subscriber';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 298976,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>Checking against user roles is not recommended. Roles have capabilities, and it's the capability you need to check against.</p>\n\n<p>E.g. if you want users who can publish posts to be able to do something, use <code>current_user_can( 'publish_posts' )</code>.</p>\n\n<p>If an existing capability doesn't map on to what you're trying to do, you can add one, and this is how you should handle additional features.</p>\n\n<p>Otherwise, you'll run into other issues, For example, a lot of users use <code>manage_options</code> as shorthand to detect if the user is an administrator, but on a multisite this capability changes, and may not do exactly what you expect.</p>\n\n<p>If you must check for a user role however, you can do it this way, but it will only work after the <code>init</code> hook:</p>\n\n<pre><code>$user = wp_get_current_user();\nif ( in_array( 'author', (array) $user->roles ) ) {\n //The user has the \"author\" role\n}\n</code></pre>\n\n<p>Remember, roles are not hierarchical, and are not user levels. Plugins can add additional roles, and what roles do can be changed by plugins</p>\n"
},
{
"answer_id": 299004,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I'm working on a custom theme. For my comment section, if the user role is administrator I want to display \"Admin\", if subscriber \"Subscriber\", etc.</p>\n</blockquote>\n\n<p>You can do it in pure CSS.</p>\n\n<p>Look at the markup generated by WP for comments and you'll notice that it adds a class when the author adds a comment:</p>\n\n<p><a href=\"https://i.stack.imgur.com/P0kLG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/P0kLG.png\" alt=\"enter image description here\"></a></p>\n\n<p><code>comment-author-admin</code> is added to any comment authors who are also admins. This is added by the <code>comment_class</code> function in the default comments template, the same way the <code>body_class</code> and <code>post_class</code> functions work</p>\n\n<p>Now we can use CSS and the <code>:after</code> selector to append the word 'Admin' to another element.</p>\n\n<p>For example:</p>\n\n<pre><code>.comment.comment-author-admin cite:after {\n content: \"Admin\";\n margin-left: 0.5em;\n color: red;\n border: 1px solid red;\n border-radius: 6px;\n padding: 0 0.5em;\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/JNBlS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JNBlS.png\" alt=\"enter image description here\"></a></p>\n\n<p>No PHP necessary.</p>\n\n<p>As for <code>current_user_can</code>, the hint is in the function name <strong>current</strong> user can. AKA you, the current user of the site. It always refers to you, not the author of the content being worked on. Instead, you needed the comment author ID.</p>\n\n<p>Thinking about it criticially, if it did work as you had expected, would it give you the current comment user? Or the current post user? What would happen if the comment had been made by a logged out user?</p>\n"
},
{
"answer_id": 406668,
"author": "Deco Grafics",
"author_id": 223058,
"author_profile": "https://wordpress.stackexchange.com/users/223058",
"pm_score": 0,
"selected": false,
"text": "<p>If you are trying to show the current user role, try this:</p>\n<pre><code><?php\n $current_user = wp_get_current_user();\n global $wp_roles;\n\n $user_roles = $current_user->roles;\n $user_role = array_shift($user_roles);\n\n?>\n\n<?php echo $wp_roles->roles[ $user_role ]['name']; ?> //put this where you want your user role to show\n</code></pre>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298971",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133371/"
]
| I'm working on a custom theme. For my comment section, if the user role is administrator I want to display "Admin", if subscriber "Subscriber", etc.
The problem is, I will add this code and "Admin" shows beside all users even if not admin (I've tried changing the role, this is just an admin example):
```
if ( current_user_can( 'administrator' ) ) {
echo '<div class="admin-tag"></div>';
}
```
Here is another one I tried, did not work at all:
```
if( current_user_can( 'administrator' ) ) {
echo 'Admin';
} else if ( current_user_can( 'subscriber' ) ) {
echo 'Subscriber';
}
``` | You are passing a role name, `administrator`, to `current_user_can`. Looking at [the Codex page](https://codex.wordpress.org/Function_Reference/current_user_can) this is supported but not guaranteed to work, and should generally be avoided:
>
> Passing role names to current\_user\_can() is discouraged as this is not guaranteed to work correctly (see #22624).
>
>
>
Instead, you should use a capability:
```
if ( current_user_can( 'manage_options' ) ) {
echo 'Admin';
} else if ( current_user_can( 'edit_pages' ) ) {
echo 'Editor';
} else if ( current_user_can( 'publish_posts' ) ) {
echo 'Author';
} else if ( current_user_can( 'read' ) ) {
echo 'Subscriber';
}
```
You can find a list of capabilities and roles types [on the Codex](https://codex.wordpress.org/Roles_and_Capabilities#Capability_vs._Role_Table) as well.
**Updated** This addresses the case of looping over the users to display each user's role:
```
foreach ( $comment_users as $user_id ) {
wp23234_show_user_role( $user_id );
}
function wp23234_show_user_role( $user_id ) {
$data = get_userdata( $user_id );
$roles = $data->roles;
if ( in_array( $roles, 'administrator' ) ) {
echo 'Administrator';
} else if ( in_array( $roles, 'editor' ) ) {
echo 'Editor';
} else if ( in_array( $roles, 'author' ) ) {
echo 'Author';
} else if ( in_array ( $roles, 'subscriber' ) ) {
echo 'Subscriber';
}
}
``` |
298,978 | <p>I want to run a function when my theme is activated. I have to add the theme activation hook within a php class:</p>
<pre><code>final class My_Class_Name {
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new self;
self::$instance->actions();
} else {
throw new BadFunctionCallException(sprintf('Plugin %s already instantiated', __CLASS__));
}
return self::$instance;
}
// some code
add_action('after_switch_theme', array( $this, 'activate' ));
function activate() {
// some code
}
// more code
}
My_Class_Name::getInstance();
</code></pre>
<p>When I activate my theme I get the following php error:</p>
<blockquote>
<p>PHP Warning: call_user_func_array() expects parameter 1 to be a valid
callback, class 'My_Class_Name' does not have a method
'activate' in
/Applications/MAMP/htdocs/wp-themes/test/wp-includes/class-wp-hook.php
on line 288</p>
</blockquote>
<p>If I use <code>add_action('after_switch_theme', 'activate' );</code></p>
<p>I get </p>
<blockquote>
<p>PHP Fatal error: Cannot access self:: when no class scope is active</p>
</blockquote>
<p>How can I make the hook work?</p>
| [
{
"answer_id": 298980,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 3,
"selected": true,
"text": "<p>It looks like you are adding the hook just inside the body of the class. Try adding it into an <code>init()</code> method and calling it after it is instantiated or at the very least in the constructor.</p>\n\n<p>I think the issues is that the hook is being registered before the class has been fully read by PHP?</p>\n\n<p>Try this:</p>\n\n<pre><code>final class My_Class_Name {\n\n function init() {\n add_action('after_switch_theme', array( $this, 'activate' ));\n }\n\n function activate() {\n }\n}\n\n$class = new My_Class_Name();\n$class->init();\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 299033,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>Just do not use \"OOP\" if you do not intent to treat things as object or extendab;e classes, use proper namespacing instead and save yourself the pointless headache.</p>\n\n<p>Singleton pattern is not OOP and encapsulating global functions in a class brings no structural or any other kind of value, just forcing you to use much more characters to do anything.</p>\n\n<p>The only use I found so far to have a singleton pattern in PHP is to be able to autoload the code, but in that case you do not need to create the object at the place you do.</p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298978",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1613/"
]
| I want to run a function when my theme is activated. I have to add the theme activation hook within a php class:
```
final class My_Class_Name {
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new self;
self::$instance->actions();
} else {
throw new BadFunctionCallException(sprintf('Plugin %s already instantiated', __CLASS__));
}
return self::$instance;
}
// some code
add_action('after_switch_theme', array( $this, 'activate' ));
function activate() {
// some code
}
// more code
}
My_Class_Name::getInstance();
```
When I activate my theme I get the following php error:
>
> PHP Warning: call\_user\_func\_array() expects parameter 1 to be a valid
> callback, class 'My\_Class\_Name' does not have a method
> 'activate' in
> /Applications/MAMP/htdocs/wp-themes/test/wp-includes/class-wp-hook.php
> on line 288
>
>
>
If I use `add_action('after_switch_theme', 'activate' );`
I get
>
> PHP Fatal error: Cannot access self:: when no class scope is active
>
>
>
How can I make the hook work? | It looks like you are adding the hook just inside the body of the class. Try adding it into an `init()` method and calling it after it is instantiated or at the very least in the constructor.
I think the issues is that the hook is being registered before the class has been fully read by PHP?
Try this:
```
final class My_Class_Name {
function init() {
add_action('after_switch_theme', array( $this, 'activate' ));
}
function activate() {
}
}
$class = new My_Class_Name();
$class->init();
```
Hope this helps! |
298,982 | <p>I’ve been using basic user rights functionality on a multi-user WP site for a while and its worked out great, having most user accounts just have access to their own posts but a few “editors” having access to everyone’s posts. This was assisted by the <em>wp-front</em> plugin that allows you to easily define user roles.</p>
<p>However I now have a scenario where I need multiple authors at the same external company and an editor also at the company that will oversee the work of the other individuals.</p>
<p>This new remote editor role is new and problematic as they would need to be able to see their own posts plus any posts created by other editors at the same company. They mustn’t be able to see everyone’s posts though.</p>
<p>Is this possible with wp-front or any other plugin or simply by some hand made solution outside of plugins ?</p>
<p>Ideally a solution would work by adding collections of users to groups of some kind but it doesn't have to.</p>
| [
{
"answer_id": 301429,
"author": "Clemens Tolboom",
"author_id": 136493,
"author_profile": "https://wordpress.stackexchange.com/users/136493",
"pm_score": -1,
"selected": false,
"text": "<p>As you now have two roles for the same company I would go for <a href=\"https://wordpress.org/plugins/groups/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/groups/</a></p>\n\n<blockquote>\n <p>Integrates standard WordPress capabilities which can be assigned to groups and users</p>\n</blockquote>\n"
},
{
"answer_id": 301500,
"author": "EarlM",
"author_id": 142218,
"author_profile": "https://wordpress.stackexchange.com/users/142218",
"pm_score": -1,
"selected": false,
"text": "<p>I think this Plugin should do what you´re lookin for: </p>\n\n<p><a href=\"https://de.wordpress.org/plugins/hide-this/\" rel=\"nofollow noreferrer\">https://de.wordpress.org/plugins/hide-this/</a></p>\n"
},
{
"answer_id": 301632,
"author": "Levi Dulstein",
"author_id": 101988,
"author_profile": "https://wordpress.stackexchange.com/users/101988",
"pm_score": 3,
"selected": true,
"text": "<p>Here's my approach. Bear in mind that it covers the basic needs you've described but could be easily expanded into more robust solution. Few steps to follow (all code goes to your <code>functions.php</code>):</p>\n\n<h1>1. Save company name as user meta</h1>\n\n<p>The first thing we need to do is assigning a company name to a user - i'd go with user meta to achieve that. You could add a metabox to edit user screen for easy management, I'm not including code for that here, but I'm sure you get the idea.</p>\n\n<p>For testing you can just add meta to user with <code>update_user_meta( $user_id, 'company', 'Tyrell Corporation' );</code> (<a href=\"https://developer.wordpress.org/reference/functions/update_user_meta/\" rel=\"nofollow noreferrer\">codex</a>)</p>\n\n<p>So in this example I assume that we have a bunch of authors with <code>Tyrell Corporation</code> set as <code>company</code> user meta key and editor with exactly same meta.</p>\n\n<h1>2. Add Company meta to posts based on author's user meta</h1>\n\n<p>To make things easier and cheaper, I'd keep the reference to Company name also in every post saved by any author with company assigned (that way we can get rid of at least one query to author meta table every time we're checking editor's rights to edit the post later on). To do that, I'm using <code>save_post</code> <a href=\"https://developer.wordpress.org/reference/hooks/save_post/\" rel=\"nofollow noreferrer\">hook</a>:</p>\n\n<pre><code>function save_company_meta( $post_id, $post, $update ) {\n // get author's company meta\n $company = get_user_meta( $post->post_author, 'company', true );\n\n if ( ! empty( $author_id ) ) {\n // add meta data to the post\n update_post_meta( $post_id, 'company', true );\n }\n}\n\nadd_action( 'save_post', 'save_company_meta', 10, 3 );\n</code></pre>\n\n<p>Now every time a user saves his/her draft, the company name that was assigned to this user is copied to post meta.</p>\n\n<h1>3. Map editor's edit_post capability</h1>\n\n<p>Finally we can simply <a href=\"https://developer.wordpress.org/reference/functions/map_meta_cap/\" rel=\"nofollow noreferrer\">map</a> editor's 'edit_post' capability. If the post's <code>company</code> meta data is different than editor's <code>company</code> user meta, we take the capability to edit this particular post away from that particular editor. There are some additional conditions in the code below, for example we don't apply restrictions if the post has no <code>company</code> meta at all or is not a <code>post</code> post type. You can align that to your needs:</p>\n\n<pre><code>function restrict_access_to_company_posts( $caps, $cap, $user_id, $args ) {\n\n /*\n We're messing with capabilities only if 'edit_post' \n is currently checked and the current user has editor role\n but is not the administrator\n */\n\n if ( ! in_array( $cap, [ 'edit_post' ], true ) ) {\n return $caps;\n }\n\n if ( ! user_can( $user_id, 'editor' ) || user_can( $user_id, 'administrator' ) ) {\n return $caps;\n }\n\n /*\n $args[0] holds post ID. $args var is a bit enigmatic, it contains\n different stuff depending on the context and there's almost \n no documentation on that, you've got to trust me on this one :)\n Anyways, if no post ID is set, we bail out and return default capabilities\n */\n if ( empty( $args[0] ) ) {\n return $caps;\n }\n\n /*\n You can also make sure that you're restricting access \n to posts only and not pages or other post types\n */\n if ( 'post' !== get_post_type( $args[0] ) ) {\n return $caps;\n }\n\n $post_company = get_post_meta( $args[0], 'company', true );\n $editor_company = get_user_meta( $user_id, 'company', true );\n\n /*\n if no meta data is set or editor is assigned \n to the same company as the post, we allow normal editing\n */\n if ( empty( $post_company ) || $post_company === $editor_company ) {\n return $caps;\n }\n\n // finally, in all other cases, we restrict access to this post\n $caps = [ 'do_not_allow' ];\n\n return $caps;\n}\n</code></pre>\n\n<p>This wouldn't hide the posts completely from admin UI, you can still see them on the list, but editor cannot get into post's edit screen and change it nor see the draft (WordPress will automatically remove all \"edit\" links for you, also in admin bar on front-end).\nOnce the post is published, the Editor still wouldn't be able to edit posts content.</p>\n\n<h1> 4. (Optionaly) Remove posts from admin list completely</h1>\n\n<p>If above still isn't enough, you can also hook into <code>pre_get_posts</code> (<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">codex</a>) to hide posts from admin list completely:</p>\n\n<pre><code>function query_company_posts_only( $query ) {\n\n if ( ! is_admin() || empty( get_current_user_id() ) ) {\n return $query;\n }\n\n $editor_company = get_user_meta( get_current_user_id(), 'company', true );\n\n if ( empty( $editor_company ) ) {\n return $query;\n }\n\n $query->set( 'meta_key', 'company' );\n $query->set( 'meta_value', $editor_company );\n}\n\nadd_action( 'pre_get_posts', 'query_company_posts_only', 10, 1 );\n</code></pre>\n\n<p>Hope that does the trick, just play around with it and add some improvements here and there.</p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298982",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28543/"
]
| I’ve been using basic user rights functionality on a multi-user WP site for a while and its worked out great, having most user accounts just have access to their own posts but a few “editors” having access to everyone’s posts. This was assisted by the *wp-front* plugin that allows you to easily define user roles.
However I now have a scenario where I need multiple authors at the same external company and an editor also at the company that will oversee the work of the other individuals.
This new remote editor role is new and problematic as they would need to be able to see their own posts plus any posts created by other editors at the same company. They mustn’t be able to see everyone’s posts though.
Is this possible with wp-front or any other plugin or simply by some hand made solution outside of plugins ?
Ideally a solution would work by adding collections of users to groups of some kind but it doesn't have to. | Here's my approach. Bear in mind that it covers the basic needs you've described but could be easily expanded into more robust solution. Few steps to follow (all code goes to your `functions.php`):
1. Save company name as user meta
=================================
The first thing we need to do is assigning a company name to a user - i'd go with user meta to achieve that. You could add a metabox to edit user screen for easy management, I'm not including code for that here, but I'm sure you get the idea.
For testing you can just add meta to user with `update_user_meta( $user_id, 'company', 'Tyrell Corporation' );` ([codex](https://developer.wordpress.org/reference/functions/update_user_meta/))
So in this example I assume that we have a bunch of authors with `Tyrell Corporation` set as `company` user meta key and editor with exactly same meta.
2. Add Company meta to posts based on author's user meta
========================================================
To make things easier and cheaper, I'd keep the reference to Company name also in every post saved by any author with company assigned (that way we can get rid of at least one query to author meta table every time we're checking editor's rights to edit the post later on). To do that, I'm using `save_post` [hook](https://developer.wordpress.org/reference/hooks/save_post/):
```
function save_company_meta( $post_id, $post, $update ) {
// get author's company meta
$company = get_user_meta( $post->post_author, 'company', true );
if ( ! empty( $author_id ) ) {
// add meta data to the post
update_post_meta( $post_id, 'company', true );
}
}
add_action( 'save_post', 'save_company_meta', 10, 3 );
```
Now every time a user saves his/her draft, the company name that was assigned to this user is copied to post meta.
3. Map editor's edit\_post capability
=====================================
Finally we can simply [map](https://developer.wordpress.org/reference/functions/map_meta_cap/) editor's 'edit\_post' capability. If the post's `company` meta data is different than editor's `company` user meta, we take the capability to edit this particular post away from that particular editor. There are some additional conditions in the code below, for example we don't apply restrictions if the post has no `company` meta at all or is not a `post` post type. You can align that to your needs:
```
function restrict_access_to_company_posts( $caps, $cap, $user_id, $args ) {
/*
We're messing with capabilities only if 'edit_post'
is currently checked and the current user has editor role
but is not the administrator
*/
if ( ! in_array( $cap, [ 'edit_post' ], true ) ) {
return $caps;
}
if ( ! user_can( $user_id, 'editor' ) || user_can( $user_id, 'administrator' ) ) {
return $caps;
}
/*
$args[0] holds post ID. $args var is a bit enigmatic, it contains
different stuff depending on the context and there's almost
no documentation on that, you've got to trust me on this one :)
Anyways, if no post ID is set, we bail out and return default capabilities
*/
if ( empty( $args[0] ) ) {
return $caps;
}
/*
You can also make sure that you're restricting access
to posts only and not pages or other post types
*/
if ( 'post' !== get_post_type( $args[0] ) ) {
return $caps;
}
$post_company = get_post_meta( $args[0], 'company', true );
$editor_company = get_user_meta( $user_id, 'company', true );
/*
if no meta data is set or editor is assigned
to the same company as the post, we allow normal editing
*/
if ( empty( $post_company ) || $post_company === $editor_company ) {
return $caps;
}
// finally, in all other cases, we restrict access to this post
$caps = [ 'do_not_allow' ];
return $caps;
}
```
This wouldn't hide the posts completely from admin UI, you can still see them on the list, but editor cannot get into post's edit screen and change it nor see the draft (WordPress will automatically remove all "edit" links for you, also in admin bar on front-end).
Once the post is published, the Editor still wouldn't be able to edit posts content.
4. (Optionaly) Remove posts from admin list completely
=======================================================
If above still isn't enough, you can also hook into `pre_get_posts` ([codex](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts)) to hide posts from admin list completely:
```
function query_company_posts_only( $query ) {
if ( ! is_admin() || empty( get_current_user_id() ) ) {
return $query;
}
$editor_company = get_user_meta( get_current_user_id(), 'company', true );
if ( empty( $editor_company ) ) {
return $query;
}
$query->set( 'meta_key', 'company' );
$query->set( 'meta_value', $editor_company );
}
add_action( 'pre_get_posts', 'query_company_posts_only', 10, 1 );
```
Hope that does the trick, just play around with it and add some improvements here and there. |
298,984 | <p>I am working on a site built in visual composer/wp bakery. I do not want to work in the admin but in a php file. </p>
<p>How can I get code like </p>
<pre><code>[vc_column_text]
<h3><a href="home">home</a></h3>
[/vc_column_text]
</code></pre>
<p>to parse from a a php file, rather than WP admin?</p>
| [
{
"answer_id": 299042,
"author": "Jon",
"author_id": 14416,
"author_profile": "https://wordpress.stackexchange.com/users/14416",
"pm_score": 4,
"selected": true,
"text": "<p>Based on Toms comment this will work:</p>\n\n<pre><code><?php echo do_shortcode( ' \n[vc_column_text]\n<h3><a href=\"home\">home</a></h3>\n[/vc_column_text]\n' );?>\n</code></pre>\n"
},
{
"answer_id": 346489,
"author": "Tasos Stot",
"author_id": 174552,
"author_profile": "https://wordpress.stackexchange.com/users/174552",
"pm_score": 1,
"selected": false,
"text": "<p>You can just try this function <code>WPBMap::addAllMappedShortcodes();</code> and the shortcodes will disappear! </p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298984",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14416/"
]
| I am working on a site built in visual composer/wp bakery. I do not want to work in the admin but in a php file.
How can I get code like
```
[vc_column_text]
<h3><a href="home">home</a></h3>
[/vc_column_text]
```
to parse from a a php file, rather than WP admin? | Based on Toms comment this will work:
```
<?php echo do_shortcode( '
[vc_column_text]
<h3><a href="home">home</a></h3>
[/vc_column_text]
' );?>
``` |
298,989 | <p>I'm trying to find anything out there that will list posts under a specific category by date. Here's my example:</p>
<p><strong>Photography</strong> (being the category name)</p>
<p><strong>2018</strong></p>
<ul>
<li>Post title shows here</li>
<li>Post title shows here</li>
<li>Post title shows here</li>
</ul>
<p><strong>2017</strong></p>
<ul>
<li>Post title shows here</li>
<li>post title shows here</li>
<li>Post title shows here</li>
</ul>
<p>I know that this is probably pretty basic wordpress, but all I can really find out there is for all categories, not just one specific one.</p>
| [
{
"answer_id": 299041,
"author": "Friss",
"author_id": 62392,
"author_profile": "https://wordpress.stackexchange.com/users/62392",
"pm_score": 2,
"selected": true,
"text": "<p>Even though it is not the most conventional way of doing, I would proceed like this:</p>\n\n<p><strong>Edit : precision</strong>\nI create a new file category.php which is the template for categories, and put this piece of code inside.</p>\n\n<pre><code>$args = array( 'post_type'=>'post',\n 'posts_per_page'=> -1,\n 'post_status'=>'publish',\n 'orderby'=>'post_date',\n 'order'=>'DESC'\n );\n\n$query = new WP_Query($args);\n\nif($query->have_posts())\n{\n $years = array();\n $postList = '';\n foreach ($query->posts as $post) {\n\n //if we haven't proceed the year yet\n // we display it\n if(!in_array($year = get_the_date('Y',$post->ID),$years))\n {\n $postList.=sprintf('<h2>%s</h2>',$year);\n $years[] = $year;\n }\n\n $postList.=sprintf('<h3><a href=\"%1$s\" title=\"%2$s\">%2$s</a></h3>',get_permalink($post->ID),$post->post_title);\n\n }\n\n echo $postList;\n\n}else{\n\n _e('No posts sorry','your-text-domain');\n\n}\n</code></pre>\n"
},
{
"answer_id": 299193,
"author": "harshclimate",
"author_id": 132008,
"author_profile": "https://wordpress.stackexchange.com/users/132008",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for your help, Friss!</p>\n\n<p>I added category_name to the query so I could draw down the photography category:</p>\n\n<p><code><?php\n $args = array(\n 'post_type' =>'post',\n 'posts_per_page' => -1,\n 'post_status' => 'publish',\n 'orderby' => 'post_date',\n 'order' => 'DESC',\n 'category_name' => 'photography'\n ); $photography_archive = new WP_Query( $args );\n ?></code></p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/298989",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132008/"
]
| I'm trying to find anything out there that will list posts under a specific category by date. Here's my example:
**Photography** (being the category name)
**2018**
* Post title shows here
* Post title shows here
* Post title shows here
**2017**
* Post title shows here
* post title shows here
* Post title shows here
I know that this is probably pretty basic wordpress, but all I can really find out there is for all categories, not just one specific one. | Even though it is not the most conventional way of doing, I would proceed like this:
**Edit : precision**
I create a new file category.php which is the template for categories, and put this piece of code inside.
```
$args = array( 'post_type'=>'post',
'posts_per_page'=> -1,
'post_status'=>'publish',
'orderby'=>'post_date',
'order'=>'DESC'
);
$query = new WP_Query($args);
if($query->have_posts())
{
$years = array();
$postList = '';
foreach ($query->posts as $post) {
//if we haven't proceed the year yet
// we display it
if(!in_array($year = get_the_date('Y',$post->ID),$years))
{
$postList.=sprintf('<h2>%s</h2>',$year);
$years[] = $year;
}
$postList.=sprintf('<h3><a href="%1$s" title="%2$s">%2$s</a></h3>',get_permalink($post->ID),$post->post_title);
}
echo $postList;
}else{
_e('No posts sorry','your-text-domain');
}
``` |
299,015 | <pre><code>add_action( 'init', 'wc_readd_add_to_cart_buttons' );
function wc_readd_add_to_cart_buttons() {
//add to cart button loop
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
}
</code></pre>
<p>I am adding back a button in WooCommerceand need to have a <code><br></code> before the button. How do I insert a <code><b></code> inside the above action?</p>
| [
{
"answer_id": 299018,
"author": "Pabamato",
"author_id": 60079,
"author_profile": "https://wordpress.stackexchange.com/users/60079",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure why you are using init and then adding the function to the WC action.\nThe following should work:</p>\n\n<pre><code>add_action( 'woocommerce_after_shop_loop_item', 'wc_readd_add_to_cart_buttons', 10 );\nif (!function_exists('wc_readd_add_to_cart_buttons')){\n function wc_readd_add_to_cart_buttons() {\n //add to cart button loop\n echo \"<br />\";\n woocommerce_template_loop_add_to_cart();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 299022,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>You can use 'echo' (or 'print') to enclose HTML, but sometimes that gets a bit messy with complex HTML, not to mention having to escape quote/double-quote character.</p>\n\n<p>So try something like this:</p>\n\n<pre><code>function myfunction() {\n // after this next, plain HTML\n ?>\n <div class='myclass'><h1 align=\"center\">This is a heading</h1></div>\n <!-- more HTML code here -->\n <?php // back to PHP\n // .. some more PHP stuff\nreturn;\n}\n</code></pre>\n\n<p>That allows you to put in some complex HTML (or a bunch of it) without having to use <code>echo/print</code>.</p>\n"
}
]
| 2018/03/26 | [
"https://wordpress.stackexchange.com/questions/299015",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140534/"
]
| ```
add_action( 'init', 'wc_readd_add_to_cart_buttons' );
function wc_readd_add_to_cart_buttons() {
//add to cart button loop
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
}
```
I am adding back a button in WooCommerceand need to have a `<br>` before the button. How do I insert a `<b>` inside the above action? | Not sure why you are using init and then adding the function to the WC action.
The following should work:
```
add_action( 'woocommerce_after_shop_loop_item', 'wc_readd_add_to_cart_buttons', 10 );
if (!function_exists('wc_readd_add_to_cart_buttons')){
function wc_readd_add_to_cart_buttons() {
//add to cart button loop
echo "<br />";
woocommerce_template_loop_add_to_cart();
}
}
``` |
299,049 | <p>As an admin, I can preview scheduled posts. In the post listing, there's a "preview" link which appears if you hover over the scheduled post title.</p>
<p>As a contributor, I can preview a post if it is in draft or pending. I can no longer preview the post once it has been scheduled. </p>
<p>Contributors are curious to see what the editor has made of their post and would like to see a preview of it while it is scheduled and not yet published.
To be clear: I'm not looking for a way to allow the contributor to alter the post once it is scheduled, just to (pre)view it.</p>
<p>In the wordpress roles and capabilities, I'm not finding a related capability. There seems to be read, read_private_posts, read_private_pages, but nothing like read_own_future_posts.
I'm not sure why this is not even the default behaviour. It's odd the contributor can view an own post to write it and once it's published, but not in between. Or am I missing something completely here?</p>
| [
{
"answer_id": 299018,
"author": "Pabamato",
"author_id": 60079,
"author_profile": "https://wordpress.stackexchange.com/users/60079",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure why you are using init and then adding the function to the WC action.\nThe following should work:</p>\n\n<pre><code>add_action( 'woocommerce_after_shop_loop_item', 'wc_readd_add_to_cart_buttons', 10 );\nif (!function_exists('wc_readd_add_to_cart_buttons')){\n function wc_readd_add_to_cart_buttons() {\n //add to cart button loop\n echo \"<br />\";\n woocommerce_template_loop_add_to_cart();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 299022,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>You can use 'echo' (or 'print') to enclose HTML, but sometimes that gets a bit messy with complex HTML, not to mention having to escape quote/double-quote character.</p>\n\n<p>So try something like this:</p>\n\n<pre><code>function myfunction() {\n // after this next, plain HTML\n ?>\n <div class='myclass'><h1 align=\"center\">This is a heading</h1></div>\n <!-- more HTML code here -->\n <?php // back to PHP\n // .. some more PHP stuff\nreturn;\n}\n</code></pre>\n\n<p>That allows you to put in some complex HTML (or a bunch of it) without having to use <code>echo/print</code>.</p>\n"
}
]
| 2018/03/27 | [
"https://wordpress.stackexchange.com/questions/299049",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140561/"
]
| As an admin, I can preview scheduled posts. In the post listing, there's a "preview" link which appears if you hover over the scheduled post title.
As a contributor, I can preview a post if it is in draft or pending. I can no longer preview the post once it has been scheduled.
Contributors are curious to see what the editor has made of their post and would like to see a preview of it while it is scheduled and not yet published.
To be clear: I'm not looking for a way to allow the contributor to alter the post once it is scheduled, just to (pre)view it.
In the wordpress roles and capabilities, I'm not finding a related capability. There seems to be read, read\_private\_posts, read\_private\_pages, but nothing like read\_own\_future\_posts.
I'm not sure why this is not even the default behaviour. It's odd the contributor can view an own post to write it and once it's published, but not in between. Or am I missing something completely here? | Not sure why you are using init and then adding the function to the WC action.
The following should work:
```
add_action( 'woocommerce_after_shop_loop_item', 'wc_readd_add_to_cart_buttons', 10 );
if (!function_exists('wc_readd_add_to_cart_buttons')){
function wc_readd_add_to_cart_buttons() {
//add to cart button loop
echo "<br />";
woocommerce_template_loop_add_to_cart();
}
}
``` |
299,059 | <p>Does anyone know if there is a way to handle a custom taxonomy for the <code>nav_menu_item</code> built'in post type?
When I assign my custom taxonomy to this post type, i don't see any change in the menu editor...
It works well with <code>posts</code>, <code>pages</code> and <code>custom post types</code>.</p>
<p>Here how I've registered my custom taxonomy:</p>
<pre><code> add_action( 'init', 'my_region_taxo', 0 );
function my_region_taxo() {
$labels = array(
'name' => _x( 'Regions', 'Taxonomy General Name', 'my-text-domain' ),
'singular_name' => _x( 'Region', 'Taxonomy Singular Name', 'my-text-domain' ),
(...)
);
$rewrite = array(
'slug' => 'region',
'with_front' => true,
'hierarchical' => true,
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => false,
'show_tagcloud' => false,
'rewrite' => $rewrite,
'show_in_rest' => true,
);
register_taxonomy(
'my_region_taxonomy',
array(
'post',
'page',
'nav_menu_item'
),
$args
);
}
</code></pre>
| [
{
"answer_id": 299061,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>This is not how you enable adding your taxonomy terms to menus. To do that you just set <code>show_in_nav_menus</code> to <code>true</code> when registering the taxonomy. You have it set to <code>false</code>.</p>\n\n<pre><code>$args = array(\n 'labels' => $labels,\n 'hierarchical' => true,\n 'public' => true,\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'show_in_nav_menus' => true, // This\n 'show_tagcloud' => false,\n 'rewrite' => $rewrite,\n 'show_in_rest' => true,\n);\n\nregister_taxonomy(\n 'my_region_taxonomy',\n array(\n 'post',\n 'page', // Not here\n ),\n $args\n);\n</code></pre>\n\n<p>Your taxonomy should not actually be a taxonomy for the <code>nav_menu_item</code> post type.</p>\n"
},
{
"answer_id": 386270,
"author": "Luke Chinworth",
"author_id": 82308,
"author_profile": "https://wordpress.stackexchange.com/users/82308",
"pm_score": 0,
"selected": false,
"text": "<p>A quick way is to use the normal post edit page by enabling <code>show_ui</code> for the <code>nav_menu_item</code> post type.</p>\n<pre><code>add_filter('register_post_type_args', 'register_post_type_args', 10, 2);\n\nfunction register_post_type_args( $args, $post_type ) {\n if ( $post_type === 'nav_menu_item' ) {\n $args['show_ui'] = true;\n }\n return $args;\n}\n</code></pre>\n<p>Then you can inspect the menu to get the nav_menu_item post id, and replace it in the post edit url. I know it's not as good as being able to set the terms from the menu editor, but it's a quick way to get it working.</p>\n"
}
]
| 2018/03/27 | [
"https://wordpress.stackexchange.com/questions/299059",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136422/"
]
| Does anyone know if there is a way to handle a custom taxonomy for the `nav_menu_item` built'in post type?
When I assign my custom taxonomy to this post type, i don't see any change in the menu editor...
It works well with `posts`, `pages` and `custom post types`.
Here how I've registered my custom taxonomy:
```
add_action( 'init', 'my_region_taxo', 0 );
function my_region_taxo() {
$labels = array(
'name' => _x( 'Regions', 'Taxonomy General Name', 'my-text-domain' ),
'singular_name' => _x( 'Region', 'Taxonomy Singular Name', 'my-text-domain' ),
(...)
);
$rewrite = array(
'slug' => 'region',
'with_front' => true,
'hierarchical' => true,
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => false,
'show_tagcloud' => false,
'rewrite' => $rewrite,
'show_in_rest' => true,
);
register_taxonomy(
'my_region_taxonomy',
array(
'post',
'page',
'nav_menu_item'
),
$args
);
}
``` | This is not how you enable adding your taxonomy terms to menus. To do that you just set `show_in_nav_menus` to `true` when registering the taxonomy. You have it set to `false`.
```
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true, // This
'show_tagcloud' => false,
'rewrite' => $rewrite,
'show_in_rest' => true,
);
register_taxonomy(
'my_region_taxonomy',
array(
'post',
'page', // Not here
),
$args
);
```
Your taxonomy should not actually be a taxonomy for the `nav_menu_item` post type. |
299,065 | <p>3/26: I created the Wordpress website on a live server. I downloaded a copy to my XAMPP server. I exported the database and created a local one.
I modified the wp-config.php file to connect to it. That all works.</p>
<p>However, I am not able to use any of the links in the navbar and otherwise to open any of the pages and posts. All those hyperlinks have absolute addresses that use the domain name of the live server.</p>
<p>I can add the directory path and go to "/index.php" under localhost but all the other paths are open-ended with no file name and they do not work.</p>
<p>If I do not use "index.php" and just have a "/" it will not go to the homepage. For the homepage, if I leave out the "index.php" file name, it will have the header and navbar and say "Oops! That page can’t be found." </p>
<p>If I use open-ended links to anything else, it will say "Error establishing a database connection."</p>
<p>3/27: Thank you all very much for your responses! I have a plugin installed that I have not used yet called "Velvet Blues Update URLs." I will give that a try. I also have "All-in-One WP Migration" and "Duplicator," but the website is over 600mb in size so the free versions of those will not work.</p>
| [
{
"answer_id": 299068,
"author": "keithschm",
"author_id": 109256,
"author_profile": "https://wordpress.stackexchange.com/users/109256",
"pm_score": 1,
"selected": true,
"text": "<p>did you change the urls in the database?</p>\n\n<p>add these to your wp-config.php </p>\n\n<pre><code>define('WP_HOME', 'http://example.com');\ndefine('WP_SITEURL, 'http://example.com');\n</code></pre>\n\n<p>Then update the ones in settings and remove those from the config file.</p>\n\n<p>also update your permalinks as well</p>\n"
},
{
"answer_id": 299071,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 1,
"selected": false,
"text": "<p>If you have it available, you can use WP_CLI to search and replace all instances of the URL.</p>\n\n<p><code>wp search-replace 'oldurl.com' 'newurl.com'</code></p>\n\n<p>Codex - <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/search-replace/</a></p>\n"
}
]
| 2018/03/27 | [
"https://wordpress.stackexchange.com/questions/299065",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140574/"
]
| 3/26: I created the Wordpress website on a live server. I downloaded a copy to my XAMPP server. I exported the database and created a local one.
I modified the wp-config.php file to connect to it. That all works.
However, I am not able to use any of the links in the navbar and otherwise to open any of the pages and posts. All those hyperlinks have absolute addresses that use the domain name of the live server.
I can add the directory path and go to "/index.php" under localhost but all the other paths are open-ended with no file name and they do not work.
If I do not use "index.php" and just have a "/" it will not go to the homepage. For the homepage, if I leave out the "index.php" file name, it will have the header and navbar and say "Oops! That page can’t be found."
If I use open-ended links to anything else, it will say "Error establishing a database connection."
3/27: Thank you all very much for your responses! I have a plugin installed that I have not used yet called "Velvet Blues Update URLs." I will give that a try. I also have "All-in-One WP Migration" and "Duplicator," but the website is over 600mb in size so the free versions of those will not work. | did you change the urls in the database?
add these to your wp-config.php
```
define('WP_HOME', 'http://example.com');
define('WP_SITEURL, 'http://example.com');
```
Then update the ones in settings and remove those from the config file.
also update your permalinks as well |
299,069 | <p>currently I am developing a site using the Dokan multivendor plugin. I added a custom field in the registration form and </p>
<p>The below code is being used to add the custom field in the registration form</p>
<pre><code><p class="form-row form-group form-row-wide">
<label for="tskypeid"><?php _e( 'Skype ID', 'dokan-lite' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text form-control" name="tskypeid" id="tskype-id" value="<?php if ( ! empty( $postdata['tskypeid'] ) ) echo esc_attr($postdata['tskypeid']); ?>" required="required" />
</p>
</code></pre>
<p>This is code that is being used to save the field data:</p>
<pre><code>// save skype id after registration
function ms_dokan_on_create_seller( $user_id, $data ) {
if ( $data['role'] != 'seller' ) {
return;
}
$dokan_settings = array(
'tskypeid' => $_POST['tskypeid'],
);
update_user_meta( $user_id, 'dokan_profile_settings', $dokan_settings );
update_user_meta( $user_id, 'dokan_store_name', $dokan_settings['store_name'] );
do_action( 'dokan_new_seller_created', $user_id, $dokan_settings );
}
add_action( 'woocommerce_created_customer', 'ms_dokan_on_create_seller', 10, 2);
</code></pre>
<p>tried to access the value using the below code:</p>
<pre><code>function wc_vendors_name_loop( $store_id ) {
$user_id = get_current_user_id();
$dokan_profile_settings = get_user_meta( $user_id )
['dokan_profile_settings'];
echo "<pre>";
var_dump( $dokan_profile_settings );
echo "</pre>";
}
add_action( 'wp_footer', 'wc_vendors_name_loop' );
</code></pre>
<p>This code outputs the below result:</p>
<pre><code>array(1) {
[0]=>
string(1183)
"a:17:{
s:8:"tskypeid";
s:7:"asdfasd";
s:10:"store_name";
s:17:"asdfas dfasdfasdf";
s:9:"store_ppp";
i:0;s:7:"address";
a:6:{
s:8:"street_1";
s:19:"fasdf asdf asdf sad";
s:8:"street_2";
s:15:"sadf asdf asd f";
s:4:"city";
s:10:"asdf asd f";
s:3:"zip";
s:8:"sad fsad";
s:7:"country";
s:2:"AZ";
s:5:"state";
s:9:"asdfasdf ";
}
s:8:
"location";
s:0:"";
s:12:"find_address";
s:27:"dsfas sadf sadfsadfsadf asf";
s:6:"banner";
i:0;s:5:"phone";
s:9:"345346456";
s:10:"show_email";
s:3:"yes";
s:14:"show_more_ptab";
s:3:"yes";
s:8:"gravatar";
i:0;s:10:"enable_tnc";
s:2:"on";
s:9:"store_tnc";
s:27:"asdf asdf asdfa sdf sadfsdf";
s:18:"profile_completion";
a:6:{
s:5:"phone";
i:10;s:10:"store_name";
i:10;s:7:"address";
i:10;s:9:"next_todo";
s:31:"Add Banner to gain 15% progress";
s:8:"progress";
i:30;s:13:"progress_vals";
a:8:{
s:10:"banner_val";
i:15;s:19:"profile_picture_val";
i:15;s:14:"store_name_val";
i:10;s:10:"social_val";
a:5:{
s:2:"fb";
i:2;s:5:"gplus";
i:2;s:7:"twitter";
i:2;s:7:"youtube";
i:2;s:8:"linkedin";
i:2;
}
s:18:"payment_method_val";
i:15;s:9:"phone_val";
i:10;s:11:"address_val";
i:10;s:7:"map_val";
i:15;
}
}
s:23:"show_min_order_discount";
s:2:"no";
s:28:"setting_minimum_order_amount";
s:0:"";
s:24:"setting_order_percentage";
s:0:"";
}"
}
</code></pre>
<p>Here I want to access the value of "tskypeid" in line 5 and the value is "asdfasd" in line 6</p>
<p>Please tell me how can I access that value.</p>
<p>Any help will be greatly appreciated.</p>
<p>Thank you in advance.</p>
| [
{
"answer_id": 299070,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 2,
"selected": false,
"text": "<p>If you're asking how to get those meta keys via WordPress, you can use the <code>get_user_meta()</code> - <a href=\"https://codex.wordpress.org/Function_Reference/get_user_meta\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_user_meta</a></p>\n\n<p><code>get_user_meta( $user_id, 'tskypeid', true )</code></p>\n"
},
{
"answer_id": 299086,
"author": "M.S Shohan",
"author_id": 124702,
"author_profile": "https://wordpress.stackexchange.com/users/124702",
"pm_score": 0,
"selected": false,
"text": "<p>Woohoo! I got it fixed with this code. function </p>\n\n<pre><code>wc_vendors_name_loop() { \n $store_id = dokan_get_current_user_id(); \n $existing_dokan_settings = get_user_meta( $store_id, 'dokan_profile_settings', true ); \n echo $existing_dokan_settings['tskypeid']; \n} \nadd_action( 'wp_footer', 'wc_vendors_name_loop' ); \n</code></pre>\n\n<p>Now I can display the skype id in the front end.</p>\n"
}
]
| 2018/03/27 | [
"https://wordpress.stackexchange.com/questions/299069",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124702/"
]
| currently I am developing a site using the Dokan multivendor plugin. I added a custom field in the registration form and
The below code is being used to add the custom field in the registration form
```
<p class="form-row form-group form-row-wide">
<label for="tskypeid"><?php _e( 'Skype ID', 'dokan-lite' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text form-control" name="tskypeid" id="tskype-id" value="<?php if ( ! empty( $postdata['tskypeid'] ) ) echo esc_attr($postdata['tskypeid']); ?>" required="required" />
</p>
```
This is code that is being used to save the field data:
```
// save skype id after registration
function ms_dokan_on_create_seller( $user_id, $data ) {
if ( $data['role'] != 'seller' ) {
return;
}
$dokan_settings = array(
'tskypeid' => $_POST['tskypeid'],
);
update_user_meta( $user_id, 'dokan_profile_settings', $dokan_settings );
update_user_meta( $user_id, 'dokan_store_name', $dokan_settings['store_name'] );
do_action( 'dokan_new_seller_created', $user_id, $dokan_settings );
}
add_action( 'woocommerce_created_customer', 'ms_dokan_on_create_seller', 10, 2);
```
tried to access the value using the below code:
```
function wc_vendors_name_loop( $store_id ) {
$user_id = get_current_user_id();
$dokan_profile_settings = get_user_meta( $user_id )
['dokan_profile_settings'];
echo "<pre>";
var_dump( $dokan_profile_settings );
echo "</pre>";
}
add_action( 'wp_footer', 'wc_vendors_name_loop' );
```
This code outputs the below result:
```
array(1) {
[0]=>
string(1183)
"a:17:{
s:8:"tskypeid";
s:7:"asdfasd";
s:10:"store_name";
s:17:"asdfas dfasdfasdf";
s:9:"store_ppp";
i:0;s:7:"address";
a:6:{
s:8:"street_1";
s:19:"fasdf asdf asdf sad";
s:8:"street_2";
s:15:"sadf asdf asd f";
s:4:"city";
s:10:"asdf asd f";
s:3:"zip";
s:8:"sad fsad";
s:7:"country";
s:2:"AZ";
s:5:"state";
s:9:"asdfasdf ";
}
s:8:
"location";
s:0:"";
s:12:"find_address";
s:27:"dsfas sadf sadfsadfsadf asf";
s:6:"banner";
i:0;s:5:"phone";
s:9:"345346456";
s:10:"show_email";
s:3:"yes";
s:14:"show_more_ptab";
s:3:"yes";
s:8:"gravatar";
i:0;s:10:"enable_tnc";
s:2:"on";
s:9:"store_tnc";
s:27:"asdf asdf asdfa sdf sadfsdf";
s:18:"profile_completion";
a:6:{
s:5:"phone";
i:10;s:10:"store_name";
i:10;s:7:"address";
i:10;s:9:"next_todo";
s:31:"Add Banner to gain 15% progress";
s:8:"progress";
i:30;s:13:"progress_vals";
a:8:{
s:10:"banner_val";
i:15;s:19:"profile_picture_val";
i:15;s:14:"store_name_val";
i:10;s:10:"social_val";
a:5:{
s:2:"fb";
i:2;s:5:"gplus";
i:2;s:7:"twitter";
i:2;s:7:"youtube";
i:2;s:8:"linkedin";
i:2;
}
s:18:"payment_method_val";
i:15;s:9:"phone_val";
i:10;s:11:"address_val";
i:10;s:7:"map_val";
i:15;
}
}
s:23:"show_min_order_discount";
s:2:"no";
s:28:"setting_minimum_order_amount";
s:0:"";
s:24:"setting_order_percentage";
s:0:"";
}"
}
```
Here I want to access the value of "tskypeid" in line 5 and the value is "asdfasd" in line 6
Please tell me how can I access that value.
Any help will be greatly appreciated.
Thank you in advance. | If you're asking how to get those meta keys via WordPress, you can use the `get_user_meta()` - <https://codex.wordpress.org/Function_Reference/get_user_meta>
`get_user_meta( $user_id, 'tskypeid', true )` |
299,073 | <p>I just learned that it is possible to create differtent header.php files in your theme by creating a new File and calling it something like: header-myname.php.</p>
<p>To call, i would use the header templates tag like this:</p>
<pre><code>get_header( 'myname' );
</code></pre>
<p>But that way I would have to put my file in the main directory of my theme, am I right? </p>
<p>So my question is:
Is there a way to put the custom-header file into a sub-directory and if so, how to i declare its position with the get_header() tag ?</p>
| [
{
"answer_id": 299074,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": false,
"text": "<p>No. The function adds a string of <code>\"header-{$name}.php\"</code> to the search for templates. You can't prepend it.</p>\n\n<p>However, if you're not reyling on the <code>get_header</code> action, you can just as well use <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\"><code>get_template_part()</code></a>, as these functions work very similar.</p>\n\n<pre><code>get_template_part('subdir/header', 'my');\n</code></pre>\n\n<p>will look for a file in <strong>subdir/header-my.php</strong>.</p>\n"
},
{
"answer_id": 299076,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>Not with <code>get_header()</code>, no. As you can see in <a href=\"https://developer.wordpress.org/reference/functions/get_header/#source\" rel=\"nofollow noreferrer\">the source</a> of <code>get_header()</code> the argument is simply appended to the filename and searched for in the root theme directory:</p>\n\n<pre><code>$name = (string) $name;\nif ( '' !== $name ) {\n $templates[] = \"header-{$name}.php\";\n}\n\n$templates[] = 'header.php';\n\nlocate_template( $templates, true );\n</code></pre>\n\n<p>And as far as I can tell there are no filters that would be useful here. As <a href=\"https://twitter.com/justintadlock/status/977962996063490048\" rel=\"nofollow noreferrer\">Justin Tadlock noted</a>, this lack of filters has persisted for 8 years.</p>\n\n<p>The next best thing you could do is to use <code>get_template_part()</code> instead:</p>\n\n<pre><code>get_template_part( 'subdirectory/header', 'myname' );\n</code></pre>\n\n<p>But you'll need your regular header in the subdirectory too.</p>\n\n<p>The only thing you'll miss out on doing it this way is that the <code>get_header()</code> hook won't fire. But you could remedy that by putting it at the beginning of your custom template:</p>\n\n<pre><code>do_action( 'get_header' );\n</code></pre>\n\n<p>or for the custom template:</p>\n\n<pre><code>do_action( 'get_header', 'myname' );\n</code></pre>\n\n<p>But honestly, I'm not sure how widely used that hook is, because it's not very useful. You can probably get away with leaving it out.</p>\n"
}
]
| 2018/03/27 | [
"https://wordpress.stackexchange.com/questions/299073",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140133/"
]
| I just learned that it is possible to create differtent header.php files in your theme by creating a new File and calling it something like: header-myname.php.
To call, i would use the header templates tag like this:
```
get_header( 'myname' );
```
But that way I would have to put my file in the main directory of my theme, am I right?
So my question is:
Is there a way to put the custom-header file into a sub-directory and if so, how to i declare its position with the get\_header() tag ? | No. The function adds a string of `"header-{$name}.php"` to the search for templates. You can't prepend it.
However, if you're not reyling on the `get_header` action, you can just as well use [`get_template_part()`](https://developer.wordpress.org/reference/functions/get_template_part/), as these functions work very similar.
```
get_template_part('subdir/header', 'my');
```
will look for a file in **subdir/header-my.php**. |
299,132 | <p>How can <code>$post_id</code> be used while echoing posts in single.php?</p>
<p>Is it a global variable?</p>
| [
{
"answer_id": 299134,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 5,
"selected": true,
"text": "<p>No, <code>$post_id</code> is not a global variable. You can see a list of global variables WordPress creates here: <a href=\"https://codex.wordpress.org/Global_Variables\" rel=\"noreferrer\">https://codex.wordpress.org/Global_Variables</a></p>\n\n<p><code>$post_id</code> is just a common naming convention for a variable that contains a post ID. In tutorials and example code it shows that the value is expected to be a post ID, but you still need to have set its value somewhere else in the code.</p>\n\n<p>If you are inside <a href=\"https://developer.wordpress.org/themes/basics/the-loop/\" rel=\"noreferrer\">The Loop</a> you can get the ID of the current page or post in the loop with <code>$post_id = get_the_ID()</code>. If you are outside The Loop and want to get the ID of the currently queried post or page you can use <code>$post_id = get_queried_object_id()</code>.</p>\n\n<p>Another way you might get a post ID is in a hook callback. For example, in the <a href=\"https://developer.wordpress.org/reference/hooks/post_thumbnail_size/\" rel=\"noreferrer\"><code>post_thumbnail_size</code></a> hook the callback receives a post ID as the 2nd argument:</p>\n\n<pre><code>function wpse_299132_post_thumbnail_size( $size, $post_id ) {\n return $size;\n}\nadd_filter( 'post_thumbnail_size', 'wpse_299132_post_thumbnail_size', 10, 2 );\n</code></pre>\n\n<p>But that's just the name used in the documentation to make it clear what the variable contains. You can call it anything you like. This is also valid, for example:</p>\n\n<pre><code>function wpse_299132_post_thumbnail_size( $size, $myPostId ) {\n return $size;\n}\nadd_filter( 'post_thumbnail_size', 'wpse_299132_post_thumbnail_size', 10, 2 );\n</code></pre>\n\n<p><code>$myPostId</code> is the 2nd argument, so will contain a post ID. But what you call it doesn't matter.</p>\n"
},
{
"answer_id": 299148,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 2,
"selected": false,
"text": "<p><code>$post_id</code> is not a global variable. <code>$post</code> is a global variable. You can use</p>\n\n<pre><code>global $post;\n$post_id = $post->ID;\n</code></pre>\n"
},
{
"answer_id": 364089,
"author": "JoyChetry",
"author_id": 184385,
"author_profile": "https://wordpress.stackexchange.com/users/184385",
"pm_score": 1,
"selected": false,
"text": "<p>In some cases, such as when you're outside The Loop, you may need to use<br>\n<a href=\"https://developer.wordpress.org/reference/functions/get_queried_object_id/\" rel=\"nofollow noreferrer\">get_queried_object_id()</a> instead of <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow noreferrer\">get_the_ID()</a>.</p>\n\n<p><code>$postID = get_queried_object_id();</code></p>\n"
}
]
| 2018/03/28 | [
"https://wordpress.stackexchange.com/questions/299132",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140003/"
]
| How can `$post_id` be used while echoing posts in single.php?
Is it a global variable? | No, `$post_id` is not a global variable. You can see a list of global variables WordPress creates here: <https://codex.wordpress.org/Global_Variables>
`$post_id` is just a common naming convention for a variable that contains a post ID. In tutorials and example code it shows that the value is expected to be a post ID, but you still need to have set its value somewhere else in the code.
If you are inside [The Loop](https://developer.wordpress.org/themes/basics/the-loop/) you can get the ID of the current page or post in the loop with `$post_id = get_the_ID()`. If you are outside The Loop and want to get the ID of the currently queried post or page you can use `$post_id = get_queried_object_id()`.
Another way you might get a post ID is in a hook callback. For example, in the [`post_thumbnail_size`](https://developer.wordpress.org/reference/hooks/post_thumbnail_size/) hook the callback receives a post ID as the 2nd argument:
```
function wpse_299132_post_thumbnail_size( $size, $post_id ) {
return $size;
}
add_filter( 'post_thumbnail_size', 'wpse_299132_post_thumbnail_size', 10, 2 );
```
But that's just the name used in the documentation to make it clear what the variable contains. You can call it anything you like. This is also valid, for example:
```
function wpse_299132_post_thumbnail_size( $size, $myPostId ) {
return $size;
}
add_filter( 'post_thumbnail_size', 'wpse_299132_post_thumbnail_size', 10, 2 );
```
`$myPostId` is the 2nd argument, so will contain a post ID. But what you call it doesn't matter. |
299,138 | <p>I used <a href="https://wordpress.stackexchange.com/a/537/3206">this answer's</a> code to generate a widget that displays all subpages of the parent's page:</p>
<pre><code>if (is_page()) {
global $wp_query;
if( empty($wp_query->post->post_parent) ) {
$parent = $wp_query->post->ID;
} else {
$parent = $wp_query->post->post_parent;
}
if(wp_list_pages("title_li=&child_of=$parent&echo=0" )) {
wp_list_pages("title_li=&child_of=$parent&echo=1" );
}
}
</code></pre>
<p>I now realise this does not cope if I am in a grandchild page, in that the uncles and aunties are not displayed, only the parents.</p>
<p>I don't understand how I can adapt this code to display more than 2 levels of menu tree.</p>
<p>Help appreciated.</p>
| [
{
"answer_id": 299180,
"author": "Alex Davison",
"author_id": 140648,
"author_profile": "https://wordpress.stackexchange.com/users/140648",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you're currently only grabbing the parent, and not checking for the top level ancestor.</p>\n\n<p>Try replacing:</p>\n\n<pre><code> if( empty($wp_query->post->post_parent) ) {\n $parent = $wp_query->post->ID;\n } else {\n $parent = $wp_query->post->post_parent;\n }\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>if ($post->post_parent) {\n $ancestors=get_post_ancestors($post->ID);\n $root=count($ancestors)-1;\n $parent = $ancestors[$root];\n} else {\n $parent = $post->ID;\n}\n</code></pre>\n\n<p>As per: <a href=\"https://css-tricks.com/snippets/wordpress/find-id-of-top-most-parent-page/\" rel=\"nofollow noreferrer\">https://css-tricks.com/snippets/wordpress/find-id-of-top-most-parent-page/</a></p>\n"
},
{
"answer_id": 299663,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Here is a function that will output the top level parent along with all of the children of the current page. Helpful menu classes are added to the output. E.g. <code>page_item_has_children</code>, <code>current_page_item</code>, <code>current_page_ancestor</code>, etc.</p>\n\n<p>This solution is <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/#comment-391\" rel=\"nofollow noreferrer\">based on one of the examples</a> in the documentation for <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages\" rel=\"nofollow noreferrer\"><code>wp_list_pages()</code></a> and <a href=\"https://wordpress.stackexchange.com/a/99900/2807\">this answer</a> here on WPSE, which references the same example.</p>\n\n<pre><code>/**\n * Use wp_list_pages() to display parent and all child pages of current page.\n */\nfunction wpse_get_ancestor_tree() {\n // Bail if this is not a page.\n if ( ! is_page() ) {\n return false;\n }\n\n // Get the current post.\n $post = get_post();\n\n /**\n * Get array of post ancestor IDs.\n * Note: The direct parent is returned as the first value in the array.\n * The highest level ancestor is returned as the last value in the array.\n * See https://codex.wordpress.org/Function_Reference/get_post_ancestors\n */\n $ancestors = get_post_ancestors( $post->ID );\n\n // If there are ancestors, get the top level parent.\n // Otherwise use the current post's ID.\n $parent = ( ! empty( $ancestors ) ) ? array_pop( $ancestors ) : $post->ID;\n\n // Get all pages that are a child of $parent.\n $pages = get_pages( [\n 'child_of' => $parent,\n ] );\n\n // Bail if there are no results.\n if ( ! $pages ) {\n return false;\n }\n\n // Store array of page IDs to include latere on.\n $page_ids = array();\n foreach ( $pages as $page ) {\n $page_ids[] = $page->ID;\n }\n\n // Add parent page to beginning of $page_ids array.\n array_unshift( $page_ids, $parent );\n\n // Get the output and return results if they exist.\n $output = wp_list_pages( [\n 'include' => $page_ids,\n 'title_li' => false,\n 'echo' => false,\n ] );\n\n if ( ! $output ) {\n return false;\n } else { \n return '<ul class=\"page-menu ancestor-tree\">' . PHP_EOL .\n $output . PHP_EOL .\n '</ul>' . PHP_EOL;\n }\n}\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>echo wpse_get_ancestor_tree();\n</code></pre>\n\n<p><strong>Example Page Structure:</strong></p>\n\n<blockquote>\n<pre><code>Parent Page\n Child Page 01\n Child Page 02\n Child Page 03\n Grandchild Page\n Great Grandchild Page\n Child Page 04\n Child Page 05\n</code></pre>\n</blockquote>\n\n<p><strong>Example Output (current page: Great Grandchild Page)</strong></p>\n\n<pre><code><ul class=\"page-menu ancestor-tree\">\n <li class=\"page_item page-item-1088 page_item_has_children current_page_ancestor\">\n <a href=\"http://example.com/parent-page/\">Parent Page</a>\n <ul class=\"children\">\n <li class=\"page_item page-item-1090\">\n <a href=\"http://example.com/parent-page/child-page-01/\">Child Page 01</a>\n </li>\n <li class=\"page_item page-item-1092\">\n <a href=\"http://example.com/parent-page/child-page-02/\">Child Page 02</a>\n </li>\n <li class=\"page_item page-item-1094 page_item_has_children current_page_ancestor\">\n <a href=\"http://example.com/parent-page/child-page-03/\">Child Page 03</a>\n <ul class=\"children\">\n <li class=\"page_item page-item-1102 page_item_has_children current_page_ancestor current_page_parent\">\n <a href=\"http://example.com/parent-page/child-page-03/grandchild-page/\">Grandchild Page</a>\n <ul class=\"children\">\n <li class=\"page_item page-item-3066 current_page_item\">\n <a href=\"http://example.com/parent-page/child-page-03/grandchild-page/great-grandchild-page/\">Great Grandchild Page</a>\n </li>\n </ul>\n </li>\n </ul>\n </li>\n <li class=\"page_item page-item-1096\">\n <a href=\"http://example.com/parent-page/child-page-04/\">Child Page 04</a>\n </li>\n <li class=\"page_item page-item-1098\">\n <a href=\"http://example.com/parent-page/child-page-05/\">Child Page 05</a>\n </li>\n </ul>\n </li>\n</ul>\n</code></pre>\n"
},
{
"answer_id": 299695,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>correct code:</p>\n\n<pre><code>if( empty($wp_query->post->post_parent) ) {\n $parent = $wp_query->post->ID;\n} else {\n $ancestors=get_post_ancestors($wp_query->post->ID);\n $parent = $ancestors[count($ancestors)-1];\n}\n</code></pre>\n\n<p>it access the top-most page of the current page.</p>\n"
}
]
| 2018/03/28 | [
"https://wordpress.stackexchange.com/questions/299138",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3206/"
]
| I used [this answer's](https://wordpress.stackexchange.com/a/537/3206) code to generate a widget that displays all subpages of the parent's page:
```
if (is_page()) {
global $wp_query;
if( empty($wp_query->post->post_parent) ) {
$parent = $wp_query->post->ID;
} else {
$parent = $wp_query->post->post_parent;
}
if(wp_list_pages("title_li=&child_of=$parent&echo=0" )) {
wp_list_pages("title_li=&child_of=$parent&echo=1" );
}
}
```
I now realise this does not cope if I am in a grandchild page, in that the uncles and aunties are not displayed, only the parents.
I don't understand how I can adapt this code to display more than 2 levels of menu tree.
Help appreciated. | Here is a function that will output the top level parent along with all of the children of the current page. Helpful menu classes are added to the output. E.g. `page_item_has_children`, `current_page_item`, `current_page_ancestor`, etc.
This solution is [based on one of the examples](https://developer.wordpress.org/reference/functions/wp_list_pages/#comment-391) in the documentation for [`wp_list_pages()`](https://developer.wordpress.org/reference/functions/wp_list_pages) and [this answer](https://wordpress.stackexchange.com/a/99900/2807) here on WPSE, which references the same example.
```
/**
* Use wp_list_pages() to display parent and all child pages of current page.
*/
function wpse_get_ancestor_tree() {
// Bail if this is not a page.
if ( ! is_page() ) {
return false;
}
// Get the current post.
$post = get_post();
/**
* Get array of post ancestor IDs.
* Note: The direct parent is returned as the first value in the array.
* The highest level ancestor is returned as the last value in the array.
* See https://codex.wordpress.org/Function_Reference/get_post_ancestors
*/
$ancestors = get_post_ancestors( $post->ID );
// If there are ancestors, get the top level parent.
// Otherwise use the current post's ID.
$parent = ( ! empty( $ancestors ) ) ? array_pop( $ancestors ) : $post->ID;
// Get all pages that are a child of $parent.
$pages = get_pages( [
'child_of' => $parent,
] );
// Bail if there are no results.
if ( ! $pages ) {
return false;
}
// Store array of page IDs to include latere on.
$page_ids = array();
foreach ( $pages as $page ) {
$page_ids[] = $page->ID;
}
// Add parent page to beginning of $page_ids array.
array_unshift( $page_ids, $parent );
// Get the output and return results if they exist.
$output = wp_list_pages( [
'include' => $page_ids,
'title_li' => false,
'echo' => false,
] );
if ( ! $output ) {
return false;
} else {
return '<ul class="page-menu ancestor-tree">' . PHP_EOL .
$output . PHP_EOL .
'</ul>' . PHP_EOL;
}
}
```
**Usage:**
```
echo wpse_get_ancestor_tree();
```
**Example Page Structure:**
>
>
> ```
> Parent Page
> Child Page 01
> Child Page 02
> Child Page 03
> Grandchild Page
> Great Grandchild Page
> Child Page 04
> Child Page 05
>
> ```
>
>
**Example Output (current page: Great Grandchild Page)**
```
<ul class="page-menu ancestor-tree">
<li class="page_item page-item-1088 page_item_has_children current_page_ancestor">
<a href="http://example.com/parent-page/">Parent Page</a>
<ul class="children">
<li class="page_item page-item-1090">
<a href="http://example.com/parent-page/child-page-01/">Child Page 01</a>
</li>
<li class="page_item page-item-1092">
<a href="http://example.com/parent-page/child-page-02/">Child Page 02</a>
</li>
<li class="page_item page-item-1094 page_item_has_children current_page_ancestor">
<a href="http://example.com/parent-page/child-page-03/">Child Page 03</a>
<ul class="children">
<li class="page_item page-item-1102 page_item_has_children current_page_ancestor current_page_parent">
<a href="http://example.com/parent-page/child-page-03/grandchild-page/">Grandchild Page</a>
<ul class="children">
<li class="page_item page-item-3066 current_page_item">
<a href="http://example.com/parent-page/child-page-03/grandchild-page/great-grandchild-page/">Great Grandchild Page</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="page_item page-item-1096">
<a href="http://example.com/parent-page/child-page-04/">Child Page 04</a>
</li>
<li class="page_item page-item-1098">
<a href="http://example.com/parent-page/child-page-05/">Child Page 05</a>
</li>
</ul>
</li>
</ul>
``` |
299,185 | <p>How can i anonymize any comment after a certain time?
Is there a way to do this?
It's for data protection.</p>
| [
{
"answer_id": 299192,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>I don't have a ready to use solution. Howeder I think is not to heavy to build a custom plugin, that do that.</p>\n\n<ol>\n<li>Update the comment data, use <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_comment\" rel=\"nofollow noreferrer\"><code>wp_update_comment()</code></a>.</li>\n<li>For anonymize the IP you can use <a href=\"https://core.trac.wordpress.org/ticket/43545\" rel=\"nofollow noreferrer\"><code>wp_privacy_anonymize_ip()</code></a> <em>(currently not in core, open as ticket)</em>.</li>\n<li>Use the wp cron to run this after 6 months and build a comparison with the comment date to anonymize the data of the comment.</li>\n</ol>\n\n<p>Alternative to the wp function to anonymize the IP helps this small function, only an small idea.</p>\n\n<pre><code>function fb_cut_ip( $ip, $cut_end = true )\n{\n return str_replace(\n ( $cut_end ? strrchr( $ip, ':' ) : strstr( $ip, ':' ) ),\n '',\n $ip\n );\n}\n</code></pre>\n"
},
{
"answer_id": 302048,
"author": "Aleshanee",
"author_id": 111201,
"author_profile": "https://wordpress.stackexchange.com/users/111201",
"pm_score": 1,
"selected": false,
"text": "<p>Thank you all for your help.</p>\n\n<p>Here is my final solution:\nIt's a PHP-snippet that i paste into a wp cron job plugin.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wp_privacy_anonymize_comments' );\nfunction wp_privacy_anonymize_comments() {\n $expiry_date = date(\"Y-m-d\", strtotime(\"-1 years\"));\n $args = array(\n // args here\n );\n\n// The Query\n$comments_query = new WP_Comment_Query;\n$meta_values = $comments_query->query( $args );\n\nforeach($meta_values as $meta_value) :\n $current_comment_ID = $meta_value->comment_ID;\n $current_comment_date = $meta_value->comment_date;\n\n if ($current_comment_date < $expiry_date) {\n //Override Userdata #anonymer-Bär\n $update_comment = array(\n 'comment_ID' => $current_comment_ID,\n 'comment_author'=> 'Anonym ' . $current_comment_ID,\n 'comment_author_email' => '[email protected]',\n 'comment_author_url' => ''\n );\n wp_update_comment($update_comment);\n }\nendforeach;\n}\n</code></pre>\n\n<p>Thank you all :)\nKind regards, Kathi</p>\n"
}
]
| 2018/03/28 | [
"https://wordpress.stackexchange.com/questions/299185",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111201/"
]
| How can i anonymize any comment after a certain time?
Is there a way to do this?
It's for data protection. | I don't have a ready to use solution. Howeder I think is not to heavy to build a custom plugin, that do that.
1. Update the comment data, use [`wp_update_comment()`](https://codex.wordpress.org/Function_Reference/wp_update_comment).
2. For anonymize the IP you can use [`wp_privacy_anonymize_ip()`](https://core.trac.wordpress.org/ticket/43545) *(currently not in core, open as ticket)*.
3. Use the wp cron to run this after 6 months and build a comparison with the comment date to anonymize the data of the comment.
Alternative to the wp function to anonymize the IP helps this small function, only an small idea.
```
function fb_cut_ip( $ip, $cut_end = true )
{
return str_replace(
( $cut_end ? strrchr( $ip, ':' ) : strstr( $ip, ':' ) ),
'',
$ip
);
}
``` |
299,240 | <p>my site when it loads in a responsive mode the sidebar is below almost everything else is there any way I can move it up a bit, any css i can put the theme is nanomag</p>
| [
{
"answer_id": 299192,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>I don't have a ready to use solution. Howeder I think is not to heavy to build a custom plugin, that do that.</p>\n\n<ol>\n<li>Update the comment data, use <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_comment\" rel=\"nofollow noreferrer\"><code>wp_update_comment()</code></a>.</li>\n<li>For anonymize the IP you can use <a href=\"https://core.trac.wordpress.org/ticket/43545\" rel=\"nofollow noreferrer\"><code>wp_privacy_anonymize_ip()</code></a> <em>(currently not in core, open as ticket)</em>.</li>\n<li>Use the wp cron to run this after 6 months and build a comparison with the comment date to anonymize the data of the comment.</li>\n</ol>\n\n<p>Alternative to the wp function to anonymize the IP helps this small function, only an small idea.</p>\n\n<pre><code>function fb_cut_ip( $ip, $cut_end = true )\n{\n return str_replace(\n ( $cut_end ? strrchr( $ip, ':' ) : strstr( $ip, ':' ) ),\n '',\n $ip\n );\n}\n</code></pre>\n"
},
{
"answer_id": 302048,
"author": "Aleshanee",
"author_id": 111201,
"author_profile": "https://wordpress.stackexchange.com/users/111201",
"pm_score": 1,
"selected": false,
"text": "<p>Thank you all for your help.</p>\n\n<p>Here is my final solution:\nIt's a PHP-snippet that i paste into a wp cron job plugin.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wp_privacy_anonymize_comments' );\nfunction wp_privacy_anonymize_comments() {\n $expiry_date = date(\"Y-m-d\", strtotime(\"-1 years\"));\n $args = array(\n // args here\n );\n\n// The Query\n$comments_query = new WP_Comment_Query;\n$meta_values = $comments_query->query( $args );\n\nforeach($meta_values as $meta_value) :\n $current_comment_ID = $meta_value->comment_ID;\n $current_comment_date = $meta_value->comment_date;\n\n if ($current_comment_date < $expiry_date) {\n //Override Userdata #anonymer-Bär\n $update_comment = array(\n 'comment_ID' => $current_comment_ID,\n 'comment_author'=> 'Anonym ' . $current_comment_ID,\n 'comment_author_email' => '[email protected]',\n 'comment_author_url' => ''\n );\n wp_update_comment($update_comment);\n }\nendforeach;\n}\n</code></pre>\n\n<p>Thank you all :)\nKind regards, Kathi</p>\n"
}
]
| 2018/03/29 | [
"https://wordpress.stackexchange.com/questions/299240",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129261/"
]
| my site when it loads in a responsive mode the sidebar is below almost everything else is there any way I can move it up a bit, any css i can put the theme is nanomag | I don't have a ready to use solution. Howeder I think is not to heavy to build a custom plugin, that do that.
1. Update the comment data, use [`wp_update_comment()`](https://codex.wordpress.org/Function_Reference/wp_update_comment).
2. For anonymize the IP you can use [`wp_privacy_anonymize_ip()`](https://core.trac.wordpress.org/ticket/43545) *(currently not in core, open as ticket)*.
3. Use the wp cron to run this after 6 months and build a comparison with the comment date to anonymize the data of the comment.
Alternative to the wp function to anonymize the IP helps this small function, only an small idea.
```
function fb_cut_ip( $ip, $cut_end = true )
{
return str_replace(
( $cut_end ? strrchr( $ip, ':' ) : strstr( $ip, ':' ) ),
'',
$ip
);
}
``` |
299,249 | <p>Is it possible to append <code>?ref=myref</code> to all external URLs?</p>
<p>If so I'm guessing I will also need to check if a <code>?</code> already exists and use <code>&</code> if so.</p>
<p>I'm a WP noob just coming from Joomla, any tips / help would be a very nice warm welcome. :) </p>
<p>Not sure if it can be done on page or <code>.htaccess</code>. </p>
| [
{
"answer_id": 299251,
"author": "Ben",
"author_id": 140703,
"author_profile": "https://wordpress.stackexchange.com/users/140703",
"pm_score": 0,
"selected": false,
"text": "<p>You can check if the request headers contain <code>http referer</code>, and then check if the <code>http referer</code> header is from external site, then use <code>.htaccess</code> to rewrite the url internally. But it is not a guarantee way to detect all the external urls as the <code>http referer</code> can be dropped for some reason.</p>\n\n<p><strong>.htaccess</strong></p>\n\n<pre><code>RewriteCond %{HTTP_REFERER} !^$\nRewriteCond %{HTTP_REFERER} !www.example.com [NC]\nRewriteRule ^(.+)$ $1?ref=myref [QSA,L]\n</code></pre>\n\n<p>Line 1 checks if the request header <code>http referer</code> is not empty. Then Line 2 checks if the <code>http referer</code> is from external domain. Line 3 rewrite all the url and append query string <code>ref=myref</code> internally if first two conditions satified.</p>\n"
},
{
"answer_id": 334879,
"author": "ludovico",
"author_id": 165369,
"author_profile": "https://wordpress.stackexchange.com/users/165369",
"pm_score": 1,
"selected": false,
"text": "<h1>Inbound vs Outbound links:</h1>\n\n<p>I guess it'll be helpful to clarify these concepts:</p>\n\n<p><strong>Inbound links</strong> = links from another website to your own website.</p>\n\n<p><strong>Outbound links</strong> = links from your website to another website.</p>\n\n<p>An <a href=\"https://moz.com/learn/seo/external-link\" rel=\"nofollow noreferrer\">external link</a> would be any link that points to any domain other than the domain the link exists on.</p>\n\n<p>From your comments, I guess what you're trying to achieve is to modify all your outbound links. </p>\n\n<p>As @MrWhite suggests, <strong>you will not be able to change your outbound links by modifying your .htaccess file</strong> (it would be helpful, though, if you had to modify your inbound links).</p>\n\n<p>Now, a couple of solutions that can work for you:</p>\n\n<h1>Modify your links on the browser (using JavaScript)</h1>\n\n<p>This should work (as long as JavaScript is enabled in the user's browser):</p>\n\n<pre><code>document.addEventListener( \"DOMContentLoaded\", modify_outbound_links);\n\nfunction modify_outbound_links(){\n anchors = document.getElementsByTagName('a');\n for (let i = 0; i < anchors.length; i++) {\n let p = anchors[i].href;\n if (p.indexOf('yourdomain.com') === -1) {\n anchors[i].href = p + (p.indexOf('?') != -1 ? \"&\" : \"?\") + 'ref=myref';\n }\n }\n}\n</code></pre>\n\n<p>The recommended (and cleanest) option to add some JavaScript to WordPress is using <a href=\"https://premium.wpmudev.org/blog/adding-scripts-and-styles-wordpress-enqueueing/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a>. If you need an easier option, it should work if you just wrap this snippet inside <code><script> ... </script></code> and put it inside your footer.php.</p>\n\n<h1>Modify your links before they're served to the user (using WP filters)</h1>\n\n<p>You can use <a href=\"https://www.wpbeginner.com/glossary/filter/\" rel=\"nofollow noreferrer\">WordPress filters</a> (functions that are called when a specific event happens).</p>\n\n<p>In your case, you can use <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"nofollow noreferrer\"><em>'the_content'</em></a> filter, which can be used to modify the content of the post <em>after it is retrieved from the database and before it is printed to the screen</em>.</p>\n\n<p>You'd need to add this to your theme's <em>functions.php</em> file:</p>\n\n<pre><code>add_filter( 'the_content', 'myprefix_modify_outbound_links' ); \n\nfunction myprefix_modify_outbound_links( $content ) {\n\n /* here you can search for all external links in $content and modify them as you wish */\n\n return $content;\n}\n</code></pre>\n\n<p>Note, this will filter all links in your WordPress posts. You might want to search through your theme's code, just in case there are other external links.</p>\n"
}
]
| 2018/03/29 | [
"https://wordpress.stackexchange.com/questions/299249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140699/"
]
| Is it possible to append `?ref=myref` to all external URLs?
If so I'm guessing I will also need to check if a `?` already exists and use `&` if so.
I'm a WP noob just coming from Joomla, any tips / help would be a very nice warm welcome. :)
Not sure if it can be done on page or `.htaccess`. | Inbound vs Outbound links:
==========================
I guess it'll be helpful to clarify these concepts:
**Inbound links** = links from another website to your own website.
**Outbound links** = links from your website to another website.
An [external link](https://moz.com/learn/seo/external-link) would be any link that points to any domain other than the domain the link exists on.
From your comments, I guess what you're trying to achieve is to modify all your outbound links.
As @MrWhite suggests, **you will not be able to change your outbound links by modifying your .htaccess file** (it would be helpful, though, if you had to modify your inbound links).
Now, a couple of solutions that can work for you:
Modify your links on the browser (using JavaScript)
===================================================
This should work (as long as JavaScript is enabled in the user's browser):
```
document.addEventListener( "DOMContentLoaded", modify_outbound_links);
function modify_outbound_links(){
anchors = document.getElementsByTagName('a');
for (let i = 0; i < anchors.length; i++) {
let p = anchors[i].href;
if (p.indexOf('yourdomain.com') === -1) {
anchors[i].href = p + (p.indexOf('?') != -1 ? "&" : "?") + 'ref=myref';
}
}
}
```
The recommended (and cleanest) option to add some JavaScript to WordPress is using [wp\_enqueue\_script](https://premium.wpmudev.org/blog/adding-scripts-and-styles-wordpress-enqueueing/). If you need an easier option, it should work if you just wrap this snippet inside `<script> ... </script>` and put it inside your footer.php.
Modify your links before they're served to the user (using WP filters)
======================================================================
You can use [WordPress filters](https://www.wpbeginner.com/glossary/filter/) (functions that are called when a specific event happens).
In your case, you can use [*'the\_content'*](https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content) filter, which can be used to modify the content of the post *after it is retrieved from the database and before it is printed to the screen*.
You'd need to add this to your theme's *functions.php* file:
```
add_filter( 'the_content', 'myprefix_modify_outbound_links' );
function myprefix_modify_outbound_links( $content ) {
/* here you can search for all external links in $content and modify them as you wish */
return $content;
}
```
Note, this will filter all links in your WordPress posts. You might want to search through your theme's code, just in case there are other external links. |
299,267 | <p>I am working in the theme called Understrap. I work in the child-theme. The theme </p>
<p>allready has a style.css and functions.php. I want to create my own style.css file </p>
<p>and overwrite that style.css they have included. Any suggestions?</p>
<p>Thank you very much </p>
| [
{
"answer_id": 299278,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": -1,
"selected": false,
"text": "<p>You need to add following code to your child-theme's functions.php</p>\n\n<pre><code> /**\n * Proper way to enqueue scripts and styles\n */\n function wpdocs_theme_name_scripts() {\n wp_enqueue_style( 'style-name', get_stylesheet_uri() );\n wp_enqueue_style( 'custom-css', get_stylesheet_uri() . '/css/custom.css', array(), '1.0.0' );\n wp_enqueue_script( 'custom-js', get_stylesheet_uri() . '/js/custom.js', array(), '1.0.0', true );\n }\n add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n"
},
{
"answer_id": 299293,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at the official docs:\n<a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Child_Themes</a>\n<a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/advanced-topics/child-themes/</a></p>\n\n<p>Make sure you are within your child theme <code>functions.php</code> and use this code to make sure the function is firing. It will kill the page if it is working correctly. </p>\n\n<pre><code> function wpdocs_theme_name_scripts() {\n wp_die('Yep! This is working');\n }\n add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n"
}
]
| 2018/03/29 | [
"https://wordpress.stackexchange.com/questions/299267",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140728/"
]
| I am working in the theme called Understrap. I work in the child-theme. The theme
allready has a style.css and functions.php. I want to create my own style.css file
and overwrite that style.css they have included. Any suggestions?
Thank you very much | Take a look at the official docs:
<https://codex.wordpress.org/Child_Themes>
<https://developer.wordpress.org/themes/advanced-topics/child-themes/>
Make sure you are within your child theme `functions.php` and use this code to make sure the function is firing. It will kill the page if it is working correctly.
```
function wpdocs_theme_name_scripts() {
wp_die('Yep! This is working');
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
``` |
299,324 | <p>I've created an rewrite endpoint with the <a href="https://developer.wordpress.org/reference/functions/add_rewrite_endpoint/" rel="nofollow noreferrer">add_rewrite_endpoint</a> function … here is the whole contruct:</p>
<pre><code>// Register to query vars
add_filter( 'query_vars', 'add_query_vars');
function add_query_vars( $vars ) {
$vars[] = 'account';
return $vars;
}
// Add rewrite endpoint
add_action( 'init', 'account_page_endpoint' );
function account_page_endpoint() {
add_rewrite_endpoint( 'account', EP_ROOT );
}
// Account template
add_action( 'template_include', 'account_page_template' );
function account_page_template( $template ) {
if( get_query_var( 'account', false ) !== false ) {
return locate_template( array( 'account.php' ) );
}
return $template;
}
</code></pre>
<p>This works great so far when i enter a url like example.com/account/username ... but the links in the site are still like example.com?account=username. </p>
<p>How do i redirect from the parameter version to rewritten version? Is it necessary to add a additional rewrite rule or is there any function that these links have to run through?</p>
<p>The account links on the site itself are created by this function:</p>
<pre><code>function account_url( $user_id ) {
$user = get_userdata( $user_id );
return add_query_arg( 'account', strtolower( $user->user_login ), get_home_url() );
}
</code></pre>
| [
{
"answer_id": 299333,
"author": "Friss",
"author_id": 62392,
"author_profile": "https://wordpress.stackexchange.com/users/62392",
"pm_score": 3,
"selected": false,
"text": "<p>EDIT 2</p>\n\n<p>To use pretty permalinks, such as example.com/account/john\nyou need to activate in your admin area, in the permalink settings,\nand activate it on you server.\nYou told us in comments that you used nginx, I know better apache so here is a tutorial which could help you.</p>\n\n<p><a href=\"https://www.cyberciti.biz/faq/how-to-configure-nginx-for-wordpress-permalinks/\" rel=\"noreferrer\">https://www.cyberciti.biz/faq/how-to-configure-nginx-for-wordpress-permalinks/</a></p>\n\n<p><strong>EDIT</strong></p>\n\n<p>I went too fast, forget about my suggestion of add_rewrite_rule,\nI think that with using add_rewrite_endpoint you have to use the \"template_redirect\" hook instead of the \"template_include\" one.</p>\n\n<p><strong>END EDIT</strong></p>\n\n<p>According to the code you show, I would add this to your account_page_endpoint function</p>\n\n<pre><code>add_rewrite_rule('^account/([a-z0-9]+)/?', 'index.php?account=$matches[1]', 'top');\n</code></pre>\n\n<p>It does not modify the .htaccess file, however you can refresh the rules.</p>\n\n<p>You may need to refresh the rules after this modification.</p>\n\n<p>Two possibilities:</p>\n\n<p>-either you add, right after the line of code above, the call to the flush rewrite function like this:</p>\n\n<pre><code>flush_rewrite_rules();\n</code></pre>\n\n<p>-or you can go in you admin area, in the permalink settings and re save your current settings.</p>\n"
},
{
"answer_id": 299406,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>Rewrite rules only handle incoming requests, they aren't involved in link generation.</p>\n\n<p>The primary WordPress rewrite system is parsed internally with PHP, you won't see any changes to an <code>.htaccess</code> file when you add an endpoint. The basic .htaccess rules essentially say \"If this isn't a request for a physical file or directory on the server, then hand the request over to WordPress\".</p>\n\n<p>Your <code>account_url</code> function has to handle both \"ugly\" and \"pretty\" cases when it outputs the account URLs. We can look at the built in <a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"nofollow noreferrer\"><code>get_permalink</code> function</a> to see how WordPress handles this, here's an abbreviated version:</p>\n\n<pre><code>$permalink = get_option('permalink_structure');\nif ( '' != $permalink ) {\n // output a pretty permalink\n} else {\n // output an ugly permalink\n}\n</code></pre>\n\n<p>The <code>permalink_structure</code> option holds the chosen pattern if pretty permalinks are enabled, we know pretty permalinks are disabled if it's empty.</p>\n"
}
]
| 2018/03/29 | [
"https://wordpress.stackexchange.com/questions/299324",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52227/"
]
| I've created an rewrite endpoint with the [add\_rewrite\_endpoint](https://developer.wordpress.org/reference/functions/add_rewrite_endpoint/) function … here is the whole contruct:
```
// Register to query vars
add_filter( 'query_vars', 'add_query_vars');
function add_query_vars( $vars ) {
$vars[] = 'account';
return $vars;
}
// Add rewrite endpoint
add_action( 'init', 'account_page_endpoint' );
function account_page_endpoint() {
add_rewrite_endpoint( 'account', EP_ROOT );
}
// Account template
add_action( 'template_include', 'account_page_template' );
function account_page_template( $template ) {
if( get_query_var( 'account', false ) !== false ) {
return locate_template( array( 'account.php' ) );
}
return $template;
}
```
This works great so far when i enter a url like example.com/account/username ... but the links in the site are still like example.com?account=username.
How do i redirect from the parameter version to rewritten version? Is it necessary to add a additional rewrite rule or is there any function that these links have to run through?
The account links on the site itself are created by this function:
```
function account_url( $user_id ) {
$user = get_userdata( $user_id );
return add_query_arg( 'account', strtolower( $user->user_login ), get_home_url() );
}
``` | Rewrite rules only handle incoming requests, they aren't involved in link generation.
The primary WordPress rewrite system is parsed internally with PHP, you won't see any changes to an `.htaccess` file when you add an endpoint. The basic .htaccess rules essentially say "If this isn't a request for a physical file or directory on the server, then hand the request over to WordPress".
Your `account_url` function has to handle both "ugly" and "pretty" cases when it outputs the account URLs. We can look at the built in [`get_permalink` function](https://developer.wordpress.org/reference/functions/get_permalink/) to see how WordPress handles this, here's an abbreviated version:
```
$permalink = get_option('permalink_structure');
if ( '' != $permalink ) {
// output a pretty permalink
} else {
// output an ugly permalink
}
```
The `permalink_structure` option holds the chosen pattern if pretty permalinks are enabled, we know pretty permalinks are disabled if it's empty. |
299,346 | <p>I'm looking to mass remove or clear the default attribute for variable products in Woocommerce. </p>
<p><a href="https://i.stack.imgur.com/BdWNd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BdWNd.png" alt="enter image description here"></a></p>
<p>Is there an easy way to mass clear this value? If not, would you be able to direct me on where I can find this value in phpMyAdmin?</p>
| [
{
"answer_id": 299352,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>you can modify the default attribute with the following code. this code retrieve the complet list of products then it can use a big amount of ressources</p>\n\n<pre><code>$products = wc_get_products([\n \"nopaging\" => TRUE, // retrieve all products\n]);\n\n\nforeach ($products as $p) { \n\n $default_attributes = $p->get_default_attributes();\n\n if ( (!empty($default_attributes))\n && FALSE // other condition to select of which product the default attributes is reset\n ) {\n\n $p->set_default_attributes(\"\");\n\n }\n\n\n}\n</code></pre>\n"
},
{
"answer_id": 319001,
"author": "Yashar",
"author_id": 146615,
"author_profile": "https://wordpress.stackexchange.com/users/146615",
"pm_score": 2,
"selected": false,
"text": "<p>Default attributes of WooCommerce variable products are stored as post meta in the database.\nYou can find them in the <code>wp_postmeta</code> table, where the <code>post_id</code> column is the post ID of the parent product (Variable product), and the <code>meta_key</code> column is <code>_default_attributes</code>.</p>\n\n<p>You can clear and remove default attributes of all products by replacing all non-empty arrays.</p>\n\n<p>To do so, open phpMyAdmin and select the database of your WordPress installation from the left panel and click on SQL tab. Then write the below SQL commands and press Go:</p>\n\n<blockquote>\n <p>Don't forget to backing up your database before executing any command\n on phpMyAdmin</p>\n</blockquote>\n\n<pre><code>UPDATE `wp_postmeta` SET `meta_value`= 'a:0:{}' WHERE meta_key = '_default_attributes'\n</code></pre>\n"
}
]
| 2018/03/30 | [
"https://wordpress.stackexchange.com/questions/299346",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118984/"
]
| I'm looking to mass remove or clear the default attribute for variable products in Woocommerce.
[](https://i.stack.imgur.com/BdWNd.png)
Is there an easy way to mass clear this value? If not, would you be able to direct me on where I can find this value in phpMyAdmin? | Default attributes of WooCommerce variable products are stored as post meta in the database.
You can find them in the `wp_postmeta` table, where the `post_id` column is the post ID of the parent product (Variable product), and the `meta_key` column is `_default_attributes`.
You can clear and remove default attributes of all products by replacing all non-empty arrays.
To do so, open phpMyAdmin and select the database of your WordPress installation from the left panel and click on SQL tab. Then write the below SQL commands and press Go:
>
> Don't forget to backing up your database before executing any command
> on phpMyAdmin
>
>
>
```
UPDATE `wp_postmeta` SET `meta_value`= 'a:0:{}' WHERE meta_key = '_default_attributes'
``` |
299,361 | <p>For example I have page on which I have only custom post types (books or music or testimonials) and don't have standard WordPress posts.</p>
<p>Can I use home.php to display my custom post types which are on pages, books or music or testimonials, and single-posttype.php for single post of each post type? Or do I need to create custom-template for page and display custom post types there.</p>
| [
{
"answer_id": 299370,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>The simple answer is “yes, you can”, but I’m pretty sure it won’t satisfy you ;)</p>\n\n<p>So... How can you achieve this and show only custom posts on home.php? All you need is to use pre_get_posts hook like so:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'add_custom_post_types_to_home_query' );\n\nfunction add_custom_post_types_to_home_query( $query ) {\nif ( is_home() && $query->is_main_query() )\n $query->set( 'post_type', array( 'book', 'movie' ) );\nreturn $query;\n}\n</code></pre>\n\n<p>The code above will change the main query so it shows only books and movies.</p>\n"
},
{
"answer_id": 299373,
"author": "sagar",
"author_id": 97598,
"author_profile": "https://wordpress.stackexchange.com/users/97598",
"pm_score": 1,
"selected": false,
"text": "<p>You do have different options for that.\nIf you look the template hierarchy of the WordPress you can find that.</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#single-page\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/#single-page</a></p>\n\n<p>By default, WordPress sets your site’s home page to display your latest blog posts. This page is called the blog posts index. You can also set your blog posts to display on a separate static page. The template file home.php is used to render the blog posts index, whether it is being used as the front page or on separate static page. If home.php does not exist, WordPress will use index.php.</p>\n\n<p>You can use a custom template function that will suit best to you \n<a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/page-template-files/</a></p>\n\n<p>Then you can do pull or retrieve any content in that particular template</p>\n"
}
]
| 2018/03/30 | [
"https://wordpress.stackexchange.com/questions/299361",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135678/"
]
| For example I have page on which I have only custom post types (books or music or testimonials) and don't have standard WordPress posts.
Can I use home.php to display my custom post types which are on pages, books or music or testimonials, and single-posttype.php for single post of each post type? Or do I need to create custom-template for page and display custom post types there. | The simple answer is “yes, you can”, but I’m pretty sure it won’t satisfy you ;)
So... How can you achieve this and show only custom posts on home.php? All you need is to use pre\_get\_posts hook like so:
```
add_action( 'pre_get_posts', 'add_custom_post_types_to_home_query' );
function add_custom_post_types_to_home_query( $query ) {
if ( is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'book', 'movie' ) );
return $query;
}
```
The code above will change the main query so it shows only books and movies. |
299,367 | <p>I want to resize a particular image on the fly with the_post_thumbnail() which I have done like so:</p>
<pre><code><?php the_post_thumbnail( array (475, 317 ) ); ?>
</code></pre>
<p>This works in resizing the image to the specified size but I also want to add a class to this. If I try add a class then the size dimensions are still correct but it doesn't apply the class?</p>
<pre><code><?php the_post_thumbnail( array (475, 317, 'class' => 'border--round' ) ); ?>
</code></pre>
| [
{
"answer_id": 299372,
"author": "Simo Patrek",
"author_id": 133002,
"author_profile": "https://wordpress.stackexchange.com/users/133002",
"pm_score": 3,
"selected": true,
"text": "<p>Try To Use it Like This :</p>\n\n<pre><code><?php the_post_thumbnail( array (475, 317), [ 'class' => 'border--round' ] ); ?>\n</code></pre>\n"
},
{
"answer_id": 299374,
"author": "Sarequl Basar",
"author_id": 125457,
"author_profile": "https://wordpress.stackexchange.com/users/125457",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to customize \"size, class etc\" then you can use this function.</p>\n\n<pre>the_post_thumbnail_url(); </pre> \n\n<p>ex: if you want to use img tag then the code will be like this.</p>\n\n<pre>\n<img class=\"yourclass\" src=\"<?php the_post_thumbnail_url( array(475, 317) );?>\" alt=\"\"/>\n</pre>\n"
}
]
| 2018/03/30 | [
"https://wordpress.stackexchange.com/questions/299367",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140276/"
]
| I want to resize a particular image on the fly with the\_post\_thumbnail() which I have done like so:
```
<?php the_post_thumbnail( array (475, 317 ) ); ?>
```
This works in resizing the image to the specified size but I also want to add a class to this. If I try add a class then the size dimensions are still correct but it doesn't apply the class?
```
<?php the_post_thumbnail( array (475, 317, 'class' => 'border--round' ) ); ?>
``` | Try To Use it Like This :
```
<?php the_post_thumbnail( array (475, 317), [ 'class' => 'border--round' ] ); ?>
``` |
299,375 | <p>I have a class called "switchable" which basically switches the text and image from left to right, to right to left. I want this to happen for every second record. So, the first one on the left, and the second on the right etc. I just don't know how to achieve this with the below code. Every second record should have instead of just , </p>
<pre><code> <?php $the_query = new WP_Query( array ( 'post_type' => 'crew_members', 'order_by' => 'menu_order', 'order' => 'ASC' ) ); ?>
<?php if( $the_query->have_posts() ): while ( $the_query->have_posts() ) : $the_query->the_post() ; ?>
<section>
<div class="container">
<div class="row justify-content-between">
<div class="col-md-6">
<div> <?php the_content(); ?> </div>
</div>
<div class="col-md-6">
<div class="boxed boxed--lg boxed--border bg--secondary"> <?php the_post_thumbnail( array (475, 317), [ 'class' => 'border--round' ] ); ?>
<h5><?php the_title(); ?></h5>
<p> <?php the_field( 'crew_member_excerpt' ); ?> </p>
</div>
</div>
</div>
</div>
</section>
<?php endwhile; endif; ?>
<?php wp_reset_postdata(); ?>
</code></pre>
<p><strong>EDIT:</strong></p>
<p>After swissspidy's answer, I tried this:</p>
<pre><code><?php
if ( 1 === $the_query->current_post % 2 ) {
$class = 'class="switchable"';
}
?>
<section <?php echo $class; ?>>
<div class="container">
<div class="row justify-content-between">
<div class="col-md-6">
<div> <?php the_content(); ?> </div>
</div>
<div class="col-md-6">
<div class="boxed boxed--lg boxed--border bg--secondary"> <img src="<?php the_post_thumbnail_url(); ?>" class="border--round">
<?php // another way: <?php the_post_thumbnail( array (475, 317), [ 'class' => 'border--round' ] ); ?>
<h5><?php the_title(); ?></h5>
<p> <?php the_field( 'crew_member_excerpt' ); ?> </p>
</div>
</div>
</div>
</div>
</section>
</code></pre>
| [
{
"answer_id": 299377,
"author": "swissspidy",
"author_id": 12404,
"author_profile": "https://wordpress.stackexchange.com/users/12404",
"pm_score": 2,
"selected": true,
"text": "<p>Inside the loop you can use <code>$the_query->current_post</code> to get the index of the post currently being displayed. You can then check if the index is an odd or even number and conditionally add the class. Example:</p>\n\n<pre><code>if ( 1 === $the_query->current_post % 2 ) {\n echo 'class=\"switchable\"';\n}\n</code></pre>\n"
},
{
"answer_id": 299418,
"author": "GodWords",
"author_id": 77285,
"author_profile": "https://wordpress.stackexchange.com/users/77285",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming the left/right elements are siblings, have you considered a CSS-only solution? Instead of adding a class in the output, you could just style the output without a class.</p>\n\n<pre><code><div id=\"your-content\">\n <p>Left</p>\n <p>Right</p>\n <p>Left</p>\n <p>Right</p>\n</div>\n\n#your-content p {\n [styles for making all of them left]\n}\n\n#your-content p:nth-child(even) {\n [styles for making the even-numbered ones right]\n}\n</code></pre>\n"
}
]
| 2018/03/30 | [
"https://wordpress.stackexchange.com/questions/299375",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140276/"
]
| I have a class called "switchable" which basically switches the text and image from left to right, to right to left. I want this to happen for every second record. So, the first one on the left, and the second on the right etc. I just don't know how to achieve this with the below code. Every second record should have instead of just ,
```
<?php $the_query = new WP_Query( array ( 'post_type' => 'crew_members', 'order_by' => 'menu_order', 'order' => 'ASC' ) ); ?>
<?php if( $the_query->have_posts() ): while ( $the_query->have_posts() ) : $the_query->the_post() ; ?>
<section>
<div class="container">
<div class="row justify-content-between">
<div class="col-md-6">
<div> <?php the_content(); ?> </div>
</div>
<div class="col-md-6">
<div class="boxed boxed--lg boxed--border bg--secondary"> <?php the_post_thumbnail( array (475, 317), [ 'class' => 'border--round' ] ); ?>
<h5><?php the_title(); ?></h5>
<p> <?php the_field( 'crew_member_excerpt' ); ?> </p>
</div>
</div>
</div>
</div>
</section>
<?php endwhile; endif; ?>
<?php wp_reset_postdata(); ?>
```
**EDIT:**
After swissspidy's answer, I tried this:
```
<?php
if ( 1 === $the_query->current_post % 2 ) {
$class = 'class="switchable"';
}
?>
<section <?php echo $class; ?>>
<div class="container">
<div class="row justify-content-between">
<div class="col-md-6">
<div> <?php the_content(); ?> </div>
</div>
<div class="col-md-6">
<div class="boxed boxed--lg boxed--border bg--secondary"> <img src="<?php the_post_thumbnail_url(); ?>" class="border--round">
<?php // another way: <?php the_post_thumbnail( array (475, 317), [ 'class' => 'border--round' ] ); ?>
<h5><?php the_title(); ?></h5>
<p> <?php the_field( 'crew_member_excerpt' ); ?> </p>
</div>
</div>
</div>
</div>
</section>
``` | Inside the loop you can use `$the_query->current_post` to get the index of the post currently being displayed. You can then check if the index is an odd or even number and conditionally add the class. Example:
```
if ( 1 === $the_query->current_post % 2 ) {
echo 'class="switchable"';
}
``` |
299,386 | <p>I am currently working on my <code>home.php</code> file for my theme, and I'm planning on displaying my the last Blog posts in a "grid view", so that there are 4 containers in a row, containing the title and some more information.</p>
<p>I tried out some things, but nothing worked the way I wanted it to. The last thing I did was putting a for loop like this: </p>
<pre><code><?php
for ($x = 1; $x <= 6; $x++) :
?>
<div id="home_post_<?php echo $x ?> " class="home_post">
<?php
if(have_posts()) :
while(have_posts()) : the_post();
get_template_part('template-parts/content', 'home');
endwhile;
endif;
?>
</div>
<?php
endfor;
?>
</code></pre>
<p>Around my loop, but that way, every new <code>div</code> is filled with the first overall Blogpost, so this is not the way to do it. </p>
<p>Is there a clever way to work with a loop that "generates" divs or am I just on the wrong track? </p>
| [
{
"answer_id": 299387,
"author": "jkresse",
"author_id": 140133,
"author_profile": "https://wordpress.stackexchange.com/users/140133",
"pm_score": 0,
"selected": false,
"text": "<p>Solved it by myself, here is how i did it: </p>\n\n<pre><code> <?php\n\n $x = 0;\n if(have_posts()) : while(have_posts() and $x <=5) : the_post(); ?>\n <div id=\"home_post_<?php echo $x ?>\"> <?php\n get_template_part('template-parts/content', 'home');\n ?> </div> <?php\n $x++;\n endwhile;\n endif;\n ?>\n</code></pre>\n"
},
{
"answer_id": 299391,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>It's a little bit hard to guess, what exactly do you want to achieve (you've mentioned something about four posts in a row and then there is number 6 in your for loop), but...</p>\n\n<p>If you want to display only 4 posts in your loop, then you can use <code>current_post</code> field of <code>$wp_query</code>, so the loop may look like this:</p>\n\n<pre><code><?php while ( have_posts() and $wp_query->current_post < 4) : the_post(); ?>\n <div id=\"home_post_<?php echo $wp_query->current_post ?>\">\n <?php get_template_part('template-parts/content', 'home'); ?>\n </div>\n<?php endwhile; ?>\n// you don't do anything if there are no posts, so there's no point in checking if (have_posts())\n</code></pre>\n\n<p>Another thing worth to remember is that if you'd like to show only 4 posts on your home, then it's a good idea to modify query accordingly - so it doesn't get redundant posts.</p>\n"
}
]
| 2018/03/30 | [
"https://wordpress.stackexchange.com/questions/299386",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140133/"
]
| I am currently working on my `home.php` file for my theme, and I'm planning on displaying my the last Blog posts in a "grid view", so that there are 4 containers in a row, containing the title and some more information.
I tried out some things, but nothing worked the way I wanted it to. The last thing I did was putting a for loop like this:
```
<?php
for ($x = 1; $x <= 6; $x++) :
?>
<div id="home_post_<?php echo $x ?> " class="home_post">
<?php
if(have_posts()) :
while(have_posts()) : the_post();
get_template_part('template-parts/content', 'home');
endwhile;
endif;
?>
</div>
<?php
endfor;
?>
```
Around my loop, but that way, every new `div` is filled with the first overall Blogpost, so this is not the way to do it.
Is there a clever way to work with a loop that "generates" divs or am I just on the wrong track? | It's a little bit hard to guess, what exactly do you want to achieve (you've mentioned something about four posts in a row and then there is number 6 in your for loop), but...
If you want to display only 4 posts in your loop, then you can use `current_post` field of `$wp_query`, so the loop may look like this:
```
<?php while ( have_posts() and $wp_query->current_post < 4) : the_post(); ?>
<div id="home_post_<?php echo $wp_query->current_post ?>">
<?php get_template_part('template-parts/content', 'home'); ?>
</div>
<?php endwhile; ?>
// you don't do anything if there are no posts, so there's no point in checking if (have_posts())
```
Another thing worth to remember is that if you'd like to show only 4 posts on your home, then it's a good idea to modify query accordingly - so it doesn't get redundant posts. |
299,437 | <p>Is it possible to use wp_remote_post to send http post requests to 3rd party api's? I wasn't able to successfully save the user object as a javascript variable, so I was hoping I could make an http request with php and handle the javascript manipulation in my node express app. </p>
<p>Current attempt:</p>
<pre><code>function identify_user() {
echo "made it into identify user";
if( is_user_logged_in()):
$current_user = wp_get_current_user();
$user = [];
$user['id'] = $current_user->ID;
$user['user_login'] = $current_user->user_login;
$user['user_email'] = $current_user->user_email;
$user['user_firstname'] = $current_user->user_firstname;
$user['user_lastname'] = $current_user->user_lastname;
$user['display_name'] = $current_user->display_name;
$response = wp_remote_post( 'myapp.com/endpoint', array(
'method' => 'POST',
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'body' => json_encode($user)
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
print_r( $response );
}
endif;
}
add_action( 'wp_login', 'identify_user' );
</code></pre>
<p>I'm having trouble troubleshooting this code because none of my echo calls are logging to the console. I've seen that you can run error_log(something) but haven't been able to get that working either. </p>
| [
{
"answer_id": 299438,
"author": "Somin",
"author_id": 140832,
"author_profile": "https://wordpress.stackexchange.com/users/140832",
"pm_score": 0,
"selected": false,
"text": "<p>You can try below code for wp_remote_post.might be you are missing remote post url parameter.</p>\n\n<p>Also i have noticed that you are converting user variable in to json format 2 time which is wrong.</p>\n\n<pre><code>$response = wp_remote_post($url, array(\n 'method' => 'POST',\n 'headers' => array('Content-Type' => 'application/json; charset=utf-8'),\n 'httpversion' => '1.0',\n 'sslverify' => false,\n 'body' => json_encode($user)\n );\n</code></pre>\n"
},
{
"answer_id": 299442,
"author": "Somin",
"author_id": 140832,
"author_profile": "https://wordpress.stackexchange.com/users/140832",
"pm_score": 1,
"selected": false,
"text": "<p>Please try below code might be help to you.</p>\n\n<pre><code>function identify_user() { \nif( is_user_logged_in()): \n$current_user = wp_get_current_user(); \n$_id = $current_user->ID; \n$_email = $current_user->user_email; \n$user = json_encode(array(\"user_id\"=>$_id,\"user_email\"=>$_email)); \n$curl = curl_init(\"myeNDPOINT\"); \ncurl_setopt( $curl, CURLOPT_POST, true ); \ncurl_setopt( $curl, CURLOPT_POSTFIELDS,$user); \ncurl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type:application/json')); \ncurl_exec( $curl ); \ncurl_close( $curl ); \nendif; \n} \n\nadd_action( 'wp_enqueue_scripts', 'identify_user');\n</code></pre>\n"
},
{
"answer_id": 316784,
"author": "patman",
"author_id": 152397,
"author_profile": "https://wordpress.stackexchange.com/users/152397",
"pm_score": 4,
"selected": true,
"text": "<p>The 'body' needs to be an array, not including the 'json_encode($user)' piece.</p>\n\n<pre><code>$response = wp_remote_post( 'myapp.com/endpoint', array(\n 'method' => 'POST',\n 'headers' => array('Content-Type' => 'application/json; charset=utf-8'),\n 'body' => $user\n )\n);\n</code></pre>\n\n<p>I have this in my function since I also had issues with the body being an object:</p>\n\n<pre><code>if (is_object($user) && !is_array($user))\n $user = json_decode(json_encode($user), true);\n$body = $user;\n</code></pre>\n\n<p>Regarding the 'run error_log(something) ...' that you are having problems with, try \n<a href=\"https://wordpress.stackexchange.com/questions/260236/how-to-put-logs-in-wordpress\">#David Lee's wrapper function</a></p>\n\n<p>Basically you can call </p>\n\n<pre><code>write_log('THIS IS THE START OF MY CUSTOM DEBUG');\n // or log data like objects\nwrite_log($object_you_want_to_log);\n</code></pre>\n\n<p>I don't know what I would do without it.</p>\n"
}
]
| 2018/03/31 | [
"https://wordpress.stackexchange.com/questions/299437",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140794/"
]
| Is it possible to use wp\_remote\_post to send http post requests to 3rd party api's? I wasn't able to successfully save the user object as a javascript variable, so I was hoping I could make an http request with php and handle the javascript manipulation in my node express app.
Current attempt:
```
function identify_user() {
echo "made it into identify user";
if( is_user_logged_in()):
$current_user = wp_get_current_user();
$user = [];
$user['id'] = $current_user->ID;
$user['user_login'] = $current_user->user_login;
$user['user_email'] = $current_user->user_email;
$user['user_firstname'] = $current_user->user_firstname;
$user['user_lastname'] = $current_user->user_lastname;
$user['display_name'] = $current_user->display_name;
$response = wp_remote_post( 'myapp.com/endpoint', array(
'method' => 'POST',
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'body' => json_encode($user)
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
print_r( $response );
}
endif;
}
add_action( 'wp_login', 'identify_user' );
```
I'm having trouble troubleshooting this code because none of my echo calls are logging to the console. I've seen that you can run error\_log(something) but haven't been able to get that working either. | The 'body' needs to be an array, not including the 'json\_encode($user)' piece.
```
$response = wp_remote_post( 'myapp.com/endpoint', array(
'method' => 'POST',
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'body' => $user
)
);
```
I have this in my function since I also had issues with the body being an object:
```
if (is_object($user) && !is_array($user))
$user = json_decode(json_encode($user), true);
$body = $user;
```
Regarding the 'run error\_log(something) ...' that you are having problems with, try
[#David Lee's wrapper function](https://wordpress.stackexchange.com/questions/260236/how-to-put-logs-in-wordpress)
Basically you can call
```
write_log('THIS IS THE START OF MY CUSTOM DEBUG');
// or log data like objects
write_log($object_you_want_to_log);
```
I don't know what I would do without it. |
299,521 | <p>I am new to Wordpress development and am tired of fighting with Contact form 7 to style it how I would like. Is it possible and not considered 'bad practice' to put a html form on my contact page and have it post to a php page which handles the form submission? Or is that just simply not done?</p>
| [
{
"answer_id": 299525,
"author": "Mr Rethman",
"author_id": 27393,
"author_profile": "https://wordpress.stackexchange.com/users/27393",
"pm_score": 1,
"selected": false,
"text": "<p>Since your not performing CRUD on the DB, I don't see why not. I've done it before where I used a page template for form processing and pointed my contact <code><form ...></code> <code>action</code> to it <code>action=\"<?php echo home_url( 'my-form-processing-page-template-slug' ); ?>\"</code>. </p>\n\n<p>Alternatively, use the actual single post type to process it i.e. <code>action=\"<?php echo get_the_permalink();?>\"</code> (needs to be a <code>is_single() || is_singular()</code> to use <code>get_the_permalink()</code>).</p>\n"
},
{
"answer_id": 299526,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>All form plugins are horrible, it is just that forms are typically very complex to code correctly, especially when the site admin should be able to design them.</p>\n\n<p>There is nothing wrong with coding a form yourself, it is just that you will probably need to recreate stuff which other people have already perfected, or at least have a good foundations for (formatting emails, storing in the DB and probably more).</p>\n\n<p>So it is really depends on your specific requirements, if flexibility is not required, and sending email is good enough, it should be easier to write your own than \"fighting\" with the plugins.</p>\n"
},
{
"answer_id": 299547,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": true,
"text": "<p>This is my very simple implementation of contact form:</p>\n\n<pre><code>class WPSE_299521_Form {\n\n /**\n * Class constructor\n */\n public function __construct() {\n\n $this->define_hooks();\n }\n\n public function controller() {\n\n if( isset( $_POST['submit'] ) ) { // Submit button\n\n $full_name = filter_input( INPUT_POST, 'full_name', FILTER_SANITIZE_STRING );\n $email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING | FILTER_SANITIZE_EMAIL );\n $color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );\n $accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );\n $comments = filter_input( INPUT_POST, 'comments', FILTER_SANITIZE_STRING );\n\n // Send an email and redirect user to \"Thank you\" page.\n }\n }\n\n /**\n * Display form\n */\n public function display_form() {\n\n $full_name = filter_input( INPUT_POST, 'full_name', FILTER_SANITIZE_STRING );\n $email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING | FILTER_SANITIZE_EMAIL );\n $color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );\n $accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );\n $comments = filter_input( INPUT_POST, 'comments', FILTER_SANITIZE_STRING );\n\n // Default empty array\n $accessories = ( $accessories === null ) ? array() : $accessories;\n\n $output = '';\n\n $output .= '<form method=\"post\">';\n $output .= ' <p>';\n $output .= ' ' . $this->display_text( 'full_name', 'Name', $full_name );\n $output .= ' </p>';\n $output .= ' <p>';\n $output .= ' ' . $this->display_text( 'email', 'Email', $email );\n $output .= ' </p>';\n $output .= ' <p>';\n $output .= ' ' . $this->display_radios( 'color', 'Color', $this->get_available_colors(), $color );\n $output .= ' </p>';\n $output .= ' <p>';\n $output .= ' ' . $this->display_checkboxes( 'accessories', 'Accessories', $this->get_available_accessories(), $accessories );\n $output .= ' </p>';\n $output .= ' <p>';\n $output .= ' ' . $this->display_textarea( 'comments', 'comments', $comments );\n $output .= ' </p>';\n $output .= ' <p>';\n $output .= ' <input type=\"submit\" name=\"submit\" value=\"Submit\" />';\n $output .= ' </p>';\n $output .= '</form>';\n\n return $output;\n }\n\n /**\n * Display text field\n */\n private function display_text( $name, $label, $value = '' ) {\n\n $output = '';\n\n $output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';\n $output .= '<input type=\"text\" name=\"' . esc_attr( $name ) . '\" value=\"' . esc_attr( $value ) . '\">';\n\n return $output;\n }\n\n /**\n * Display textarea field\n */\n private function display_textarea( $name, $label, $value = '' ) {\n\n $output = '';\n\n $output .= '<label> ' . esc_html__( $label, 'wpse_299521' ) . '</label>';\n $output .= '<textarea name=\"' . esc_attr( $name ) . '\" >' . esc_html( $value ) . '</textarea>';\n\n return $output;\n }\n\n /**\n * Display radios field\n */\n private function display_radios( $name, $label, $options, $value = null ) {\n\n $output = '';\n\n $output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';\n\n foreach ( $options as $option_value => $option_label ):\n $output .= $this->display_radio( $name, $option_label, $option_value, $value );\n endforeach;\n\n return $output;\n }\n\n /**\n * Display single checkbox field\n */\n private function display_radio( $name, $label, $option_value, $value = null ) {\n\n $output = '';\n\n $checked = ( $option_value === $value ) ? ' checked' : '';\n\n $output .= '<label>';\n $output .= ' <input type=\"radio\" name=\"' . esc_attr( $name ) . '\" value=\"' . esc_attr( $option_value ) . '\"' . esc_attr( $checked ) . '>';\n $output .= ' ' . esc_html__( $label, 'wpse_299521' );\n $output .= '</label>';\n\n return $output;\n }\n\n /**\n * Display checkboxes field\n */\n private function display_checkboxes( $name, $label, $options, $values = array() ) {\n\n $output = '';\n\n $name .= '[]';\n\n $output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';\n\n foreach ( $options as $option_value => $option_label ):\n $output .= $this->display_checkbox( $name, $option_label, $option_value, $values );\n endforeach;\n\n return $output;\n }\n\n /**\n * Display single checkbox field\n */\n private function display_checkbox( $name, $label, $available_value, $values = array() ) {\n\n $output = '';\n\n $checked = ( in_array($available_value, $values) ) ? ' checked' : '';\n\n $output .= '<label>';\n $output .= ' <input type=\"checkbox\" name=\"' . esc_attr( $name ) . '\" value=\"' . esc_attr( $available_value ) . '\"' . esc_attr( $checked ) . '>';\n $output .= ' ' . esc_html__( $label, 'wpse_299521' );\n $output .= '</label>';\n\n return $output;\n }\n\n /**\n * Get available colors\n */\n private function get_available_colors() {\n\n return array(\n 'red' => 'Red',\n 'blue' => 'Blue',\n 'green' => 'Green',\n );\n }\n\n /**\n * Get available accessories\n */\n private function get_available_accessories() {\n\n return array(\n 'case' => 'Case',\n 'tempered_glass' => 'Tempered glass',\n 'headphones' => 'Headphones',\n );\n }\n\n /**\n * Define hooks related to plugin\n */\n private function define_hooks() {\n\n /**\n * Add action to send email\n */\n add_action( 'wp', array( $this, 'controller' ) );\n\n /**\n * Add shortcode to display form\n */\n add_shortcode( 'contact', array( $this, 'display_form' ) );\n }\n}\n\nnew WPSE_299521_Form();\n</code></pre>\n\n<p>After pasting code you can use shortcode <code>[contact]</code> to display it.</p>\n"
}
]
| 2018/04/01 | [
"https://wordpress.stackexchange.com/questions/299521",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140276/"
]
| I am new to Wordpress development and am tired of fighting with Contact form 7 to style it how I would like. Is it possible and not considered 'bad practice' to put a html form on my contact page and have it post to a php page which handles the form submission? Or is that just simply not done? | This is my very simple implementation of contact form:
```
class WPSE_299521_Form {
/**
* Class constructor
*/
public function __construct() {
$this->define_hooks();
}
public function controller() {
if( isset( $_POST['submit'] ) ) { // Submit button
$full_name = filter_input( INPUT_POST, 'full_name', FILTER_SANITIZE_STRING );
$email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING | FILTER_SANITIZE_EMAIL );
$color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );
$accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );
$comments = filter_input( INPUT_POST, 'comments', FILTER_SANITIZE_STRING );
// Send an email and redirect user to "Thank you" page.
}
}
/**
* Display form
*/
public function display_form() {
$full_name = filter_input( INPUT_POST, 'full_name', FILTER_SANITIZE_STRING );
$email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING | FILTER_SANITIZE_EMAIL );
$color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );
$accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );
$comments = filter_input( INPUT_POST, 'comments', FILTER_SANITIZE_STRING );
// Default empty array
$accessories = ( $accessories === null ) ? array() : $accessories;
$output = '';
$output .= '<form method="post">';
$output .= ' <p>';
$output .= ' ' . $this->display_text( 'full_name', 'Name', $full_name );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_text( 'email', 'Email', $email );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_radios( 'color', 'Color', $this->get_available_colors(), $color );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_checkboxes( 'accessories', 'Accessories', $this->get_available_accessories(), $accessories );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_textarea( 'comments', 'comments', $comments );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' <input type="submit" name="submit" value="Submit" />';
$output .= ' </p>';
$output .= '</form>';
return $output;
}
/**
* Display text field
*/
private function display_text( $name, $label, $value = '' ) {
$output = '';
$output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';
$output .= '<input type="text" name="' . esc_attr( $name ) . '" value="' . esc_attr( $value ) . '">';
return $output;
}
/**
* Display textarea field
*/
private function display_textarea( $name, $label, $value = '' ) {
$output = '';
$output .= '<label> ' . esc_html__( $label, 'wpse_299521' ) . '</label>';
$output .= '<textarea name="' . esc_attr( $name ) . '" >' . esc_html( $value ) . '</textarea>';
return $output;
}
/**
* Display radios field
*/
private function display_radios( $name, $label, $options, $value = null ) {
$output = '';
$output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';
foreach ( $options as $option_value => $option_label ):
$output .= $this->display_radio( $name, $option_label, $option_value, $value );
endforeach;
return $output;
}
/**
* Display single checkbox field
*/
private function display_radio( $name, $label, $option_value, $value = null ) {
$output = '';
$checked = ( $option_value === $value ) ? ' checked' : '';
$output .= '<label>';
$output .= ' <input type="radio" name="' . esc_attr( $name ) . '" value="' . esc_attr( $option_value ) . '"' . esc_attr( $checked ) . '>';
$output .= ' ' . esc_html__( $label, 'wpse_299521' );
$output .= '</label>';
return $output;
}
/**
* Display checkboxes field
*/
private function display_checkboxes( $name, $label, $options, $values = array() ) {
$output = '';
$name .= '[]';
$output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';
foreach ( $options as $option_value => $option_label ):
$output .= $this->display_checkbox( $name, $option_label, $option_value, $values );
endforeach;
return $output;
}
/**
* Display single checkbox field
*/
private function display_checkbox( $name, $label, $available_value, $values = array() ) {
$output = '';
$checked = ( in_array($available_value, $values) ) ? ' checked' : '';
$output .= '<label>';
$output .= ' <input type="checkbox" name="' . esc_attr( $name ) . '" value="' . esc_attr( $available_value ) . '"' . esc_attr( $checked ) . '>';
$output .= ' ' . esc_html__( $label, 'wpse_299521' );
$output .= '</label>';
return $output;
}
/**
* Get available colors
*/
private function get_available_colors() {
return array(
'red' => 'Red',
'blue' => 'Blue',
'green' => 'Green',
);
}
/**
* Get available accessories
*/
private function get_available_accessories() {
return array(
'case' => 'Case',
'tempered_glass' => 'Tempered glass',
'headphones' => 'Headphones',
);
}
/**
* Define hooks related to plugin
*/
private function define_hooks() {
/**
* Add action to send email
*/
add_action( 'wp', array( $this, 'controller' ) );
/**
* Add shortcode to display form
*/
add_shortcode( 'contact', array( $this, 'display_form' ) );
}
}
new WPSE_299521_Form();
```
After pasting code you can use shortcode `[contact]` to display it. |
299,533 | <p>I have a few years worth of experience building <a href="https://developer.wordpress.org/themes/advanced-topics/child-themes/" rel="nofollow noreferrer">Child Themes</a> in WordPress, which is generally my preferred route when developing a new website as I am not a theme developer per say.</p>
<p>I am now doing a couple of projects which want to leverage the WP REST API, and I am looking to use the <a href="https://github.com/ryelle/Foxhound" rel="nofollow noreferrer">Foxhound</a> theme, built using React js, as a parent theme.</p>
<p>Beyond the page template/css overloading approach to child theme-ing, I have been trying to understand how to extend the parent theme's default react app functionality to customise my child theme js functionality. I understand how to <a href="https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#adding-custom-fields-to-api-responses" rel="nofollow noreferrer">add custom fields</a> to existing end-points, however, what I am not able to understand is how to load <a href="https://www.tutorialspoint.com/reactjs/reactjs_component_life_cycle.htm" rel="nofollow noreferrer">custom react components</a>. Should I/Can I build a <a href="https://github.com/facebook/create-react-app" rel="nofollow noreferrer">custom react app</a> to load from my child theme? If so how can I ensure it executes after the parent theme app? </p>
| [
{
"answer_id": 299525,
"author": "Mr Rethman",
"author_id": 27393,
"author_profile": "https://wordpress.stackexchange.com/users/27393",
"pm_score": 1,
"selected": false,
"text": "<p>Since your not performing CRUD on the DB, I don't see why not. I've done it before where I used a page template for form processing and pointed my contact <code><form ...></code> <code>action</code> to it <code>action=\"<?php echo home_url( 'my-form-processing-page-template-slug' ); ?>\"</code>. </p>\n\n<p>Alternatively, use the actual single post type to process it i.e. <code>action=\"<?php echo get_the_permalink();?>\"</code> (needs to be a <code>is_single() || is_singular()</code> to use <code>get_the_permalink()</code>).</p>\n"
},
{
"answer_id": 299526,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>All form plugins are horrible, it is just that forms are typically very complex to code correctly, especially when the site admin should be able to design them.</p>\n\n<p>There is nothing wrong with coding a form yourself, it is just that you will probably need to recreate stuff which other people have already perfected, or at least have a good foundations for (formatting emails, storing in the DB and probably more).</p>\n\n<p>So it is really depends on your specific requirements, if flexibility is not required, and sending email is good enough, it should be easier to write your own than \"fighting\" with the plugins.</p>\n"
},
{
"answer_id": 299547,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": true,
"text": "<p>This is my very simple implementation of contact form:</p>\n\n<pre><code>class WPSE_299521_Form {\n\n /**\n * Class constructor\n */\n public function __construct() {\n\n $this->define_hooks();\n }\n\n public function controller() {\n\n if( isset( $_POST['submit'] ) ) { // Submit button\n\n $full_name = filter_input( INPUT_POST, 'full_name', FILTER_SANITIZE_STRING );\n $email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING | FILTER_SANITIZE_EMAIL );\n $color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );\n $accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );\n $comments = filter_input( INPUT_POST, 'comments', FILTER_SANITIZE_STRING );\n\n // Send an email and redirect user to \"Thank you\" page.\n }\n }\n\n /**\n * Display form\n */\n public function display_form() {\n\n $full_name = filter_input( INPUT_POST, 'full_name', FILTER_SANITIZE_STRING );\n $email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING | FILTER_SANITIZE_EMAIL );\n $color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );\n $accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );\n $comments = filter_input( INPUT_POST, 'comments', FILTER_SANITIZE_STRING );\n\n // Default empty array\n $accessories = ( $accessories === null ) ? array() : $accessories;\n\n $output = '';\n\n $output .= '<form method=\"post\">';\n $output .= ' <p>';\n $output .= ' ' . $this->display_text( 'full_name', 'Name', $full_name );\n $output .= ' </p>';\n $output .= ' <p>';\n $output .= ' ' . $this->display_text( 'email', 'Email', $email );\n $output .= ' </p>';\n $output .= ' <p>';\n $output .= ' ' . $this->display_radios( 'color', 'Color', $this->get_available_colors(), $color );\n $output .= ' </p>';\n $output .= ' <p>';\n $output .= ' ' . $this->display_checkboxes( 'accessories', 'Accessories', $this->get_available_accessories(), $accessories );\n $output .= ' </p>';\n $output .= ' <p>';\n $output .= ' ' . $this->display_textarea( 'comments', 'comments', $comments );\n $output .= ' </p>';\n $output .= ' <p>';\n $output .= ' <input type=\"submit\" name=\"submit\" value=\"Submit\" />';\n $output .= ' </p>';\n $output .= '</form>';\n\n return $output;\n }\n\n /**\n * Display text field\n */\n private function display_text( $name, $label, $value = '' ) {\n\n $output = '';\n\n $output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';\n $output .= '<input type=\"text\" name=\"' . esc_attr( $name ) . '\" value=\"' . esc_attr( $value ) . '\">';\n\n return $output;\n }\n\n /**\n * Display textarea field\n */\n private function display_textarea( $name, $label, $value = '' ) {\n\n $output = '';\n\n $output .= '<label> ' . esc_html__( $label, 'wpse_299521' ) . '</label>';\n $output .= '<textarea name=\"' . esc_attr( $name ) . '\" >' . esc_html( $value ) . '</textarea>';\n\n return $output;\n }\n\n /**\n * Display radios field\n */\n private function display_radios( $name, $label, $options, $value = null ) {\n\n $output = '';\n\n $output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';\n\n foreach ( $options as $option_value => $option_label ):\n $output .= $this->display_radio( $name, $option_label, $option_value, $value );\n endforeach;\n\n return $output;\n }\n\n /**\n * Display single checkbox field\n */\n private function display_radio( $name, $label, $option_value, $value = null ) {\n\n $output = '';\n\n $checked = ( $option_value === $value ) ? ' checked' : '';\n\n $output .= '<label>';\n $output .= ' <input type=\"radio\" name=\"' . esc_attr( $name ) . '\" value=\"' . esc_attr( $option_value ) . '\"' . esc_attr( $checked ) . '>';\n $output .= ' ' . esc_html__( $label, 'wpse_299521' );\n $output .= '</label>';\n\n return $output;\n }\n\n /**\n * Display checkboxes field\n */\n private function display_checkboxes( $name, $label, $options, $values = array() ) {\n\n $output = '';\n\n $name .= '[]';\n\n $output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';\n\n foreach ( $options as $option_value => $option_label ):\n $output .= $this->display_checkbox( $name, $option_label, $option_value, $values );\n endforeach;\n\n return $output;\n }\n\n /**\n * Display single checkbox field\n */\n private function display_checkbox( $name, $label, $available_value, $values = array() ) {\n\n $output = '';\n\n $checked = ( in_array($available_value, $values) ) ? ' checked' : '';\n\n $output .= '<label>';\n $output .= ' <input type=\"checkbox\" name=\"' . esc_attr( $name ) . '\" value=\"' . esc_attr( $available_value ) . '\"' . esc_attr( $checked ) . '>';\n $output .= ' ' . esc_html__( $label, 'wpse_299521' );\n $output .= '</label>';\n\n return $output;\n }\n\n /**\n * Get available colors\n */\n private function get_available_colors() {\n\n return array(\n 'red' => 'Red',\n 'blue' => 'Blue',\n 'green' => 'Green',\n );\n }\n\n /**\n * Get available accessories\n */\n private function get_available_accessories() {\n\n return array(\n 'case' => 'Case',\n 'tempered_glass' => 'Tempered glass',\n 'headphones' => 'Headphones',\n );\n }\n\n /**\n * Define hooks related to plugin\n */\n private function define_hooks() {\n\n /**\n * Add action to send email\n */\n add_action( 'wp', array( $this, 'controller' ) );\n\n /**\n * Add shortcode to display form\n */\n add_shortcode( 'contact', array( $this, 'display_form' ) );\n }\n}\n\nnew WPSE_299521_Form();\n</code></pre>\n\n<p>After pasting code you can use shortcode <code>[contact]</code> to display it.</p>\n"
}
]
| 2018/04/01 | [
"https://wordpress.stackexchange.com/questions/299533",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52120/"
]
| I have a few years worth of experience building [Child Themes](https://developer.wordpress.org/themes/advanced-topics/child-themes/) in WordPress, which is generally my preferred route when developing a new website as I am not a theme developer per say.
I am now doing a couple of projects which want to leverage the WP REST API, and I am looking to use the [Foxhound](https://github.com/ryelle/Foxhound) theme, built using React js, as a parent theme.
Beyond the page template/css overloading approach to child theme-ing, I have been trying to understand how to extend the parent theme's default react app functionality to customise my child theme js functionality. I understand how to [add custom fields](https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#adding-custom-fields-to-api-responses) to existing end-points, however, what I am not able to understand is how to load [custom react components](https://www.tutorialspoint.com/reactjs/reactjs_component_life_cycle.htm). Should I/Can I build a [custom react app](https://github.com/facebook/create-react-app) to load from my child theme? If so how can I ensure it executes after the parent theme app? | This is my very simple implementation of contact form:
```
class WPSE_299521_Form {
/**
* Class constructor
*/
public function __construct() {
$this->define_hooks();
}
public function controller() {
if( isset( $_POST['submit'] ) ) { // Submit button
$full_name = filter_input( INPUT_POST, 'full_name', FILTER_SANITIZE_STRING );
$email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING | FILTER_SANITIZE_EMAIL );
$color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );
$accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );
$comments = filter_input( INPUT_POST, 'comments', FILTER_SANITIZE_STRING );
// Send an email and redirect user to "Thank you" page.
}
}
/**
* Display form
*/
public function display_form() {
$full_name = filter_input( INPUT_POST, 'full_name', FILTER_SANITIZE_STRING );
$email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING | FILTER_SANITIZE_EMAIL );
$color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );
$accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );
$comments = filter_input( INPUT_POST, 'comments', FILTER_SANITIZE_STRING );
// Default empty array
$accessories = ( $accessories === null ) ? array() : $accessories;
$output = '';
$output .= '<form method="post">';
$output .= ' <p>';
$output .= ' ' . $this->display_text( 'full_name', 'Name', $full_name );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_text( 'email', 'Email', $email );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_radios( 'color', 'Color', $this->get_available_colors(), $color );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_checkboxes( 'accessories', 'Accessories', $this->get_available_accessories(), $accessories );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_textarea( 'comments', 'comments', $comments );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' <input type="submit" name="submit" value="Submit" />';
$output .= ' </p>';
$output .= '</form>';
return $output;
}
/**
* Display text field
*/
private function display_text( $name, $label, $value = '' ) {
$output = '';
$output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';
$output .= '<input type="text" name="' . esc_attr( $name ) . '" value="' . esc_attr( $value ) . '">';
return $output;
}
/**
* Display textarea field
*/
private function display_textarea( $name, $label, $value = '' ) {
$output = '';
$output .= '<label> ' . esc_html__( $label, 'wpse_299521' ) . '</label>';
$output .= '<textarea name="' . esc_attr( $name ) . '" >' . esc_html( $value ) . '</textarea>';
return $output;
}
/**
* Display radios field
*/
private function display_radios( $name, $label, $options, $value = null ) {
$output = '';
$output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';
foreach ( $options as $option_value => $option_label ):
$output .= $this->display_radio( $name, $option_label, $option_value, $value );
endforeach;
return $output;
}
/**
* Display single checkbox field
*/
private function display_radio( $name, $label, $option_value, $value = null ) {
$output = '';
$checked = ( $option_value === $value ) ? ' checked' : '';
$output .= '<label>';
$output .= ' <input type="radio" name="' . esc_attr( $name ) . '" value="' . esc_attr( $option_value ) . '"' . esc_attr( $checked ) . '>';
$output .= ' ' . esc_html__( $label, 'wpse_299521' );
$output .= '</label>';
return $output;
}
/**
* Display checkboxes field
*/
private function display_checkboxes( $name, $label, $options, $values = array() ) {
$output = '';
$name .= '[]';
$output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';
foreach ( $options as $option_value => $option_label ):
$output .= $this->display_checkbox( $name, $option_label, $option_value, $values );
endforeach;
return $output;
}
/**
* Display single checkbox field
*/
private function display_checkbox( $name, $label, $available_value, $values = array() ) {
$output = '';
$checked = ( in_array($available_value, $values) ) ? ' checked' : '';
$output .= '<label>';
$output .= ' <input type="checkbox" name="' . esc_attr( $name ) . '" value="' . esc_attr( $available_value ) . '"' . esc_attr( $checked ) . '>';
$output .= ' ' . esc_html__( $label, 'wpse_299521' );
$output .= '</label>';
return $output;
}
/**
* Get available colors
*/
private function get_available_colors() {
return array(
'red' => 'Red',
'blue' => 'Blue',
'green' => 'Green',
);
}
/**
* Get available accessories
*/
private function get_available_accessories() {
return array(
'case' => 'Case',
'tempered_glass' => 'Tempered glass',
'headphones' => 'Headphones',
);
}
/**
* Define hooks related to plugin
*/
private function define_hooks() {
/**
* Add action to send email
*/
add_action( 'wp', array( $this, 'controller' ) );
/**
* Add shortcode to display form
*/
add_shortcode( 'contact', array( $this, 'display_form' ) );
}
}
new WPSE_299521_Form();
```
After pasting code you can use shortcode `[contact]` to display it. |
299,542 | <p>This is not really a question but a guide on how to make authenticated requests to the Wordpress API using JWT. I'm writing this as a reminder to myself and for those who may need some help with the same topic. </p>
| [
{
"answer_id": 302024,
"author": "grazdev",
"author_id": 129417,
"author_profile": "https://wordpress.stackexchange.com/users/129417",
"pm_score": 6,
"selected": true,
"text": "<p><strong>Why JWT authentication</strong></p>\n\n<p>I'm building a site that uses Wordpress as the back-end, and a React+Redux app as the front-end, so I'm pulling all the content in the front-end by making requests to the Wordpress API. Some requests (mainly, POST requests) must be authenticated, which is when I came across JWT.</p>\n\n<p><strong>What we need</strong></p>\n\n<p>To use JWT authentication with Wordpress, we first need to install the <a href=\"https://it.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/\" rel=\"noreferrer\">JWT Authentication for WP REST API</a> plugin. As is explained in the plugin's instructions, we also need to modify some core Wordpress files. In particular:</p>\n\n<p>In the .htaccess file included in the Wordpress installation's root folder, we need to add the following lines:</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{HTTP:Authorization} ^(.*)\nRewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]\n</code></pre>\n\n<p>In the wp-config.php file, also included in the Wordpress installation's root folder, we need to add these lines:</p>\n\n<pre><code>define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key'); // Replace 'your-top-secret-key' with an actual secret key.\ndefine('JWT_AUTH_CORS_ENABLE', true);\n</code></pre>\n\n<p><strong>Testing to see if JWT is available</strong></p>\n\n<p>To verify that we can now use JWT, fire up Postman and make a request to the Wordpress API's default 'index':</p>\n\n<pre><code>http://example.com/wp-json/\n</code></pre>\n\n<p>A few new endpoints, like <code>/jwt-auth/v1</code> and <code>/jwt-auth/v1/token</code> should have been added to the API. If you can find them in the response to the above request, it means JWT is now available.</p>\n\n<p><strong>Getting the JWT token</strong></p>\n\n<p>Let's stay in Postman for the moment, and let's request a token to the Wordpress API:</p>\n\n<pre><code>http://example.com/wp-json/jwt-auth/v1/token\n</code></pre>\n\n<p>The response will contain the JWT token, which is an encrypted key that looks something like this:</p>\n\n<blockquote>\n <p>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODg4OFwvZm90b3Jvb20tbmV4dCIsImlhdCI6MTUyMjU5NzQ1MiwibmJmIjoxNTIyNTk3NDUyLCJleHAiOjE1MjMyMDIyNTIsImRhdGEiOnsidXNlciI6eyJpZCI6IjEifX19.hxaaT9iowAX1Xf8RUM42OwbP7QgRNxux8eTtKhWvEUM</p>\n</blockquote>\n\n<p><strong>Making an authenticated request</strong></p>\n\n<p>Let's try to change the title of a post with an ID of 300 as an example of an authenticated request with JWT.</p>\n\n<p>In Postman, choose POST as the method and type the following endpoint:</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/posts/300\n</code></pre>\n\n<p>Choose No Auth in the Authorization tab, and add the following in the Headers tab:</p>\n\n<pre><code>'Content-type': 'application/json', \n'Authorization': 'Bearer jwtToken' // Replace jwtToken with the actual token (the encrypted key above)\n</code></pre>\n\n<p>Finally, in the Body tab, select the raw and JSON (application/json) options, then in the editor right below the options type the following:</p>\n\n<pre><code>{ \"title\": \"YES! Authenticated requests with JWT work\" }\n</code></pre>\n\n<p>Now you can hit SEND. Look in the response tab with all the data about the post that we requested: the value for the title key should now be <code>YES! Authenticated requests with JWT work</code></p>\n"
},
{
"answer_id": 309820,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 3,
"selected": false,
"text": "<p>Complementing @grazianodev's answer, this is how you get your authorization token using cURL:</p>\n\n<pre><code>/**\n* Generate a JWT token for future API calls to WordPress\n*/\nprivate function getToken() {\n $ch = curl_init();\n\n curl_setopt($ch, CURLOPT_URL,'https://site.localhost/wp-json/jwt-auth/v1/token');\n curl_setopt($ch, CURLOPT_POST, 1);\n\n # Admin credentials here\n curl_setopt($ch, CURLOPT_POSTFIELDS, \"username=admin&password=Str0ngPass\"); \n\n // receive server response ...\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n\n $server_output = curl_exec ($ch);\n if ($server_output === false) {\n die('Error getting JWT token on WordPress for API integration.');\n }\n $server_output = json_decode($server_output);\n\n if ($server_output === null && json_last_error() !== JSON_ERROR_NONE) {\n die('Invalid response getting JWT token on WordPress for API integration.');\n }\n\n if (!empty($server_output->token)) {\n $this->token = $server_output->token; # Token is here\n curl_close ($ch);\n return true;\n } else {\n die('Invalid response getting JWT token on WordPress for API integration.');\n }\n return false;\n}\n</code></pre>\n\n<p>After that, send your requests with the header: \"Authorization: Bearer $token\"</p>\n\n<p>Where $token is the token returned by the getToken() function above.</p>\n\n<p>I personally use the plugin \"<strong>Disable REST API and Require JWT / OAuth Authentication</strong>\" to restrict API access only with the token above.</p>\n"
}
]
| 2018/04/01 | [
"https://wordpress.stackexchange.com/questions/299542",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129417/"
]
| This is not really a question but a guide on how to make authenticated requests to the Wordpress API using JWT. I'm writing this as a reminder to myself and for those who may need some help with the same topic. | **Why JWT authentication**
I'm building a site that uses Wordpress as the back-end, and a React+Redux app as the front-end, so I'm pulling all the content in the front-end by making requests to the Wordpress API. Some requests (mainly, POST requests) must be authenticated, which is when I came across JWT.
**What we need**
To use JWT authentication with Wordpress, we first need to install the [JWT Authentication for WP REST API](https://it.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/) plugin. As is explained in the plugin's instructions, we also need to modify some core Wordpress files. In particular:
In the .htaccess file included in the Wordpress installation's root folder, we need to add the following lines:
```
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
```
In the wp-config.php file, also included in the Wordpress installation's root folder, we need to add these lines:
```
define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key'); // Replace 'your-top-secret-key' with an actual secret key.
define('JWT_AUTH_CORS_ENABLE', true);
```
**Testing to see if JWT is available**
To verify that we can now use JWT, fire up Postman and make a request to the Wordpress API's default 'index':
```
http://example.com/wp-json/
```
A few new endpoints, like `/jwt-auth/v1` and `/jwt-auth/v1/token` should have been added to the API. If you can find them in the response to the above request, it means JWT is now available.
**Getting the JWT token**
Let's stay in Postman for the moment, and let's request a token to the Wordpress API:
```
http://example.com/wp-json/jwt-auth/v1/token
```
The response will contain the JWT token, which is an encrypted key that looks something like this:
>
> eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODg4OFwvZm90b3Jvb20tbmV4dCIsImlhdCI6MTUyMjU5NzQ1MiwibmJmIjoxNTIyNTk3NDUyLCJleHAiOjE1MjMyMDIyNTIsImRhdGEiOnsidXNlciI6eyJpZCI6IjEifX19.hxaaT9iowAX1Xf8RUM42OwbP7QgRNxux8eTtKhWvEUM
>
>
>
**Making an authenticated request**
Let's try to change the title of a post with an ID of 300 as an example of an authenticated request with JWT.
In Postman, choose POST as the method and type the following endpoint:
```
http://example.com/wp-json/wp/v2/posts/300
```
Choose No Auth in the Authorization tab, and add the following in the Headers tab:
```
'Content-type': 'application/json',
'Authorization': 'Bearer jwtToken' // Replace jwtToken with the actual token (the encrypted key above)
```
Finally, in the Body tab, select the raw and JSON (application/json) options, then in the editor right below the options type the following:
```
{ "title": "YES! Authenticated requests with JWT work" }
```
Now you can hit SEND. Look in the response tab with all the data about the post that we requested: the value for the title key should now be `YES! Authenticated requests with JWT work` |
299,548 | <p>i am not good in php</p>
<p>but i am using advanced custom fields plugin to improve my web site , now in my website i using about 25 "text" advanced custom fields and 1 "choice - select" advanced custom field</p>
<p>and I also have a plugin like woocommerce it use about 15 custom fields</p>
<p>now i have about 40 custom field for every single post</p>
<p>i am using cache plugin so visitor will not query database but the plugin when it make cache it will query the database</p>
<p>my question is , i am worry about this a lot of custom fields may make performance issues in future when i have a lot of posts</p>
<p>i want your opinion if what i make is good or it will make performance issues ?</p>
<p>thanks alot</p>
| [
{
"answer_id": 302024,
"author": "grazdev",
"author_id": 129417,
"author_profile": "https://wordpress.stackexchange.com/users/129417",
"pm_score": 6,
"selected": true,
"text": "<p><strong>Why JWT authentication</strong></p>\n\n<p>I'm building a site that uses Wordpress as the back-end, and a React+Redux app as the front-end, so I'm pulling all the content in the front-end by making requests to the Wordpress API. Some requests (mainly, POST requests) must be authenticated, which is when I came across JWT.</p>\n\n<p><strong>What we need</strong></p>\n\n<p>To use JWT authentication with Wordpress, we first need to install the <a href=\"https://it.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/\" rel=\"noreferrer\">JWT Authentication for WP REST API</a> plugin. As is explained in the plugin's instructions, we also need to modify some core Wordpress files. In particular:</p>\n\n<p>In the .htaccess file included in the Wordpress installation's root folder, we need to add the following lines:</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{HTTP:Authorization} ^(.*)\nRewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]\n</code></pre>\n\n<p>In the wp-config.php file, also included in the Wordpress installation's root folder, we need to add these lines:</p>\n\n<pre><code>define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key'); // Replace 'your-top-secret-key' with an actual secret key.\ndefine('JWT_AUTH_CORS_ENABLE', true);\n</code></pre>\n\n<p><strong>Testing to see if JWT is available</strong></p>\n\n<p>To verify that we can now use JWT, fire up Postman and make a request to the Wordpress API's default 'index':</p>\n\n<pre><code>http://example.com/wp-json/\n</code></pre>\n\n<p>A few new endpoints, like <code>/jwt-auth/v1</code> and <code>/jwt-auth/v1/token</code> should have been added to the API. If you can find them in the response to the above request, it means JWT is now available.</p>\n\n<p><strong>Getting the JWT token</strong></p>\n\n<p>Let's stay in Postman for the moment, and let's request a token to the Wordpress API:</p>\n\n<pre><code>http://example.com/wp-json/jwt-auth/v1/token\n</code></pre>\n\n<p>The response will contain the JWT token, which is an encrypted key that looks something like this:</p>\n\n<blockquote>\n <p>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODg4OFwvZm90b3Jvb20tbmV4dCIsImlhdCI6MTUyMjU5NzQ1MiwibmJmIjoxNTIyNTk3NDUyLCJleHAiOjE1MjMyMDIyNTIsImRhdGEiOnsidXNlciI6eyJpZCI6IjEifX19.hxaaT9iowAX1Xf8RUM42OwbP7QgRNxux8eTtKhWvEUM</p>\n</blockquote>\n\n<p><strong>Making an authenticated request</strong></p>\n\n<p>Let's try to change the title of a post with an ID of 300 as an example of an authenticated request with JWT.</p>\n\n<p>In Postman, choose POST as the method and type the following endpoint:</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/posts/300\n</code></pre>\n\n<p>Choose No Auth in the Authorization tab, and add the following in the Headers tab:</p>\n\n<pre><code>'Content-type': 'application/json', \n'Authorization': 'Bearer jwtToken' // Replace jwtToken with the actual token (the encrypted key above)\n</code></pre>\n\n<p>Finally, in the Body tab, select the raw and JSON (application/json) options, then in the editor right below the options type the following:</p>\n\n<pre><code>{ \"title\": \"YES! Authenticated requests with JWT work\" }\n</code></pre>\n\n<p>Now you can hit SEND. Look in the response tab with all the data about the post that we requested: the value for the title key should now be <code>YES! Authenticated requests with JWT work</code></p>\n"
},
{
"answer_id": 309820,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 3,
"selected": false,
"text": "<p>Complementing @grazianodev's answer, this is how you get your authorization token using cURL:</p>\n\n<pre><code>/**\n* Generate a JWT token for future API calls to WordPress\n*/\nprivate function getToken() {\n $ch = curl_init();\n\n curl_setopt($ch, CURLOPT_URL,'https://site.localhost/wp-json/jwt-auth/v1/token');\n curl_setopt($ch, CURLOPT_POST, 1);\n\n # Admin credentials here\n curl_setopt($ch, CURLOPT_POSTFIELDS, \"username=admin&password=Str0ngPass\"); \n\n // receive server response ...\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n\n $server_output = curl_exec ($ch);\n if ($server_output === false) {\n die('Error getting JWT token on WordPress for API integration.');\n }\n $server_output = json_decode($server_output);\n\n if ($server_output === null && json_last_error() !== JSON_ERROR_NONE) {\n die('Invalid response getting JWT token on WordPress for API integration.');\n }\n\n if (!empty($server_output->token)) {\n $this->token = $server_output->token; # Token is here\n curl_close ($ch);\n return true;\n } else {\n die('Invalid response getting JWT token on WordPress for API integration.');\n }\n return false;\n}\n</code></pre>\n\n<p>After that, send your requests with the header: \"Authorization: Bearer $token\"</p>\n\n<p>Where $token is the token returned by the getToken() function above.</p>\n\n<p>I personally use the plugin \"<strong>Disable REST API and Require JWT / OAuth Authentication</strong>\" to restrict API access only with the token above.</p>\n"
}
]
| 2018/04/01 | [
"https://wordpress.stackexchange.com/questions/299548",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140950/"
]
| i am not good in php
but i am using advanced custom fields plugin to improve my web site , now in my website i using about 25 "text" advanced custom fields and 1 "choice - select" advanced custom field
and I also have a plugin like woocommerce it use about 15 custom fields
now i have about 40 custom field for every single post
i am using cache plugin so visitor will not query database but the plugin when it make cache it will query the database
my question is , i am worry about this a lot of custom fields may make performance issues in future when i have a lot of posts
i want your opinion if what i make is good or it will make performance issues ?
thanks alot | **Why JWT authentication**
I'm building a site that uses Wordpress as the back-end, and a React+Redux app as the front-end, so I'm pulling all the content in the front-end by making requests to the Wordpress API. Some requests (mainly, POST requests) must be authenticated, which is when I came across JWT.
**What we need**
To use JWT authentication with Wordpress, we first need to install the [JWT Authentication for WP REST API](https://it.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/) plugin. As is explained in the plugin's instructions, we also need to modify some core Wordpress files. In particular:
In the .htaccess file included in the Wordpress installation's root folder, we need to add the following lines:
```
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
```
In the wp-config.php file, also included in the Wordpress installation's root folder, we need to add these lines:
```
define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key'); // Replace 'your-top-secret-key' with an actual secret key.
define('JWT_AUTH_CORS_ENABLE', true);
```
**Testing to see if JWT is available**
To verify that we can now use JWT, fire up Postman and make a request to the Wordpress API's default 'index':
```
http://example.com/wp-json/
```
A few new endpoints, like `/jwt-auth/v1` and `/jwt-auth/v1/token` should have been added to the API. If you can find them in the response to the above request, it means JWT is now available.
**Getting the JWT token**
Let's stay in Postman for the moment, and let's request a token to the Wordpress API:
```
http://example.com/wp-json/jwt-auth/v1/token
```
The response will contain the JWT token, which is an encrypted key that looks something like this:
>
> eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODg4OFwvZm90b3Jvb20tbmV4dCIsImlhdCI6MTUyMjU5NzQ1MiwibmJmIjoxNTIyNTk3NDUyLCJleHAiOjE1MjMyMDIyNTIsImRhdGEiOnsidXNlciI6eyJpZCI6IjEifX19.hxaaT9iowAX1Xf8RUM42OwbP7QgRNxux8eTtKhWvEUM
>
>
>
**Making an authenticated request**
Let's try to change the title of a post with an ID of 300 as an example of an authenticated request with JWT.
In Postman, choose POST as the method and type the following endpoint:
```
http://example.com/wp-json/wp/v2/posts/300
```
Choose No Auth in the Authorization tab, and add the following in the Headers tab:
```
'Content-type': 'application/json',
'Authorization': 'Bearer jwtToken' // Replace jwtToken with the actual token (the encrypted key above)
```
Finally, in the Body tab, select the raw and JSON (application/json) options, then in the editor right below the options type the following:
```
{ "title": "YES! Authenticated requests with JWT work" }
```
Now you can hit SEND. Look in the response tab with all the data about the post that we requested: the value for the title key should now be `YES! Authenticated requests with JWT work` |
299,569 | <p>I am trying to hack together something in mySQL to allow me to change from one plugin to another without having to do manual data entry for all of my products on my woocommerce store.</p>
<p>The goal is to change every meta_value with the meta_key <strong>_woofv_video_embed</strong> from this format <code>https://youtu.be/JCdljysorMo</code> to this format <code>a:1:{s:3:"url";s:28:"https://youtu.be/JCdljysorMo";}</code> where every product has a different video link that needs to be updated.</p>
<p>I have:</p>
<pre><code>update `wp_postmeta` set `meta_value`= concat( a:1:{s:3:"url";s:28:", meta_value, ";} ) where `meta_key` = '_woofv_video_embed'
</code></pre>
<p>I am trying to use the concatenate function but I need everything except for commas to be a string literal I tried: </p>
<pre><code>update `wp_postmeta` set `meta_value`= concat( 'a:1:{s:3:"url";s:28:"', meta_value, '";'} ) where `meta_key` = '_woofv_video_embed'
</code></pre>
<p>but I still got an error. What do I need to do differently? Also will I need back ticks around meta_value inside the concatenate function? I am new to mySQL so I am just looking at other peoples code but wasn't able to find and example that worked for this specific instance. Any help would be greatly appreciated. I am running this script by using "SQL" within phpMyAdmin if that changes the answer at all.</p>
<p>Thank you</p>
| [
{
"answer_id": 299572,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>Never manipulate the DB directly, instead write some small wordpress plugin to do it. The amount of gotchas when trying to change a serialized data \"by hand\" is ridiculous and the risk do not justify the small amount of time it seems like it will save you.</p>\n"
},
{
"answer_id": 299576,
"author": "nicolai",
"author_id": 140965,
"author_profile": "https://wordpress.stackexchange.com/users/140965",
"pm_score": 1,
"selected": false,
"text": "<p>I misplaced a single quote. This query worked for me and solved my problem.</p>\n\n<p>update <code>wp_postmeta</code> set <code>meta_value</code>= concat( 'a:1:{s:3:\"url\";s:28:\"', <code>meta_value</code>, '\";}' ) where <code>meta_key</code> = '_woofv_video_embed'</p>\n"
}
]
| 2018/04/02 | [
"https://wordpress.stackexchange.com/questions/299569",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140965/"
]
| I am trying to hack together something in mySQL to allow me to change from one plugin to another without having to do manual data entry for all of my products on my woocommerce store.
The goal is to change every meta\_value with the meta\_key **\_woofv\_video\_embed** from this format `https://youtu.be/JCdljysorMo` to this format `a:1:{s:3:"url";s:28:"https://youtu.be/JCdljysorMo";}` where every product has a different video link that needs to be updated.
I have:
```
update `wp_postmeta` set `meta_value`= concat( a:1:{s:3:"url";s:28:", meta_value, ";} ) where `meta_key` = '_woofv_video_embed'
```
I am trying to use the concatenate function but I need everything except for commas to be a string literal I tried:
```
update `wp_postmeta` set `meta_value`= concat( 'a:1:{s:3:"url";s:28:"', meta_value, '";'} ) where `meta_key` = '_woofv_video_embed'
```
but I still got an error. What do I need to do differently? Also will I need back ticks around meta\_value inside the concatenate function? I am new to mySQL so I am just looking at other peoples code but wasn't able to find and example that worked for this specific instance. Any help would be greatly appreciated. I am running this script by using "SQL" within phpMyAdmin if that changes the answer at all.
Thank you | I misplaced a single quote. This query worked for me and solved my problem.
update `wp_postmeta` set `meta_value`= concat( 'a:1:{s:3:"url";s:28:"', `meta_value`, '";}' ) where `meta_key` = '\_woofv\_video\_embed' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.