qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
328,413 | <pre><code><select name="select-city" onchange="location = this.value;">
<option value="">Select a post to read</option>
<?php
if ( is_user_logged_in() ):
global $current_user;
wp_get_current_user();
$author_query = array('posts_per_page' => '-1','author' => $current_user->ID);
$author_posts = new WP_Query($author_query);
$numposts = $count_user_posts( $user_id );
while($author_posts->have_posts()) : $author_posts->the_post();
?>
<option value="<?php the_permalink(); ?>"><?php the_title(); ?></option>
<?php elseif ($numposts == 0):
echo 'You have no posts';
?>
<?php endwhile;
else :
echo '<a href="https://www.mysiteeeee.com/wp-login.php" >Log in</a>';
endif; ?>
</code></pre>
<p></p>
<p>Hello there, I'm trying to make this work but I don't get it. </p>
<p>If user is logged in I get a form dropdown of the posts the user has published. If it has no posts I get the message "You have no posts". And if user is not logged in a link to log in prints. </p>
<p>I don't get it to work with the second part "You have no posts"</p>
<p>What am I doing wrong? Thanks.</p>
| [
{
"answer_id": 328415,
"author": "Fabrizio Mele",
"author_id": 40463,
"author_profile": "https://wordpress.stackexchange.com/users/40463",
"pm_score": 0,
"selected": false,
"text": "<p>You have incorrectly placed your <code>endwhile</code> instruction. You code is entering the while-loop and encountering the <code>elseif</code> outside the <code>if</code> block.</p>\n\n<p>Current code outline (pseudocode):</p>\n\n<pre><code>if :\n while:\n elseif:\n endwhile;\nelse:\nendif;\n\n</code></pre>\n\n<p>Syntactically correct code outline:</p>\n\n<pre><code>if :\n while:\n ...\n endwhile;\nelseif:\nelse:\nendif;\n\n</code></pre>\n\n<p>You would have to move this line: </p>\n\n<pre><code><?php endwhile;\n</code></pre>\n\n<p>just below:</p>\n\n<pre><code><option value=\"<?php the_permalink(); ?>\"><?php the_title(); ?></option>\n</code></pre>\n\n<p><strong>HOWEVER</strong> this will simply not work! The while loop has no else case. I think you want to do something like:</p>\n\n<pre><code><select name=\"select-city\" onchange=\"location = this.value;\">\n<option value=\"\">Select a post to read</option>\n<?php\n if ( is_user_logged_in() ):\n global $current_user;\n wp_get_current_user();\n $author_query = array('posts_per_page' => '-1','author' => $current_user->ID);\n $author_posts = new WP_Query($author_query);\n $numposts = $count_user_posts( $user_id );\n if ($numposts == 0) {\n echo 'You have no posts';\n } else {\n\n while($author_posts->have_posts()) : $author_posts->the_post(); ?>\n<option value=\"<?php the_permalink(); ?>\"><?php the_title(); ?></option>\n<?php endwhile;\n }\n\n else :\n\n echo '<a href=\"https://www.mysiteeeee.com/wp-login.php\" >Log in</a>';\n\n endif; ?>\n</code></pre>\n\n<p>and place the while inside an if-else checking whether the user has posts. <strong>However</strong> this won't fully work, because <code>echo</code>ing inside a <code><select></code> tag won't do nothing. Instead, wrap the select just around the while,open it only if there are posts.</p>\n"
},
{
"answer_id": 328416,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>Let's start with proper indenting your code:</p>\n\n<pre><code><select name=\"select-city\" onchange=\"location = this.value;\">\n <option value=\"\">Select a post to read</option>\n <?php\n if ( is_user_logged_in() ):\n global $current_user;\n wp_get_current_user();\n $author_query = array('posts_per_page' => '-1','author' => $current_user->ID);\n $author_posts = new WP_Query($author_query);\n $numposts = count_user_posts( $user_id ); // <- you can't use $count_user_posts also - it's a function, not a variable\n while ( $author_posts->have_posts() ) :\n $author_posts->the_post();\n ?>\n <option value=\"<?php the_permalink(); ?>\"><?php the_title(); ?></option>\n <?php\n elseif ($numposts == 0) : // <- here's the problem - there is an elseif, but there was no if earlier\n echo 'You have no posts';\n ?>\n <?php endwhile; // <- and here is another problem, because you use endwhile in elseif, but there was no while in that elseif...\n else :\n echo '<a href=\"https://www.mysiteeeee.com/wp-login.php\" >Log in</a>';\n endif; ?>\n</code></pre>\n\n<p>As you can see there clearly is something wrong with that code, because you can't indent it.</p>\n\n<p>So how should that look? It's hard to be certain, but... I'm pretty sure it should be something like this:</p>\n\n<pre><code><?php if ( is_user_logged_in() ): ?>\n <?php\n global $current_user;\n wp_get_current_user();\n $author_query = array('posts_per_page' => '-1','author' => $current_user->ID);\n $author_posts = new WP_Query($author_query);\n $numposts = count_user_posts( $user_id );\n if ( $numposts ) : // if there are posts, then show <select>\n ?>\n <select name=\"select-city\" onchange=\"location = this.value;\">\n <option value=\"\">Select a post to read</option>\n <?php while ( $author_posts->have_posts() ) : $author_posts->the_post(); ?>\n <option value=\"<?php the_permalink(); ?>\"><?php the_title(); ?></option>\n <?php endwhile; ?>\n </select>\n <?php else : // if there are no posts ?>\n You have no posts\n <?php endif; ?>\n<?php else : // you can't show links inside of select, so this is elseif for ( is_user_logged_in() ?>\n <a href=\"https://www.mysiteeeee.com/wp-login.php\" >Log in</a>\n<?php endif; ?>\n</code></pre>\n"
}
] | 2019/02/11 | [
"https://wordpress.stackexchange.com/questions/328413",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28838/"
] | ```
<select name="select-city" onchange="location = this.value;">
<option value="">Select a post to read</option>
<?php
if ( is_user_logged_in() ):
global $current_user;
wp_get_current_user();
$author_query = array('posts_per_page' => '-1','author' => $current_user->ID);
$author_posts = new WP_Query($author_query);
$numposts = $count_user_posts( $user_id );
while($author_posts->have_posts()) : $author_posts->the_post();
?>
<option value="<?php the_permalink(); ?>"><?php the_title(); ?></option>
<?php elseif ($numposts == 0):
echo 'You have no posts';
?>
<?php endwhile;
else :
echo '<a href="https://www.mysiteeeee.com/wp-login.php" >Log in</a>';
endif; ?>
```
Hello there, I'm trying to make this work but I don't get it.
If user is logged in I get a form dropdown of the posts the user has published. If it has no posts I get the message "You have no posts". And if user is not logged in a link to log in prints.
I don't get it to work with the second part "You have no posts"
What am I doing wrong? Thanks. | Let's start with proper indenting your code:
```
<select name="select-city" onchange="location = this.value;">
<option value="">Select a post to read</option>
<?php
if ( is_user_logged_in() ):
global $current_user;
wp_get_current_user();
$author_query = array('posts_per_page' => '-1','author' => $current_user->ID);
$author_posts = new WP_Query($author_query);
$numposts = count_user_posts( $user_id ); // <- you can't use $count_user_posts also - it's a function, not a variable
while ( $author_posts->have_posts() ) :
$author_posts->the_post();
?>
<option value="<?php the_permalink(); ?>"><?php the_title(); ?></option>
<?php
elseif ($numposts == 0) : // <- here's the problem - there is an elseif, but there was no if earlier
echo 'You have no posts';
?>
<?php endwhile; // <- and here is another problem, because you use endwhile in elseif, but there was no while in that elseif...
else :
echo '<a href="https://www.mysiteeeee.com/wp-login.php" >Log in</a>';
endif; ?>
```
As you can see there clearly is something wrong with that code, because you can't indent it.
So how should that look? It's hard to be certain, but... I'm pretty sure it should be something like this:
```
<?php if ( is_user_logged_in() ): ?>
<?php
global $current_user;
wp_get_current_user();
$author_query = array('posts_per_page' => '-1','author' => $current_user->ID);
$author_posts = new WP_Query($author_query);
$numposts = count_user_posts( $user_id );
if ( $numposts ) : // if there are posts, then show <select>
?>
<select name="select-city" onchange="location = this.value;">
<option value="">Select a post to read</option>
<?php while ( $author_posts->have_posts() ) : $author_posts->the_post(); ?>
<option value="<?php the_permalink(); ?>"><?php the_title(); ?></option>
<?php endwhile; ?>
</select>
<?php else : // if there are no posts ?>
You have no posts
<?php endif; ?>
<?php else : // you can't show links inside of select, so this is elseif for ( is_user_logged_in() ?>
<a href="https://www.mysiteeeee.com/wp-login.php" >Log in</a>
<?php endif; ?>
``` |
328,417 | <p>Does anyone know another way to redirect without header(); giving me this error? <code>wp_redirect</code> doesn't work for me either...</p>
<p>This is the error I'm getting:</p>
<blockquote>
<p>Warning: Cannot modify header information - headers already sent by
(output started at
/home/my_site/public_html/wp-content/themes/EHCC/page-secure.php:8) in
/home/my_site/public_html/wp-content/themes/my_theme/template-parts/secure-form.php
on line 8</p>
</blockquote>
<pre><code><?php
ob_start();
if (!empty($_POST['password']))
{
$redirect = ($_POST['password']);
$redirect = str_replace(" ","-",$redirect);
$redirect = strtolower($redirect);
header("Location: /bids/$redirect");
die();
}
else
{
print '
<div class=\'row secureform__container\'>
<form id=\'securedownloads\' class=\'secureform\' method=\'post\' action=\'\'>
<fieldset class=\'secureform__inner\'>
<label for=\'password\' class=\'secureform__label\'>Password:</label>
<input id=\'password\' type=\'text\' name=\'password\' maxlength=\'40\' class=\'secureform__input\'>
<input type=\'submit\' value=\'login\' class=\'secureform__submit\'>
<input type=\'hidden\' name=\'next\' value=\'\'>
</fieldset>
</form>
</div>
';
}
?>
</code></pre>
| [
{
"answer_id": 328420,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>There is no way do perform a redirect, if you already printed anything to the browser. (To make a redirect you have to send proper header to the browser. And headers have to be sent before any output.)</p>\n\n<p>So if you want to perform any redirects, you can't (and shouldn't) put such code directly in template. It should be placed in <code>functions.php</code> and run on some hook.</p>\n\n<p>Also... It's not the best idea to send any form with no action set - it's a security problem. And there is already a mechanism built in WP, that you should use for such requests.</p>\n\n<p>So if you want to do this properly, it may look something like this...</p>\n\n<p>In <code>functions.php</code> file:</p>\n\n<pre><code>function process_my_form() {\n if ( ! empty($_POST['password']) ) {\n $redirect = ($_POST['password']);\n $redirect = str_replace(\" \",\"-\",$redirect);\n $redirect = strtolower($redirect);\n wp_redirect( \"/bids/$redirect\" );\n die;\n }\n\n wp_redirect( '<URL OF YOUR FORM>' ); // redirect back to the form, so replace it with correct URL\n die;\n}\nadd_action( 'admin_post_process_my_form', 'process_my_form' );\nadd_action( 'admin_post_nopriv_process_my_form', 'process_my_form' );\n</code></pre>\n\n<p>And in your template file:</p>\n\n<pre><code><div class='row secureform__container'>\n <form id='securedownloads' class='secureform' method='post' action='<?php echo esc_attr( admin_url('admin-post.php') ); ?>'>\n <fieldset class='secureform__inner'>\n <label for='password' class='secureform__label'>Password:</label>\n <input id='password' type='text' name='password' maxlength='40' class='secureform__input'>\n <input type='submit' value='login' class='secureform__submit'>\n <input type='hidden' name='next' value=''>\n <input type='hidden' name='action' value='process_my_form'>\n </fieldset>\n </form>\n</div>\n</code></pre>\n"
},
{
"answer_id": 354798,
"author": "Arthur Bezner",
"author_id": 179892,
"author_profile": "https://wordpress.stackexchange.com/users/179892",
"pm_score": 1,
"selected": false,
"text": "<p>Try javascript redirection instead. </p>\n\n<pre><code>echo \"<script>location.href = '$redirect_url';</script>\";\n\nexit;\n</code></pre>\n\n<p>Literally saved my live without getting too dirty with WP screwed architecture. </p>\n"
}
] | 2019/02/11 | [
"https://wordpress.stackexchange.com/questions/328417",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/160874/"
] | Does anyone know another way to redirect without header(); giving me this error? `wp_redirect` doesn't work for me either...
This is the error I'm getting:
>
> Warning: Cannot modify header information - headers already sent by
> (output started at
> /home/my\_site/public\_html/wp-content/themes/EHCC/page-secure.php:8) in
> /home/my\_site/public\_html/wp-content/themes/my\_theme/template-parts/secure-form.php
> on line 8
>
>
>
```
<?php
ob_start();
if (!empty($_POST['password']))
{
$redirect = ($_POST['password']);
$redirect = str_replace(" ","-",$redirect);
$redirect = strtolower($redirect);
header("Location: /bids/$redirect");
die();
}
else
{
print '
<div class=\'row secureform__container\'>
<form id=\'securedownloads\' class=\'secureform\' method=\'post\' action=\'\'>
<fieldset class=\'secureform__inner\'>
<label for=\'password\' class=\'secureform__label\'>Password:</label>
<input id=\'password\' type=\'text\' name=\'password\' maxlength=\'40\' class=\'secureform__input\'>
<input type=\'submit\' value=\'login\' class=\'secureform__submit\'>
<input type=\'hidden\' name=\'next\' value=\'\'>
</fieldset>
</form>
</div>
';
}
?>
``` | There is no way do perform a redirect, if you already printed anything to the browser. (To make a redirect you have to send proper header to the browser. And headers have to be sent before any output.)
So if you want to perform any redirects, you can't (and shouldn't) put such code directly in template. It should be placed in `functions.php` and run on some hook.
Also... It's not the best idea to send any form with no action set - it's a security problem. And there is already a mechanism built in WP, that you should use for such requests.
So if you want to do this properly, it may look something like this...
In `functions.php` file:
```
function process_my_form() {
if ( ! empty($_POST['password']) ) {
$redirect = ($_POST['password']);
$redirect = str_replace(" ","-",$redirect);
$redirect = strtolower($redirect);
wp_redirect( "/bids/$redirect" );
die;
}
wp_redirect( '<URL OF YOUR FORM>' ); // redirect back to the form, so replace it with correct URL
die;
}
add_action( 'admin_post_process_my_form', 'process_my_form' );
add_action( 'admin_post_nopriv_process_my_form', 'process_my_form' );
```
And in your template file:
```
<div class='row secureform__container'>
<form id='securedownloads' class='secureform' method='post' action='<?php echo esc_attr( admin_url('admin-post.php') ); ?>'>
<fieldset class='secureform__inner'>
<label for='password' class='secureform__label'>Password:</label>
<input id='password' type='text' name='password' maxlength='40' class='secureform__input'>
<input type='submit' value='login' class='secureform__submit'>
<input type='hidden' name='next' value=''>
<input type='hidden' name='action' value='process_my_form'>
</fieldset>
</form>
</div>
``` |
328,449 | <p>I am able to get articles as RSS feed from below url</p>
<pre><code>http://wordpress_site/blog/feed
</code></pre>
<p>I am also able to get articles from BlogSpot with specific keywords as below</p>
<pre><code>https://www.yourblogname.blogspot.com/feeds/posts/default?q=KEYWORD
</code></pre>
<p>I have tried to get articles from filtering with specific KEYWORD in wordpress blog but I am not able to get. What can be the URL.</p>
<p>I am very much newbie to wordpress.</p>
| [
{
"answer_id": 328455,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>You can modify the list of posts displayed in feed using <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> action. And to target only feeds, you can use <a href=\"https://codex.wordpress.org/Function_Reference/is_feed\" rel=\"nofollow noreferrer\"><code>is_feed</code></a> conditional tag. </p>\n\n<p>So such code can look like this:</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $query ) {\n if ( ! is_admin() && is_feed() && $query->is_main_query() ) {\n if ( isset($_GET['q']) && trim($_GET['q']) ) {\n $query->set( 's', trim($_GET['q']) );\n }\n }\n} );\n</code></pre>\n\n<p>This way you can go to <code>example.com/feed/?q=KEYWORD</code> and you'll get filtered feed (be careful - most browsers are caching feeds, so you'll have to force them to refresh it).</p>\n"
},
{
"answer_id": 328458,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<p>Here's how we can use the builtin public query parameters on feeds:</p>\n\n<p><strong>Query parameter: <code>s</code></strong></p>\n\n<p>We can use the <code>s</code> query parameter on the feed:</p>\n\n<pre><code>https://example.com/feed/?s=KEYWORD\n</code></pre>\n\n<p>This will generate a feed for the keyword on all <em>searchable post types</em>.</p>\n\n<p><strong>Query parameter: <code>post_type</code></strong></p>\n\n<p>We can restrict it to a given <em>post type</em> with:</p>\n\n<pre><code>https://example.com/feed/?s=KEYWORD&post_type=post\n</code></pre>\n\n<p><strong>Query parameter: <code>exact</code></strong></p>\n\n<p>We can also use the <code>exact</code> query search parameter to exactly match the search keyword (no wildcard):</p>\n\n<pre><code>https://example.com/feed/?s=hello+world&post_type=post&exact=1\n</code></pre>\n\n<p><strong>Query parameter: <code>sentence</code></strong></p>\n\n<p>The <code>sentence</code> query search parameter can be used to match the whole keyword sentence (no word split):</p>\n\n<pre><code>https://example.com/feed/?s=hello+world&post_type=post&sentence=1\n</code></pre>\n\n<p><strong>All together:</strong></p>\n\n<pre><code>https://example.com/feed/?s=hello+world&post_type=post&exact=1&sentence=1\n</code></pre>\n"
}
] | 2019/02/12 | [
"https://wordpress.stackexchange.com/questions/328449",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159842/"
] | I am able to get articles as RSS feed from below url
```
http://wordpress_site/blog/feed
```
I am also able to get articles from BlogSpot with specific keywords as below
```
https://www.yourblogname.blogspot.com/feeds/posts/default?q=KEYWORD
```
I have tried to get articles from filtering with specific KEYWORD in wordpress blog but I am not able to get. What can be the URL.
I am very much newbie to wordpress. | You can modify the list of posts displayed in feed using [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) action. And to target only feeds, you can use [`is_feed`](https://codex.wordpress.org/Function_Reference/is_feed) conditional tag.
So such code can look like this:
```
add_action( 'pre_get_posts', function ( $query ) {
if ( ! is_admin() && is_feed() && $query->is_main_query() ) {
if ( isset($_GET['q']) && trim($_GET['q']) ) {
$query->set( 's', trim($_GET['q']) );
}
}
} );
```
This way you can go to `example.com/feed/?q=KEYWORD` and you'll get filtered feed (be careful - most browsers are caching feeds, so you'll have to force them to refresh it). |
328,459 | <p>Is there any documentation showing the names of the Gutenberg block icons within the WordPress docs? </p>
<p><a href="https://i.stack.imgur.com/IWsrs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IWsrs.png" alt="Gutenberg block icons"></a></p>
<p>To give you some context, I'm using <a href="https://www.advancedcustomfields.com/blog/acf-5-8-introducing-acf-blocks-for-gutenberg/" rel="noreferrer">ACF blocks for Gutenberg</a>, and need to find a reference for <code>'icon'</code>.</p>
<pre><code>add_action('acf/init', 'my_acf_init');
function my_acf_init() {
// check function exists
if( function_exists('acf_register_block') ) {
// register a testimonial block
acf_register_block(array(
'name' => 'testimonial',
'title' => __('Testimonial'),
'description' => __('A custom testimonial block.'),
'render_callback' => 'my_acf_block_render_callback',
'category' => 'formatting',
'icon' => 'admin-comments',
'keywords' => array( 'testimonial', 'quote' ),
));
}
}
</code></pre>
| [
{
"answer_id": 328461,
"author": "moped",
"author_id": 160324,
"author_profile": "https://wordpress.stackexchange.com/users/160324",
"pm_score": 5,
"selected": true,
"text": "<p>Gutenberg is making use of dashicons. <br />\nYou can find your example icon <a href=\"https://developer.wordpress.org/resource/dashicons/#admin-comments\" rel=\"noreferrer\">here</a>, and a cheat sheet of dashicons <a href=\"https://developer.wordpress.org/resource/dashicons/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 363595,
"author": "uryga",
"author_id": 184541,
"author_profile": "https://wordpress.stackexchange.com/users/184541",
"pm_score": 1,
"selected": false,
"text": "<p>i'd be happy to be corrected on this, but it seems like only dashicons can be used \"by name\" in this way – Gutenberg's icons seem to live as inline HTML (JSX) in .js files (<a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/icons/src/library\" rel=\"nofollow noreferrer\">gutenberg/packages/icons/src/library</a>) so i don't think they can be used from PHP.</p>\n\n<p>If you're looking for the actual icons, a lot of them seem to be <a href=\"https://material.io/resources/icons/?style=outline\" rel=\"nofollow noreferrer\">Material UI icons</a>. e.g. the Image block's icon and the pencil from the top bar:</p>\n\n<p><a href=\"https://i.stack.imgur.com/k0LGT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/k0LGT.png\" alt=\"material design "Photo" icon\"></a> <a href=\"https://i.stack.imgur.com/bc9GC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bc9GC.png\" alt=\"material design "Create" icon\"></a></p>\n\n<p>so you could use those instead, or just copy the SVG you want from the github repo. but either way you're going to have to wrangle some SVGs manually</p>\n"
},
{
"answer_id": 364789,
"author": "Jules",
"author_id": 5986,
"author_profile": "https://wordpress.stackexchange.com/users/5986",
"pm_score": 5,
"selected": false,
"text": "<p>Here you can find a list of all the Gutenberg icons with name and preview: <a href=\"https://wordpress.github.io/gutenberg/?path=/story/icons-icon--library\" rel=\"noreferrer\">https://wordpress.github.io/gutenberg/?path=/story/icons-icon--library</a></p>\n<p>In order to use this, you'll need to copy the actual SVG source code.</p>\n<hr />\n<p><strong>Example: register an ACF block with the postExcerpt icon</strong></p>\n<img src=\"https://i.stack.imgur.com/7AsJj.png\" width=\"250\" />\n<p>You'll need to inspect the actual element and extract the source code of the SVG icon from <a href=\"https://wordpress.github.io/gutenberg/?path=/story/icons-icon--library\" rel=\"noreferrer\">https://wordpress.github.io/gutenberg/?path=/story/icons-icon--library</a>:</p>\n<pre><code><svg><path d="M12.75 9.333c0 .521-.102.977-.327 1.354-.23.386-.555.628-.893.774-.545.234-1.183.227-1.544.222l-.12-.001v-1.5h.123c.414.001.715.002.948-.099a.395.395 0 00.199-.166c.05-.083.114-.253.114-.584V7.2H8.8V4h3.95v5.333zM7.95 9.333c0 .521-.102.977-.327 1.354-.23.386-.555.628-.893.774-.545.234-1.183.227-1.544.222l-.12-.001v-1.5h.123c.414.001.715.002.948-.099a.394.394 0 00.198-.166c.05-.083.115-.253.115-.584V7.2H4V4h3.95v5.333zM13 20H4v-1.5h9V20zM20 16H4v-1.5h16V16z"></path></svg>\n</code></pre>\n<p>Then, you can register your block like this:</p>\n<pre><code>add_action('acf/init', 'my_acf_blocks_init');\nfunction my_acf_blocks_init() {\n\n // Check function exists.\n if( function_exists('acf_register_block_type') ) {\n\n // Register a testimonial block.\n acf_register_block_type(array(\n 'name' => 'testimonial',\n 'title' => __('Testimonial'),\n 'description' => __('A custom testimonial block.'),\n 'render_template' => 'template-parts/blocks/testimonial/testimonial.php',\n 'category' => 'formatting',\n 'icon' => '<svg><path d="M12.75 9.333c0 .521-.102.977-.327 1.354-.23.386-.555.628-.893.774-.545.234-1.183.227-1.544.222l-.12-.001v-1.5h.123c.414.001.715.002.948-.099a.395.395 0 00.199-.166c.05-.083.114-.253.114-.584V7.2H8.8V4h3.95v5.333zM7.95 9.333c0 .521-.102.977-.327 1.354-.23.386-.555.628-.893.774-.545.234-1.183.227-1.544.222l-.12-.001v-1.5h.123c.414.001.715.002.948-.099a.394.394 0 00.198-.166c.05-.083.115-.253.115-.584V7.2H4V4h3.95v5.333zM13 20H4v-1.5h9V20zM20 16H4v-1.5h16V16z"></path></svg>'\n ));\n }\n}\n</code></pre>\n<p><strong>Result:</strong></p>\n<img src=\"https://i.stack.imgur.com/s0Du7.png\" width=\"250\" />\n<p>More information about ACF blocks at <a href=\"https://www.advancedcustomfields.com/resources/acf_register_block_type/\" rel=\"noreferrer\">https://www.advancedcustomfields.com/resources/acf_register_block_type/</a></p>\n"
},
{
"answer_id": 373931,
"author": "Lik Core",
"author_id": 193848,
"author_profile": "https://wordpress.stackexchange.com/users/193848",
"pm_score": -1,
"selected": false,
"text": "<p>If you need Gutenberg Icon block you can use this plugin <a href=\"https://wordpress.org/plugins/kiticon-icon-block/\" rel=\"nofollow noreferrer\">kitIcon</a>\nas i see this icon block have svg icon maybe over 1000+icon here\nwith icon block. plugin name is <a href=\"https://wordpress.org/plugins/kiticon-icon-block/\" rel=\"nofollow noreferrer\">KitIcon WordPress Gutenberg Icon Block.</a></p>\n<p>may be its help you</p>\n"
},
{
"answer_id": 384160,
"author": "user3892612",
"author_id": 202574,
"author_profile": "https://wordpress.stackexchange.com/users/202574",
"pm_score": -1,
"selected": false,
"text": "<p>Official icon font of the WordPress admin as of 3.8.</p>\n<p><a href=\"https://developer.wordpress.org/resource/dashicons/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/resource/dashicons/</a></p>\n"
}
] | 2019/02/12 | [
"https://wordpress.stackexchange.com/questions/328459",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37548/"
] | Is there any documentation showing the names of the Gutenberg block icons within the WordPress docs?
[](https://i.stack.imgur.com/IWsrs.png)
To give you some context, I'm using [ACF blocks for Gutenberg](https://www.advancedcustomfields.com/blog/acf-5-8-introducing-acf-blocks-for-gutenberg/), and need to find a reference for `'icon'`.
```
add_action('acf/init', 'my_acf_init');
function my_acf_init() {
// check function exists
if( function_exists('acf_register_block') ) {
// register a testimonial block
acf_register_block(array(
'name' => 'testimonial',
'title' => __('Testimonial'),
'description' => __('A custom testimonial block.'),
'render_callback' => 'my_acf_block_render_callback',
'category' => 'formatting',
'icon' => 'admin-comments',
'keywords' => array( 'testimonial', 'quote' ),
));
}
}
``` | Gutenberg is making use of dashicons.
You can find your example icon [here](https://developer.wordpress.org/resource/dashicons/#admin-comments), and a cheat sheet of dashicons [here](https://developer.wordpress.org/resource/dashicons/). |
328,477 | <p>I want to be able to hide the 'My account' button when users are logged out and I want to be able to hide the 'Registration' button when users are logged in. </p>
<p>How would I go about doing this? I'm still a amatuer at WordPress and I'm still learning, this is what I have so far in my nav-menus.php file.</p>
<pre><code>if( is_user_logged_in() ) {
wp_nav_menu( array( 'My Account' => 'logged-users' ) );
} else {
wp_nav_menu( array( 'Registration' => 'not-logged-users' ) );
}
</code></pre>
<p>I know this isn't correct, but I would love some help with it, please let me know if I'm missing any information.</p>
<p><a href="https://i.stack.imgur.com/tcm1Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tcm1Z.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 334411,
"author": "Wade John Beckett",
"author_id": 116893,
"author_profile": "https://wordpress.stackexchange.com/users/116893",
"pm_score": 0,
"selected": false,
"text": "<p>These are the plugins I use most often to show/hide menu items based on user role or weather the user is logged in or out:</p>\n\n<p><a href=\"https://wordpress.org/plugins/user-menus/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/user-menus/</a> - Simple and intuitive.</p>\n\n<p><a href=\"https://wordpress.org/plugins/conditional-menus/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/conditional-menus/</a> - For more advanced conditions and flexibility.</p>\n\n<p>I also just found this one:</p>\n\n<p><a href=\"https://wordpress.org/plugins/if-menu/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/if-menu/</a> - I have not tested it but it has better reviews and was updated more recently than my first suggestion.</p>\n"
},
{
"answer_id": 381165,
"author": "Timothy M",
"author_id": 200068,
"author_profile": "https://wordpress.stackexchange.com/users/200068",
"pm_score": 1,
"selected": false,
"text": "<p>I should suggest a custom walker to, not that hard at all.</p>\n<p>starting with:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/</a></p>\n<p>in the foreach loop you are able to check based on title.</p>\n<p>in this part you will use:\n<a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/is_user_logged_in/</a></p>\n<pre><code>foreach($nav_items as $item): \nif($item->title == 'Register'):\nif(is_user_logged_in()):\n//Do your thing when logged in\nelse:\n//Do your thing when not logged in\nendif;\nendif;\n\nendforeach;\n</code></pre>\n<p>Above is an example, there are multiple ways you can do this :) hope it helps you</p>\n"
}
] | 2019/02/12 | [
"https://wordpress.stackexchange.com/questions/328477",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I want to be able to hide the 'My account' button when users are logged out and I want to be able to hide the 'Registration' button when users are logged in.
How would I go about doing this? I'm still a amatuer at WordPress and I'm still learning, this is what I have so far in my nav-menus.php file.
```
if( is_user_logged_in() ) {
wp_nav_menu( array( 'My Account' => 'logged-users' ) );
} else {
wp_nav_menu( array( 'Registration' => 'not-logged-users' ) );
}
```
I know this isn't correct, but I would love some help with it, please let me know if I'm missing any information.
[](https://i.stack.imgur.com/tcm1Z.png) | I should suggest a custom walker to, not that hard at all.
starting with:
<https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/>
in the foreach loop you are able to check based on title.
in this part you will use:
<https://developer.wordpress.org/reference/functions/is_user_logged_in/>
```
foreach($nav_items as $item):
if($item->title == 'Register'):
if(is_user_logged_in()):
//Do your thing when logged in
else:
//Do your thing when not logged in
endif;
endif;
endforeach;
```
Above is an example, there are multiple ways you can do this :) hope it helps you |
328,536 | <p>Assuming I have no infinite scroll or anything else going on in my theme:
Is there a way to enqueue my custom Gutenberg block styles and scripts so they are only (lazy) loaded in the front-end when the block is really used? Something like <code>is_active_widget</code>, just for blocks?</p>
<p>If I enqueue them inside a <code>enqueue_block_assets</code> function they're added to any site.</p>
<p>On github, I found this <a href="https://github.com/WordPress/gutenberg/issues/5445" rel="noreferrer">https://github.com/WordPress/gutenberg/issues/5445</a> , but it sounds like it's more on bundling than conditional load, so I still hope they didn't leave that optimization opportunity out - otherwise any other site will soon be junked with 20 additional scripts from numerous Gutenberg block plugins people install and only use once on a page (think of large image gallery block scripts for example).</p>
<p>Thanks & Regards!</p>
| [
{
"answer_id": 328553,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 4,
"selected": false,
"text": "<p>Well, the styles and scripts you register in your php register_block_type call should only be loaded when the block is in use if i recall correctly.</p>\n\n<p>If you want to load additional scripts or styles to be enqueued only if there is a block of type \"my-awesome/block-type\", you can use the has_block function in your wp_enqueue_scripts function like this:</p>\n\n<pre><code>add_action('wp_enqueue_scripts','enqueue_if_block_is_present');\n\nfunction enqueue_if_block_is_present(){\n if(is_singular()){\n //We only want the script if it's a singular page\n $id = get_the_ID();\n if(has_block('my-awesome/block-type',$id)){\n wp_enqueue_script('my-awesome-script',$path_of_script,$needed_scripts,$version_of_script,$load_in_footer);\n }\n }\n}\n</code></pre>\n\n<p>If you also want the script to be loaded on multiple views as well (like category archive or the blog page), you can hook into the the_content filter and enqueue the script there:</p>\n\n<pre><code>add_filter('the_content','enqueue_my_awesome_script_if_there_is_block');\n\nfunction enqueue_my_awesome_script_if_there_is_block($content = \"\"){\n if(has_block('my-awesome/block-type')){\n wp_enqueue_script('my-awesome-script',$path_of_script,$needed_scripts,$version_of_script,true);\n //Be aware that for this to work, the load_in_footer MUST be set to true, as \n //the scripts for the header are already echoed out at this point\n }\n return $content;\n}\n</code></pre>\n\n<p>Happy Coding!</p>\n"
},
{
"answer_id": 328582,
"author": "user127091",
"author_id": 147050,
"author_profile": "https://wordpress.stackexchange.com/users/147050",
"pm_score": 4,
"selected": true,
"text": "<p>Thanks @kuchenundkakao for pointing me into the right direction. I'm still answering my own question as I want to give some more context for others that may stumble upon this.</p>\n\n<p>So, there are several ways to load your custom blocks, mainly:</p>\n\n<ul>\n<li><code>add_action('enqueue_block_assets','xy_function')</code> / <code>add_action('enqueue_block_editor_assets','xy_function')</code>, which at the\nmoment is the default when creating a block with\n\"create_guten_block\". This is what I was using. It might change, see\n<a href=\"https://github.com/ahmadawais/create-guten-block/issues/21\" rel=\"noreferrer\">https://github.com/ahmadawais/create-guten-block/issues/21</a></li>\n<li><code>register_block_type</code> as per the handbook, see <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/block-tutorial/writing-your-first-block-type/#enqueuing-block-scripts\" rel=\"noreferrer\">https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/block-tutorial/writing-your-first-block-type/#enqueuing-block-scripts</a></li>\n</ul>\n\n<p>While registering the block in PHP (like described in the handbook) is the default method and future proof, the <code>enqueue_block_assets</code> variant can load multiple blocks without the need to split your blocks into seperate files and define them again in PHP. \"create_guten_block\" for example merges any number of blocks into three files by default (blocks.build.js, blocks.editor.build.css and block.style.build.css).</p>\n\n<p>Both ways do <strong>not</strong> conditionally load styles (yet).</p>\n\n<p>When using the create_guten_block method, <code>enqueue_block_assets</code>, and only having a single block defined (or set up to split the files per block), the conditional loading can be added using <code>has_block</code>:</p>\n\n<pre><code> function my_awesome_blocks_cgb_block_assets() {\n if (is_singular()) {\n $id = get_the_ID();\n if (has_block('my-awesome/block-type', $id)) {\n wp_enqueue_style(\n 'my-awesome_blocks-cgb-style-css',\n plugins_url( 'blocks/dist/blocks.style.build.css', __FILE__ ),\n );\n }\n }\n }\n add_action( 'enqueue_block_assets', 'my_awesome_blocks_cgb_block_assets' );\n</code></pre>\n\n<p>You can combine register and conditional loading by leaving out the style / script parts in the register and load the according fontend files with enqueue_block_assets as in the code above.</p>\n\n<p>The future proof method will be using <code>register_block_type</code>, as the <code>script</code> and <code>style</code> fields of it will most likely be used if conditional loading is ever implemented natively (see comment <a href=\"https://github.com/WordPress/gutenberg/issues/11231\" rel=\"noreferrer\">here</a>).</p>\n"
},
{
"answer_id": 366739,
"author": "Ian Dunn",
"author_id": 3898,
"author_profile": "https://wordpress.stackexchange.com/users/3898",
"pm_score": 3,
"selected": false,
"text": "<p>Another way is to <a href=\"https://mkaz.blog/wordpress/conditionally-load-block-assets-part-2/\" rel=\"noreferrer\">enqueue them inside the block's <code>render_callback()</code> function</a>.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>register_block_type( 'mkaz/test-block', array(\n 'editor_script' => 'mkaz-test-block-script',\n 'render_callback' => function( $attribs, $content ) {\n wp_enqueue_script( 'mkaz-test-block-client-asset' );\n return $content;\n }\n) );\n</code></pre>\n\n<p>In the past it was invalid to enqueue stylesheets outside of <code><head></code>, but that's supported by the spec now.</p>\n\n<p>x-ref: <a href=\"https://github.com/WordPress/gutenberg/issues/21838\" rel=\"noreferrer\">https://github.com/WordPress/gutenberg/issues/21838</a></p>\n"
}
] | 2019/02/13 | [
"https://wordpress.stackexchange.com/questions/328536",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147050/"
] | Assuming I have no infinite scroll or anything else going on in my theme:
Is there a way to enqueue my custom Gutenberg block styles and scripts so they are only (lazy) loaded in the front-end when the block is really used? Something like `is_active_widget`, just for blocks?
If I enqueue them inside a `enqueue_block_assets` function they're added to any site.
On github, I found this <https://github.com/WordPress/gutenberg/issues/5445> , but it sounds like it's more on bundling than conditional load, so I still hope they didn't leave that optimization opportunity out - otherwise any other site will soon be junked with 20 additional scripts from numerous Gutenberg block plugins people install and only use once on a page (think of large image gallery block scripts for example).
Thanks & Regards! | Thanks @kuchenundkakao for pointing me into the right direction. I'm still answering my own question as I want to give some more context for others that may stumble upon this.
So, there are several ways to load your custom blocks, mainly:
* `add_action('enqueue_block_assets','xy_function')` / `add_action('enqueue_block_editor_assets','xy_function')`, which at the
moment is the default when creating a block with
"create\_guten\_block". This is what I was using. It might change, see
<https://github.com/ahmadawais/create-guten-block/issues/21>
* `register_block_type` as per the handbook, see <https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/block-tutorial/writing-your-first-block-type/#enqueuing-block-scripts>
While registering the block in PHP (like described in the handbook) is the default method and future proof, the `enqueue_block_assets` variant can load multiple blocks without the need to split your blocks into seperate files and define them again in PHP. "create\_guten\_block" for example merges any number of blocks into three files by default (blocks.build.js, blocks.editor.build.css and block.style.build.css).
Both ways do **not** conditionally load styles (yet).
When using the create\_guten\_block method, `enqueue_block_assets`, and only having a single block defined (or set up to split the files per block), the conditional loading can be added using `has_block`:
```
function my_awesome_blocks_cgb_block_assets() {
if (is_singular()) {
$id = get_the_ID();
if (has_block('my-awesome/block-type', $id)) {
wp_enqueue_style(
'my-awesome_blocks-cgb-style-css',
plugins_url( 'blocks/dist/blocks.style.build.css', __FILE__ ),
);
}
}
}
add_action( 'enqueue_block_assets', 'my_awesome_blocks_cgb_block_assets' );
```
You can combine register and conditional loading by leaving out the style / script parts in the register and load the according fontend files with enqueue\_block\_assets as in the code above.
The future proof method will be using `register_block_type`, as the `script` and `style` fields of it will most likely be used if conditional loading is ever implemented natively (see comment [here](https://github.com/WordPress/gutenberg/issues/11231)). |
328,590 | <p>I was trying to redirect my homepage to random blog post in WordPress.</p>
<p>My aim is to redirect my viewers to random blog posts whenever they enter into my website. I couldn't find a proper solution, can anyone help me?</p>
| [
{
"answer_id": 328591,
"author": "Sam",
"author_id": 37548,
"author_profile": "https://wordpress.stackexchange.com/users/37548",
"pm_score": 0,
"selected": false,
"text": "<p>The quickest way to achieve this is to install the <a href=\"https://wordpress.org/plugins/redirect-url-to-post/\" rel=\"nofollow noreferrer\">Redirect URL to Post</a> plugin.</p>\n\n<p>Via the query parameter, you can configure the homepage to load your latest post or a random one.</p>\n\n<p>For example, your new homepage URL would be <code>http://www.example.com/?redirect_to=random</code></p>\n\n<p>You would likely need to change your home and site URL via WordPress settings. You can read more about this <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 328592,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to use a plugin. You could put the re-direct directly into your .htaccess (on an apache server):</p>\n\n<p>Place this code at the bottom of the .htaccess file:</p>\n\n<pre><code>redirect 301 / http://www.example.com/your-post-slug\n</code></pre>\n\n<p>make sure to change the url to the full url of your blog post.</p>\n\n<p>If you don't have access to your .htaccess you could also do this in your cPanel (or other hosting control panel if you have one)</p>\n"
},
{
"answer_id": 328593,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>template_redirect</code> hook for that:</p>\n\n<pre><code>function my_page_template_redirect() {\n if ( is_home() ) { // change to is_frontpage(), if you use static page as front page\n $posts = get_posts( array(\n 'post_type' => 'post',\n 'orderby' => 'rand',\n 'numberposts' => 1\n ) );\n if ( ! empty( $posts ) ) {\n wp_redirect( get_permalink( $posts[0]->ID) );\n die;\n }\n }\n}\nadd_action( 'template_redirect', 'my_page_template_redirect' );\n</code></pre>\n"
}
] | 2019/02/13 | [
"https://wordpress.stackexchange.com/questions/328590",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161143/"
] | I was trying to redirect my homepage to random blog post in WordPress.
My aim is to redirect my viewers to random blog posts whenever they enter into my website. I couldn't find a proper solution, can anyone help me? | If you don't want to use a plugin. You could put the re-direct directly into your .htaccess (on an apache server):
Place this code at the bottom of the .htaccess file:
```
redirect 301 / http://www.example.com/your-post-slug
```
make sure to change the url to the full url of your blog post.
If you don't have access to your .htaccess you could also do this in your cPanel (or other hosting control panel if you have one) |
328,665 | <p>I am tried to display all product category with bellow function .. getting a error Invalid taxonomy .. it's was working fine last 2 installation.. </p>
<pre><code> function be_woocommerce_category_id(){
$categories_array = array();
$categories_array[0] = esc_html__('Choose a Category', 'shopstore');
$args = array(
'orderby' => 'title',
'order' => 'ASC',
);
$categories = get_terms( 'product_cat', $args );
if( count($categories) > 0 ){
foreach( $categories as $category ){
$categories_array[$category->term_id] = $category->name;
}
}
return $categories_array;
}
</code></pre>
| [
{
"answer_id": 328591,
"author": "Sam",
"author_id": 37548,
"author_profile": "https://wordpress.stackexchange.com/users/37548",
"pm_score": 0,
"selected": false,
"text": "<p>The quickest way to achieve this is to install the <a href=\"https://wordpress.org/plugins/redirect-url-to-post/\" rel=\"nofollow noreferrer\">Redirect URL to Post</a> plugin.</p>\n\n<p>Via the query parameter, you can configure the homepage to load your latest post or a random one.</p>\n\n<p>For example, your new homepage URL would be <code>http://www.example.com/?redirect_to=random</code></p>\n\n<p>You would likely need to change your home and site URL via WordPress settings. You can read more about this <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 328592,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to use a plugin. You could put the re-direct directly into your .htaccess (on an apache server):</p>\n\n<p>Place this code at the bottom of the .htaccess file:</p>\n\n<pre><code>redirect 301 / http://www.example.com/your-post-slug\n</code></pre>\n\n<p>make sure to change the url to the full url of your blog post.</p>\n\n<p>If you don't have access to your .htaccess you could also do this in your cPanel (or other hosting control panel if you have one)</p>\n"
},
{
"answer_id": 328593,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>template_redirect</code> hook for that:</p>\n\n<pre><code>function my_page_template_redirect() {\n if ( is_home() ) { // change to is_frontpage(), if you use static page as front page\n $posts = get_posts( array(\n 'post_type' => 'post',\n 'orderby' => 'rand',\n 'numberposts' => 1\n ) );\n if ( ! empty( $posts ) ) {\n wp_redirect( get_permalink( $posts[0]->ID) );\n die;\n }\n }\n}\nadd_action( 'template_redirect', 'my_page_template_redirect' );\n</code></pre>\n"
}
] | 2019/02/14 | [
"https://wordpress.stackexchange.com/questions/328665",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83449/"
] | I am tried to display all product category with bellow function .. getting a error Invalid taxonomy .. it's was working fine last 2 installation..
```
function be_woocommerce_category_id(){
$categories_array = array();
$categories_array[0] = esc_html__('Choose a Category', 'shopstore');
$args = array(
'orderby' => 'title',
'order' => 'ASC',
);
$categories = get_terms( 'product_cat', $args );
if( count($categories) > 0 ){
foreach( $categories as $category ){
$categories_array[$category->term_id] = $category->name;
}
}
return $categories_array;
}
``` | If you don't want to use a plugin. You could put the re-direct directly into your .htaccess (on an apache server):
Place this code at the bottom of the .htaccess file:
```
redirect 301 / http://www.example.com/your-post-slug
```
make sure to change the url to the full url of your blog post.
If you don't have access to your .htaccess you could also do this in your cPanel (or other hosting control panel if you have one) |
328,685 | <p>On the taxonomy-{name}.php template for my "Organisation" taxonomy, I am currently showing a limited number of posts, grouped for each term of taxonomy "Format".</p>
<p>Where the number of available posts exceeds that which is displayable, I now want to enable AJAX-based loading of more posts.</p>
<p>I have followed countless tutorials and StackExchange questions on this topic, but something is still not clicking. For example, I implemented <a href="https://rudrastyh.com/wordpress/load-more-posts-ajax.html" rel="nofollow noreferrer">Misha Rudrastyh's "Load More" button</a>, but the code just would not load any posts. I am lost and on the verge of giving up.</p>
<p>I have a post block with a "More" link like this, ready and waiting...</p>
<p><a href="https://i.stack.imgur.com/SWOJa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SWOJa.png" alt="enter image description here"></a></p>
<p>That corresponds to posts of "Format" taxonomy term "executive" for one taxonomy "Organisation" term. Here is the relevant portion of taxonomy-organisation.php, containing my query...</p>
<pre><code> <?php
// This will output posts in blocks for each "Format" taxonomy term.
// But we also want to use this loop to output posts *without* a "Format" taxonomy term.
$formats = array("interview","executive","analyst","oped","","ma","earnings","financialanalysis","ipo","marketindicators","industrymoves");
foreach ($formats as $format) {
// Term of the slug above
$format_term = get_term_by('slug', $format, "format");
// Formulate the secondary tax_query for "format" with some conditionality
/* *********************************** */
/* Posts by Format */
/* *********************************** */
if (!empty($format)) {
$posts_per_page = 8;
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $format_term->slug,
'include_children' => false
);
// Oh, and set a title for output below
$section_title = $format_term->name;
/* *********************************** */
/* Format without Format */
/* *********************************** */
} elseif (empty($format)) {
$posts_per_page = 12;
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'operator' => 'NOT EXISTS', // or 'EXISTS'
);
// Oh, and set a title for output below
$section_title = 'Reporting';
}
// Query posts
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
// pagination
// 'nopaging' => false,
'posts_per_page' => $posts_per_page,
// 'offset' => '4',
// 'paged' => $paged,
// posts
'post_type' => array( 'article', 'viewpoint' ),
// order
'orderby' => 'date',
'order' => 'DESC',
// taxonomy
'tax_query' => array(
array(
'taxonomy' => 'company', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $organisation->slug,
'include_children' => false
),
$tax_q_format_array
),
);
// the query
$posts_org = new WP_Query($args);
if ( $posts_org->have_posts() ) { ?>
<h5 class="mt-0 pt-2 pb-3 text-secondary"><?php echo $section_title; ?> <span class="badge badge-secondary badge-pill"><?php echo $posts_org->found_posts; ?></span></h5>
<div class="row pb-3">
<?php
while( $posts_org->have_posts() ) {
$posts_org->the_post();
get_template_part('partials/loops/col', 'vertical');
}
if ($posts_org->found_posts > $posts_per_page) {
echo '<p class="text-secondary pl-3 pb-0 load_more" style="opacity: 0.6"><i class="fas fa-plus-circle"></i> More</p>';
}
echo '</div>';
wp_reset_postdata(); // reset the query
} else {
// echo '<div class="col"><p>'.__('Sorry, no posts matched your criteria.').'</p></div>';
} // end if have_posts
}
?>
</code></pre>
<p>And here is the include file used by <code>get_template_part</code> to output post item thumbnails and links...</p>
<pre><code> <?php
// Get fallback image if needed
@require(dirname(__FILE__).'/../source_thumbnail_fallback.php');
// @ Suppress "Notices" generated when post has no source set (ie no source at array position [0])
?>
<div class="col-sm-6 col-md-4 col-lg-3 col-xl-2 post-item overlay-bg <?php echo $display_class; ?>">
<a href="<?php the_field( 'source_url' ); ?>" class="text-dark" target="_blank">
<img src="http://www.myserver.com/to/image/location/<?php echo $source_image_url; ?>" class="img-fluid rounded mb-2">
<p><?php the_title(); ?></p>
<?php
//Do something if a specific array value exists within a post
$format_terms = wp_get_post_terms($post->ID, 'format', array("fields" => "all"));
// foreach($format_terms as $format_single) { ?>
<span class="badge <?php get_format_badge_colour_class($format_terms[0]->term_id); ?> font-weight-normal mr-2 overlay-content"><?php echo $format_terms[0]->name; ?></span>
<?php // } ?>
</a>
</div>
</code></pre>
<p>From the tutorials and questions, I have gleaned that the process seems to be...</p>
<ul>
<li>Register/enqueue/localise a Javascript file containing the relevant code, and pass parameters to it from PHP functions.php</li>
<li>Some sort of WordPress AJAX handler in functions.php which does a WP_Query for more posts?</li>
</ul>
<p>But I am just not understanding how to implement in my situation.</p>
<p>FYI, my self-built theme is based on Bootstrap and, until now, I have de-registered WordPress' built-in <code>jquery</code>, replaced by enqueuing Bootstrap's recommended <code>https://code.jquery.com/jquery-3.3.1.slim.min.js</code> as <code>jQuery</code>. I'm not sure which is the right option, it seemed like this has a bearing on WP_Ajax_*.</p>
<p>I'm aware a similar question has been asked before, but my query seems unique and many questions/answers seem also to refer to unique situations, ie. offering answers specifically designed to work with twentyfifteen theme.</p>
<h1>Update (Feb 15, 2019):</h1>
<p>I have come a long way toward solving this, using a combination of:</p>
<ul>
<li><a href="https://artisansweb.net/load-wordpress-post-ajax/" rel="nofollow noreferrer">Artisans Web tutorial</a> for the basic concept</li>
<li><a href="https://wordpress.stackexchange.com/a/328760/39300">Anti's suggestion</a> for establishing <em>which</em> of multiple "More" links was clicked (necessary to feed unique arguments back to looped WP queries).</li>
<li>Further research/exploration based on available code, to learn how to take and pass those variables.</li>
<li>Further jQuery research to learn how to change UI elements.</li>
</ul>
<p>I can now share the following two pieces of code, which works 90% well and I could consider offering this as an answer, or Anti's answer.</p>
<h2>Theme template fragment:</h2>
<pre><code> <?php
$organisation = get_query_var('organisation');
$org_id_prefixed = get_query_var('org_id_prefixed');
?>
<?php
/* ************************************************************************************************************** */
/* */
/* LIST POSTS BY FORMAT TERM, WITH DYNAMIC AJAX MORE-POST LOADING */
/* */
/* Outline: */
/* This will output posts in blocks for each "Format" taxonomy term. */
/* But we also want to use this loop to output posts *without* a "Format" taxonomy term. */
/* >> Method via Sajid @ Artisans Web, https://artisansweb.net/load-wordpress-post-ajax/ */
/* */
/* Dynamic: */
/* 1. Javascript: When "More" link is clicked */
/* 2. Send current "organisation", clicked "format" and "page" as variables to function */
/* 3. PHP: Do WP query for next page of posts, return to javascript */
/* 4. Javascript: Append results to the clicked container */
/* */
/* Dynamic method: */
/* $format used as ID for i) .row .my-posts container and ii) .loadmore link, so that we know: */
/* a) Which "Load more" link was clicked */
/* b) Which box to return new output to */
/* >> Help via Antti Koskinen @ StackOverflow, https://wordpress.stackexchange.com/a/328760/39300 */
/* */
/* ************************************************************************************************************** */
// Specify which "Format" terms we want to display post blocks for
// ("reporting" here is a wildcard, used to accommodate posts without a "Format" term set)
$formats = array("interview","executive","analyst","oped","reporting","ma","earnings","financialanalysis","ipo","marketindicators","industrymoves");
// For each of them,
foreach ($formats as $format) {
// 1. Get actual term of the slug above
$format_term = get_term_by('slug', $format, "format");
// 2. Formulate the secondary tax_query for "format" with some conditionality
/* *********************************** */
/* Posts by Format? */
/* *********************************** */
if ($format!="reporting") {
// $posts_per_page = 8;
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $format_term->slug,
'include_children' => false
);
// Oh, and set a title for output below
$section_title = $format_term->name;
/* *********************************** */
/* Format without Format? */
/* *********************************** */
} elseif ($format=="reporting") {
// $posts_per_page = 12;
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'operator' => 'NOT EXISTS', // or 'EXISTS'
);
// Oh, and set a title for output below
$section_title = 'Reporting';
}
// 3. Set query arguments
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
// pagination
// 'nopaging' => false,
'posts_per_page' => '8', // $posts_per_page,
// 'offset' => '4',
'paged' => $paged,
// posts
'post_type' => array( 'article', 'viewpoint' ),
// order
'orderby' => 'date',
'order' => 'DESC',
// taxonomy
'tax_query' => array(
// #1 Organisation: the current one
array(
'taxonomy' => 'company', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $organisation->slug,
'include_children' => false
),
// #2 Format: as above
$tax_q_format_array
),
);
// 4. Query for posts
$posts_org = new WP_Query($args);
// 5. Output
if ( $posts_org->have_posts() ) { ?>
<h5 class="mt-0 pt-4 pb-3 text-secondary"><?php echo $section_title; ?> <span class="badge badge-secondary badge-pill"><?php echo $posts_org->found_posts; ?></span></h5>
<div class="row pb-0 my-posts" id="<?php echo $format; ?>">
<?php
while( $posts_org->have_posts() ) {
$posts_org->the_post();
get_template_part('partials/loops/col', 'vertical');
}
?>
</div>
<?php
// wp_reset_postdata(); // reset the query
// "More" posts link
if ($posts_org->found_posts > $posts_per_page) {
echo '<p class="text-secondary pb-0" style="opacity: 0.6"><a href="javascript:;" class="loadmore" id="'.$format.'"><i class="fas fa-plus-circle"></i> <span class="moretext">More</span></a></p>';
}
} else {
// echo '<div class="col"><p>'.__('Sorry, no posts matched your criteria.').'</p></div>';
} // end if have_posts
}
?>
<script type="text/javascript">
// Set starting values which to send from Javascript to WP query function...
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2; // Infer page #2 to start, then increment at end
var org_slug = "<?php echo $organisation->slug; ?>"; // Slug of this "organisation" term
jQuery(function($) {
// When this selector is clicked
$('body').on('click', '.loadmore', function() {
// Get ID of clicked link (corresponds to original $format value, eg. "executive"/"reporting")
var clicked_format = $(this).attr('id');
// Change link text to provide feedback
$('#'+clicked_format+' .moretext').text('Loading...');
$('#'+clicked_format+' i').attr('class', 'fas fa-cog fa-spin');
// 1. Send this package of variables to WP query function
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'org_slug': org_slug,
'clicked_format': clicked_format,
'security': '<?php echo wp_create_nonce("load_more_posts"); ?>'
};
// 2. Send to query function and get results
$.post(ajaxurl, data, function(response) {
// Append the returned output to this selector
$(response).appendTo('div#'+clicked_format).hide().fadeIn(2000); // was: $('div#'+clicked_format).append(response).fadeIn(4000); Reverse method, cf. https://stackoverflow.com/a/6534160/1375163
// Change link text back to original
$('#'+clicked_format+' .moretext').text('More');
$('#'+clicked_format+' i').attr('class', 'fas fa-plus-circle');
// Increment page for next click
page++;
});
});
});
</script>
</code></pre>
<h2>In functions.php:</h2>
<pre><code> // Called from org_deck2_many.php
add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');
function load_posts_by_ajax_callback() {
check_ajax_referer('load_more_posts', 'security');
// 1. Query values are passed from referring page, to Javascript and to this query...
$paged = $_POST['page']; // Passed from page: Which page we are on
$org_slug = $_POST['org_slug']; // Passed from page: Organisation taxonomy term slug
$clicked_format = $_POST['clicked_format']; // ID of the clicked "More" link (corresponds to original $format value, eg. "executive"/"reporting")
// $tax_q_format_array = $_POST['tax_q_format_array']; // Passed from page: 'Format' term-specifying part for 'tax_query'
// 2. Formulate the secondary tax_query for "format" with some conditionality
/* *********************************** */
/* Posts by Format? */
/* *********************************** */
if ($clicked_format!="reporting") {
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $clicked_format,
'include_children' => false
);
// $offset = NULL;
/* *********************************** */
/* Format without Format? */
/* *********************************** */
} elseif ($clicked_format=="reporting") {
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'operator' => 'NOT EXISTS', // or 'EXISTS'
);
// $offset = '12'; // More articles shown in "Reporting"
}
// 3. Set query arguments
$args = array(
// posts
'post_type' => array( 'article', 'viewpoint' ),
'post_status' => 'publish',
// 'offset' => $offset,
// pages
'posts_per_page' => '8',
'paged' => $paged,
// taxonomy
'tax_query' => array(
// #1 Organisation: the current one
array(
'taxonomy' => 'company', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $org_slug,
'include_children' => false
),
// #2 Format: as above
$tax_q_format_array
),
);
// 4. Query for posts
$posts_org = new WP_Query( $args );
// 5. Send results to Javascript
if ( $posts_org->have_posts() ) :
?>
<?php while ( $posts_org->have_posts() ) : $posts_org->the_post(); ?>
<?php get_template_part('partials/loops/col', 'vertical'); ?>
<?php endwhile; ?>
<?php
endif;
wp_die();
}
</code></pre>
<p><strong>However, there is a remaining issue that I know about...</strong></p>
<p>There seems to be a Javascript issue with picking up the clicked "More" link's ID as <code>clicked_format</code> and clicking some of the <em>multiple</em> "More" links on the page. I can see this because the first few "More" clicks succeed, but then clicking a different "More" link can leave the process in the "Loading" state.</p>
<p>I suspect it is something to do with when <code>clicked_format</code> gets set and destroyed (or not). I have tried unsetting it, but to no effect.</p>
<p>Should i consider filing a separate, specific question - in either WordPress Development or StackOverflow (Javascript) - for this?</p>
<p><a href="http://recordit.co/AI7OjJUVmH" rel="nofollow noreferrer">http://recordit.co/AI7OjJUVmH</a></p>
| [
{
"answer_id": 328760,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 2,
"selected": true,
"text": "<p>You can use ajax to load more posts on your archive page.</p>\n\n<ol>\n<li>attach a js/jquery click event on the More link</li>\n<li>send ajax request to <code>admin-ajax.php</code> (use <code>wp_localize_script</code> to get the ajax url to front end) with page number (track this with js variable).</li>\n<li>handle ajax request in php. Add custom ajax actions with <code>add_action( 'wp_ajax_my_action', 'my_action' );</code> and <code>add_action( 'wp_ajax_nopriv_my_action', 'my_action' );</code> (for non-logged in users). Send <code>my_action</code> part of the action hook as ajax request <code>action</code> parameter.</li>\n<li>query posts. Get the correct page (WP_Query <code>paged</code> arg, <em>commented out in your code</em>) for the query from the ajax request, e.g. <code>$_POST['page']</code></li>\n<li>send queried posts back to front end</li>\n<li>append posts from ajax response to the dom with js/jquery.</li>\n</ol>\n\n<p>I don't think it matters that much if you use the default jQuery version or a newer one to load more posts.</p>\n\n<p>Please have a look at the code examples here, <a href=\"https://www.billerickson.net/infinite-scroll-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.billerickson.net/infinite-scroll-in-wordpress/</a> (<em>not my blog</em>), for more detailed example and explanation. I know code examples are preferred to links, but the code examples written by Bill Erickson are rather long so I think it is more to convenient post a link insted of copy-pasting the examples here.</p>\n\n<p>You should also have a look at the codex entry about ajax, it is really helpfull. <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a> </p>\n\n<p>I only took a cursory glance at the query function you posted, but I think it should be fine for the post most part for loading more posts with ajax.</p>\n\n<hr>\n\n<p><strong>UPDATE 15.2.2019</strong></p>\n\n<p>If you need to identify which \"Load more\" link/button is clicked you can do this in js/jquery. </p>\n\n<pre><code>// Html\n<div id=\"posts-cat-1\" class=\"posts-section\">\n// posts here\n<button id=\"cat-name-1\" class=\"load-more\">Load more</button>\n</div>\n\n<div id=\"posts-cat-2\" class=\"posts-section\">\n// posts here\n<button class=\"load-more\" data-category=\"cat-name-2\">Load more</button>\n</div>\n\n<div id=\"cat-name-3\" class=\"posts-section\">\n// posts here\n<button class=\"load-more\">Load more</button>\n</div>\n\n// jQuery\njQuery('.load-more').on('click',function(event){\n// get cat name from id\nvar catName1 = jQuery(this).attr('id');\n// or from data attribute\nvar catName2 = jQuery(this).attr('data-category'); // or .data('category');\n// or from parent section, perhaps not ideal\nvar catName3 = jQuery(this).closest('.posts-section').attr('id');\n\n// Then pass the catName to your ajax request data so you can identify which category to query in php.\n});\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE 16.2.2019</strong></p>\n\n<p>To hide the \"Load more\" button when there are no more posts to show you can add a simple if-else conditional to your jquery ajax call.</p>\n\n<pre><code>// 2. Send to query function and get results\n$.post(ajaxurl, data, function(response) {\n\n // Check if there's any content in the response.\n // I think your ajax php should return empty string when there's no posts to show\n if ( '' !== response ) {\n\n // Append the returned output to this selector\n $(response).appendTo('div#'+clicked_format).hide().fadeIn(2000); // was: $('div#'+clicked_format).append(response).fadeIn(4000); Reverse method, cf. https://stackoverflow.com/a/6534160/1375163\n\n // Change link text back to original\n $('a#'+clicked_format+' i').attr('class', 'fas fa-plus-circle'); // Icon\n $('a#'+clicked_format+' .moretext').text('More'); // Text\n\n // Increment \"data-page\" attribute of clicked link for next click\n // page++;\n $('a#'+clicked_format).find('span').data().page++\n\n } else {\n\n // This adds display:none to the button, use .remove() to remove the button completely\n $('a#'+clicked_format).hide();\n\n }\n\n});\n</code></pre>\n"
},
{
"answer_id": 328879,
"author": "Robert Andrews",
"author_id": 39300,
"author_profile": "https://wordpress.stackexchange.com/users/39300",
"pm_score": 2,
"selected": false,
"text": "<p>This has been quite the learning curve.</p>\n\n<p>This solution takes multiple sources:</p>\n\n<ul>\n<li><a href=\"https://artisansweb.net/load-wordpress-post-ajax/\" rel=\"nofollow noreferrer\">Artisan Web tutorial</a></li>\n<li>Commenter Antti's contributions</li>\n</ul>\n\n<p>The method employs:</p>\n\n<p><strong>Javascript: In-line activate on click of \"More\" link.</strong></p>\n\n<p>In my case, due to using multiple blocks of posts for revealing, the script <em>must</em> have awareness of <em>which</em> link was clicked. So I need to set a named region for the post block and name the link correspondingly.</p>\n\n<p>Additionally, it is then important to increment only the next-page for the specific block whose \"More\" was clicked. So, we set a \"data-page\" attribute in the link, starting at the default 2 for page 2. Then we pick up this value and use it as \"page\". Then we increment this and only this one for next time.</p>\n\n<p><strong>WordPress function in functions.php</strong></p>\n\n<p>Fired through wp_ajax_load_posts_by_ajax and wp_ajax_nopriv_load_posts_by_ajax actions, it virtually replicates the same WP query setup as in my template file, but smartly taking the name of the clicked link in to correspond to a taxonomy term value required in the tax_query array.</p>\n\n<p><strong>Javascript: New results sent back to front-end</strong></p>\n\n<p>The new posts are appended to the posts block. And then the page increment takes place.</p>\n\n<p>Enhancements welcome to the code or this explanation.</p>\n\n<h1>Theme template fragment:</h1>\n\n<pre><code> <?php\n $organisation = get_query_var('organisation');\n $org_id_prefixed = get_query_var('org_id_prefixed');\n ?>\n\n\n <?php\n\n\n /* ************************************************************************************************************** */\n /* */\n /* LIST POSTS BY FORMAT TERM, WITH DYNAMIC AJAX MORE-POST LOADING */\n /* */\n /* Outline: */\n /* This will output posts in blocks for each \"Format\" taxonomy term. */\n /* But we also want to use this loop to output posts *without* a \"Format\" taxonomy term. */\n /* >> Method via Sajid @ Artisans Web, https://artisansweb.net/load-wordpress-post-ajax/ */\n /* */\n /* Dynamic: */\n /* 1. Javascript: When \"More\" link is clicked */\n /* 2. Send current \"organisation\", clicked \"format\" and \"page\" as variables to function */\n /* 3. PHP: Do WP query for next page of posts, return to javascript */\n /* 4. Javascript: Append results to the clicked container */\n /* */\n /* Dynamic method: */\n /* $format used as ID for i) .row .my-posts container and ii) .loadmore link, so that we know: */\n /* a) Which \"Load more\" link was clicked */\n /* b) Which box to return new output to */\n /* c) Employs data-page attribute in link - picks up this and increments page only for this */\n /* >> Help via Antti Koskinen @ StackOverflow, https://wordpress.stackexchange.com/a/328760/39300 */\n /* */\n /* ************************************************************************************************************** */\n\n\n // Specify which \"Format\" terms we want to display post blocks for\n // (\"reporting\" here is a wildcard, used to accommodate posts without a \"Format\" term set)\n $formats = array(\"interview\",\"executive\",\"analyst\",\"oped\",\"reporting\",\"ma\",\"earnings\",\"financialanalysis\",\"ipo\",\"marketindicators\",\"industrymoves\");\n\n // For each of them,\n foreach ($formats as $format) {\n\n // 1. Get actual term of the slug above\n $format_term = get_term_by('slug', $format, \"format\");\n\n // 2. Formulate the secondary tax_query for \"format\" with some conditionality\n /* *********************************** */\n /* Posts by Format? */\n /* *********************************** */\n if ($format!=\"reporting\") {\n $posts_per_page = 8;\n $tax_q_format_array = array(\n 'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'\n 'field' => 'slug',\n 'terms' => $format_term->slug,\n 'include_children' => false\n );\n // Oh, and set a title for output below\n $section_title = $format_term->name;\n /* *********************************** */\n /* Posts without Format? */\n /* *********************************** */\n } elseif ($format==\"reporting\") {\n $posts_per_page = 8;\n $tax_q_format_array = array(\n 'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'\n 'operator' => 'NOT EXISTS', // or 'EXISTS'\n );\n // Oh, and set a title for output below\n $section_title = 'Reporting';\n }\n\n // 3. Set query arguments\n $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n $args = array(\n // pagination\n // 'nopaging' => false,\n 'posts_per_page' => $posts_per_page,\n // 'offset' => '4',\n 'paged' => $paged,\n // posts\n 'post_type' => array( 'article', 'viewpoint' ),\n // order\n 'orderby' => 'date',\n 'order' => 'DESC',\n // taxonomy\n 'tax_query' => array(\n // #1 Organisation: the current one\n array(\n 'taxonomy' => 'company', // from above, whatever this taxonomy is, eg. 'source'\n 'field' => 'slug',\n 'terms' => $organisation->slug,\n 'include_children' => false\n ),\n // #2 Format: as above\n $tax_q_format_array\n ),\n );\n\n // 4. Query for posts\n $posts_org = new WP_Query($args);\n\n\n // 5. Output\n if ( $posts_org->have_posts() ) { ?>\n\n <h5 class=\"mt-0 pt-4 pb-3 text-secondary\"><?php echo $section_title; ?> <span class=\"badge badge-secondary badge-pill\"><?php echo $posts_org->found_posts; ?></span></h5>\n <div class=\"row pb-0 my-posts\" id=\"<?php echo $format; ?>\">\n <?php\n while( $posts_org->have_posts() ) {\n $posts_org->the_post();\n get_template_part('partials/loops/col', 'vertical');\n }\n ?>\n </div>\n <?php\n // wp_reset_postdata(); // reset the query\n\n // \"More\" posts link\n if ($posts_org->found_posts > $posts_per_page) {\n echo '<p class=\"text-secondary pb-0\" style=\"opacity: 0.6\"><a href=\"javascript:;\" class=\"loadmore\" id=\"'.$format.'\"><i class=\"fas fa-plus-circle\"></i> <span class=\"moretext\" data-page=\"2\">More</span></a></p>';\n }\n\n } else {\n // echo '<div class=\"col\"><p>'.__('Sorry, no posts matched your criteria.').'</p></div>';\n } // end if have_posts\n\n\n }\n\n\n ?>\n\n\n\n <script type=\"text/javascript\">\n\n // Set starting values which to send from Javascript to WP query function...\n var ajaxurl = \"<?php echo admin_url( 'admin-ajax.php' ); ?>\";\n var page = 2; // Infer page #2 to start, then increment at end\n var org_slug = \"<?php echo $organisation->slug; ?>\"; // Slug of this \"organisation\" term\n\n jQuery(function($) {\n\n // When this selector is clicked\n $('body').on('click', '.loadmore', function() {\n\n // Get ID of clicked link (corresponds to original $format value, eg. \"executive\"/\"reporting\")\n var clicked_format = $(this).attr('id');\n\n // Temporarily change clicked-link text to provide feedback\n $('a#'+clicked_format+' i').attr('class', 'fas fa-cog fa-spin'); // Icon\n $('a#'+clicked_format+' .moretext').text('Loading...'); // Text\n\n // Pick up data-page attribute from the clicked link (defaults to 2 at load)\n var clicked_page = $('a#'+clicked_format).find('span').data().page;\n // console.log(clicked_page);\n\n\n // 1. Send this package of variables to WP query function\n var data = {\n 'action': 'load_posts_by_ajax',\n 'page': clicked_page,\n 'org_slug': org_slug,\n 'clicked_format': clicked_format,\n 'security': '<?php echo wp_create_nonce(\"load_more_posts\"); ?>'\n };\n\n // 2. Send to query function and get results\n $.post(ajaxurl, data, function(response) {\n\n // Append the returned output to this selector\n $(response).appendTo('div#'+clicked_format).hide().fadeIn(2000); // was: $('div#'+clicked_format).append(response).fadeIn(4000); Reverse method, cf. https://stackoverflow.com/a/6534160/1375163\n\n // Change link text back to original\n $('a#'+clicked_format+' i').attr('class', 'fas fa-plus-circle'); // Icon\n $('a#'+clicked_format+' .moretext').text('More'); // Text\n\n // Increment \"data-page\" attribute of clicked link for next click\n // page++;\n $('a#'+clicked_format).find('span').data().page++\n });\n\n\n\n\n\n });\n\n\n\n });\n </script>\n</code></pre>\n\n<p>Function in functions.php:</p>\n\n<pre><code> // Called from org_deck2_many.php\n\n add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');\n add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');\n\n function load_posts_by_ajax_callback() {\n check_ajax_referer('load_more_posts', 'security');\n\n // 1. Query values are passed from referring page, to Javascript and to this query...\n $paged = $_POST['page']; // Passed from page: Which page we are on\n $org_slug = $_POST['org_slug']; // Passed from page: Organisation taxonomy term slug\n $clicked_format = $_POST['clicked_format']; // ID of the clicked \"More\" link (corresponds to original $format value, eg. \"executive\"/\"reporting\")\n\n // 2. Formulate the secondary tax_query for \"format\" with some conditionality\n /* *********************************** */\n /* Posts by Format? */\n /* *********************************** */\n if ($clicked_format!=\"reporting\") {\n $tax_q_format_array = array(\n 'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'\n 'field' => 'slug',\n 'terms' => $clicked_format,\n 'include_children' => false\n );\n // $offset = NULL;\n /* *********************************** */\n /* Posts without Format? */\n /* *********************************** */\n } elseif ($clicked_format==\"reporting\") {\n $tax_q_format_array = array(\n 'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'\n 'operator' => 'NOT EXISTS', // or 'EXISTS'\n );\n // $offset = '12'; // More articles shown in \"Reporting\"\n }\n\n // 3. Set query arguments\n $args = array(\n // posts\n 'post_type' => array( 'article', 'viewpoint' ),\n 'post_status' => 'publish',\n // 'offset' => $offset,\n // pages\n 'posts_per_page' => '8',\n 'paged' => $paged,\n // taxonomy\n 'tax_query' => array(\n // #1 Organisation: the current one\n array(\n 'taxonomy' => 'company', // from above, whatever this taxonomy is, eg. 'source'\n 'field' => 'slug',\n 'terms' => $org_slug,\n 'include_children' => false\n ),\n // #2 Format: as above\n $tax_q_format_array\n ),\n );\n\n // 4. Query for posts\n $posts_org = new WP_Query( $args );\n\n // 5. Send results to Javascript\n if ( $posts_org->have_posts() ) :\n ?>\n <?php while ( $posts_org->have_posts() ) : $posts_org->the_post(); ?>\n <?php get_template_part('partials/loops/col', 'vertical'); ?>\n <?php endwhile; ?>\n <?php\n endif;\n\n wp_die();\n }\n</code></pre>\n\n<h1>Edit: If all posts are pulled, disallow more polling</h1>\n\n<p>How should we stop allowing more link clicks if all posts/pages have been returned?</p>\n\n<p>In PHP, this code update calculates the total number of pages of posts this query will have, based on total posts divided by posts per page.</p>\n\n<p>It uses a <code>data-page</code> attribute in the clicked link to denote the next pagination page expected to be pulled.</p>\n\n<p>That counter is incremented each time a page of results is pulled.</p>\n\n<p>If the counter reaches past the total number of pages of posts for the query, that means we have exhausted the posts/pages for this query, there are no more, so we should STOP.</p>\n\n<p>What does \"STOP\" mean? It means using jQuery selectors to find and HIDE the whole link, which could otherwise be clicked to call posts again.</p>\n\n<pre><code> <?php\n $organisation = get_query_var('organisation');\n $org_id_prefixed = get_query_var('org_id_prefixed');\n ?>\n\n\n <?php\n\n\n /* ************************************************************************************************************** */\n /* */\n /* LIST POSTS BY FORMAT TERM, WITH DYNAMIC AJAX MORE-POST LOADING */\n /* */\n /* Outline: */\n /* This will output posts in blocks for each \"Format\" taxonomy term. */\n /* But we also want to use this loop to output posts *without* a \"Format\" taxonomy term. */\n /* >> Method via Sajid @ Artisans Web, https://artisansweb.net/load-wordpress-post-ajax/ */\n /* */\n /* Dynamic: */\n /* 1. Javascript: When \"More\" link is clicked */\n /* 2. Send current \"organisation\", clicked \"format\" and \"page\" as variables to function */\n /* 3. PHP: Do WP query for next page of posts, return to javascript */\n /* 4. Javascript: Append results to the clicked container */\n /* */\n /* Dynamic method: */\n /* $format used as ID for i) .row .my-posts container and ii) .loadmore link, so that we know: */\n /* a) Which \"Load more\" link was clicked */\n /* b) Which box to return new output to */\n /* c) Employs data-page attribute in link - picks up this and increments page only for this */\n /* >> Help via Antti Koskinen @ StackOverflow, https://wordpress.stackexchange.com/a/328760/39300 */\n /* */\n /* ************************************************************************************************************** */\n\n\n // Specify which \"Format\" terms we want to display post blocks for\n // (\"reporting\" here is a wildcard, used to accommodate posts without a \"Format\" term set)\n $formats = array(\"interview\",\"executive\",\"analyst\",\"oped\",\"reporting\",\"ma\",\"earnings\",\"financialanalysis\",\"ipo\",\"marketindicators\",\"industrymoves\");\n\n // For each of them,\n foreach ($formats as $format) {\n\n // 1. Get actual term of the slug above\n $format_term = get_term_by('slug', $format, \"format\");\n\n // 2. Formulate the secondary tax_query for \"format\" with some conditionality\n /* *********************************** */\n /* Posts by Format? */\n /* *********************************** */\n if ($format!=\"reporting\") {\n $posts_per_page = 8;\n $tax_q_format_array = array(\n 'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'\n 'field' => 'slug',\n 'terms' => $format_term->slug,\n 'include_children' => false\n );\n // Oh, and set a title for output below\n $section_title = $format_term->name;\n /* *********************************** */\n /* Posts without Format? */\n /* *********************************** */\n } elseif ($format==\"reporting\") {\n $posts_per_page = 8;\n $tax_q_format_array = array(\n 'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'\n 'operator' => 'NOT EXISTS', // or 'EXISTS'\n );\n // Oh, and set a title for output below\n $section_title = 'Reporting';\n }\n\n // 3. Set query arguments\n $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n $args = array(\n // pagination\n // 'nopaging' => false,\n 'posts_per_page' => $posts_per_page,\n // 'offset' => '4',\n 'paged' => $paged,\n // posts\n 'post_type' => array( 'article', 'viewpoint' ),\n // order\n 'orderby' => 'date',\n 'order' => 'DESC',\n // taxonomy\n 'tax_query' => array(\n // #1 Organisation: the current one\n array(\n 'taxonomy' => 'company', // from above, whatever this taxonomy is, eg. 'source'\n 'field' => 'slug',\n 'terms' => $organisation->slug,\n 'include_children' => false\n ),\n // #2 Format: as above\n $tax_q_format_array\n ),\n );\n\n // 4. Query for posts\n $posts_org = new WP_Query($args);\n\n\n // 5. Output\n if ( $posts_org->have_posts() ) { ?>\n\n <?php\n $total_posts = $posts_org->found_posts;\n $total_pages = $total_posts / $posts_per_page;\n ?>\n\n <h5 class=\"mt-0 pt-4 pb-3 text-secondary\"><?php echo $section_title; ?> <span class=\"badge badge-secondary badge-pill\"><?php echo $total_posts; ?></span></h5>\n <div class=\"row pb-0 my-posts\" id=\"<?php echo $format; ?>\" data-totalpages=\"<?php echo $total_pages; ?>\">\n <?php\n while( $posts_org->have_posts() ) {\n $posts_org->the_post();\n get_template_part('partials/loops/col', 'vertical');\n }\n ?>\n </div>\n <?php\n // wp_reset_postdata(); // reset the query\n\n // \"More\" posts link\n if ($posts_org->found_posts > $posts_per_page) {\n echo '<p class=\"text-secondary pb-0\" style=\"opacity: 0.6\"><a href=\"javascript:;\" class=\"loadmore\" id=\"'.$format.'\"><i class=\"fas fa-plus-circle\"></i> <span class=\"moretext\" data-page=\"2\">More</span></a></p>';\n }\n\n } else {\n // echo '<div class=\"col\"><p>'.__('Sorry, no posts matched your criteria.').'</p></div>';\n } // end if have_posts\n\n\n }\n\n\n ?>\n\n\n\n <script type=\"text/javascript\">\n\n // Set starting values which to send from Javascript to WP query function...\n var ajaxurl = \"<?php echo admin_url( 'admin-ajax.php' ); ?>\";\n var page = 2; // Infer page #2 to start, then increment at end\n var org_slug = \"<?php echo $organisation->slug; ?>\"; // Slug of this \"organisation\" term\n\n jQuery(function($) {\n\n // When this selector is clicked\n $('body').on('click', '.loadmore', function() {\n\n // Get ID of clicked link (corresponds to original $format value, eg. \"executive\"/\"reporting\")\n var clicked_format = $(this).attr('id');\n\n // Get total pagination pages for this section\n var total_pages_for_section = $('div .row #'+clicked_format).data().totalpages;\n // alert(total_pages_for_section);\n\n // Temporarily change clicked-link text to provide feedback\n $('a#'+clicked_format+' i').attr('class', 'fas fa-cog fa-spin'); // Icon\n $('a#'+clicked_format+' .moretext').text('Loading...'); // Text\n\n // Pick up data-page attribute from the clicked link (defaults to 2 at load)\n var clicked_page = $('a#'+clicked_format).find('span').data().page;\n // console.log(clicked_page);\n\n\n // 1. Send this package of variables to WP query function\n var data = {\n 'action': 'load_posts_by_ajax',\n 'page': clicked_page, // page of posts to get is the number set in data-page attribute\n 'org_slug': org_slug,\n 'clicked_format': clicked_format,\n 'security': '<?php echo wp_create_nonce(\"load_more_posts\"); ?>'\n };\n\n // 2. Send to query function and get results\n $.post(ajaxurl, data, function(response) {\n\n // Append the returned output to this selector\n $(response).appendTo('div#'+clicked_format).hide().fadeIn(2000); // was: $('div#'+clicked_format).append(response).fadeIn(4000); Reverse method, cf. https://stackoverflow.com/a/6534160/1375163\n\n // If we have exhausted all post pages, hide the whole \"More\" link <p>\n if (clicked_page >= total_pages_for_section) {\n $('p a#'+clicked_format).hide();\n // Otherwise, restore it and increment counter\n } else {\n // Change link text back to original\n $('a#'+clicked_format+' i').attr('class', 'fas fa-plus-circle'); // Icon\n $('a#'+clicked_format+' .moretext').text('More'); // Text\n // Increment \"data-page\" attribute of clicked link for next click\n $('a#'+clicked_format).find('span').data().page++; // was page++;\n }\n\n });\n\n\n\n\n\n });\n\n\n\n });\n </script>\n</code></pre>\n"
}
] | 2019/02/14 | [
"https://wordpress.stackexchange.com/questions/328685",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39300/"
] | On the taxonomy-{name}.php template for my "Organisation" taxonomy, I am currently showing a limited number of posts, grouped for each term of taxonomy "Format".
Where the number of available posts exceeds that which is displayable, I now want to enable AJAX-based loading of more posts.
I have followed countless tutorials and StackExchange questions on this topic, but something is still not clicking. For example, I implemented [Misha Rudrastyh's "Load More" button](https://rudrastyh.com/wordpress/load-more-posts-ajax.html), but the code just would not load any posts. I am lost and on the verge of giving up.
I have a post block with a "More" link like this, ready and waiting...
[](https://i.stack.imgur.com/SWOJa.png)
That corresponds to posts of "Format" taxonomy term "executive" for one taxonomy "Organisation" term. Here is the relevant portion of taxonomy-organisation.php, containing my query...
```
<?php
// This will output posts in blocks for each "Format" taxonomy term.
// But we also want to use this loop to output posts *without* a "Format" taxonomy term.
$formats = array("interview","executive","analyst","oped","","ma","earnings","financialanalysis","ipo","marketindicators","industrymoves");
foreach ($formats as $format) {
// Term of the slug above
$format_term = get_term_by('slug', $format, "format");
// Formulate the secondary tax_query for "format" with some conditionality
/* *********************************** */
/* Posts by Format */
/* *********************************** */
if (!empty($format)) {
$posts_per_page = 8;
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $format_term->slug,
'include_children' => false
);
// Oh, and set a title for output below
$section_title = $format_term->name;
/* *********************************** */
/* Format without Format */
/* *********************************** */
} elseif (empty($format)) {
$posts_per_page = 12;
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'operator' => 'NOT EXISTS', // or 'EXISTS'
);
// Oh, and set a title for output below
$section_title = 'Reporting';
}
// Query posts
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
// pagination
// 'nopaging' => false,
'posts_per_page' => $posts_per_page,
// 'offset' => '4',
// 'paged' => $paged,
// posts
'post_type' => array( 'article', 'viewpoint' ),
// order
'orderby' => 'date',
'order' => 'DESC',
// taxonomy
'tax_query' => array(
array(
'taxonomy' => 'company', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $organisation->slug,
'include_children' => false
),
$tax_q_format_array
),
);
// the query
$posts_org = new WP_Query($args);
if ( $posts_org->have_posts() ) { ?>
<h5 class="mt-0 pt-2 pb-3 text-secondary"><?php echo $section_title; ?> <span class="badge badge-secondary badge-pill"><?php echo $posts_org->found_posts; ?></span></h5>
<div class="row pb-3">
<?php
while( $posts_org->have_posts() ) {
$posts_org->the_post();
get_template_part('partials/loops/col', 'vertical');
}
if ($posts_org->found_posts > $posts_per_page) {
echo '<p class="text-secondary pl-3 pb-0 load_more" style="opacity: 0.6"><i class="fas fa-plus-circle"></i> More</p>';
}
echo '</div>';
wp_reset_postdata(); // reset the query
} else {
// echo '<div class="col"><p>'.__('Sorry, no posts matched your criteria.').'</p></div>';
} // end if have_posts
}
?>
```
And here is the include file used by `get_template_part` to output post item thumbnails and links...
```
<?php
// Get fallback image if needed
@require(dirname(__FILE__).'/../source_thumbnail_fallback.php');
// @ Suppress "Notices" generated when post has no source set (ie no source at array position [0])
?>
<div class="col-sm-6 col-md-4 col-lg-3 col-xl-2 post-item overlay-bg <?php echo $display_class; ?>">
<a href="<?php the_field( 'source_url' ); ?>" class="text-dark" target="_blank">
<img src="http://www.myserver.com/to/image/location/<?php echo $source_image_url; ?>" class="img-fluid rounded mb-2">
<p><?php the_title(); ?></p>
<?php
//Do something if a specific array value exists within a post
$format_terms = wp_get_post_terms($post->ID, 'format', array("fields" => "all"));
// foreach($format_terms as $format_single) { ?>
<span class="badge <?php get_format_badge_colour_class($format_terms[0]->term_id); ?> font-weight-normal mr-2 overlay-content"><?php echo $format_terms[0]->name; ?></span>
<?php // } ?>
</a>
</div>
```
From the tutorials and questions, I have gleaned that the process seems to be...
* Register/enqueue/localise a Javascript file containing the relevant code, and pass parameters to it from PHP functions.php
* Some sort of WordPress AJAX handler in functions.php which does a WP\_Query for more posts?
But I am just not understanding how to implement in my situation.
FYI, my self-built theme is based on Bootstrap and, until now, I have de-registered WordPress' built-in `jquery`, replaced by enqueuing Bootstrap's recommended `https://code.jquery.com/jquery-3.3.1.slim.min.js` as `jQuery`. I'm not sure which is the right option, it seemed like this has a bearing on WP\_Ajax\_\*.
I'm aware a similar question has been asked before, but my query seems unique and many questions/answers seem also to refer to unique situations, ie. offering answers specifically designed to work with twentyfifteen theme.
Update (Feb 15, 2019):
======================
I have come a long way toward solving this, using a combination of:
* [Artisans Web tutorial](https://artisansweb.net/load-wordpress-post-ajax/) for the basic concept
* [Anti's suggestion](https://wordpress.stackexchange.com/a/328760/39300) for establishing *which* of multiple "More" links was clicked (necessary to feed unique arguments back to looped WP queries).
* Further research/exploration based on available code, to learn how to take and pass those variables.
* Further jQuery research to learn how to change UI elements.
I can now share the following two pieces of code, which works 90% well and I could consider offering this as an answer, or Anti's answer.
Theme template fragment:
------------------------
```
<?php
$organisation = get_query_var('organisation');
$org_id_prefixed = get_query_var('org_id_prefixed');
?>
<?php
/* ************************************************************************************************************** */
/* */
/* LIST POSTS BY FORMAT TERM, WITH DYNAMIC AJAX MORE-POST LOADING */
/* */
/* Outline: */
/* This will output posts in blocks for each "Format" taxonomy term. */
/* But we also want to use this loop to output posts *without* a "Format" taxonomy term. */
/* >> Method via Sajid @ Artisans Web, https://artisansweb.net/load-wordpress-post-ajax/ */
/* */
/* Dynamic: */
/* 1. Javascript: When "More" link is clicked */
/* 2. Send current "organisation", clicked "format" and "page" as variables to function */
/* 3. PHP: Do WP query for next page of posts, return to javascript */
/* 4. Javascript: Append results to the clicked container */
/* */
/* Dynamic method: */
/* $format used as ID for i) .row .my-posts container and ii) .loadmore link, so that we know: */
/* a) Which "Load more" link was clicked */
/* b) Which box to return new output to */
/* >> Help via Antti Koskinen @ StackOverflow, https://wordpress.stackexchange.com/a/328760/39300 */
/* */
/* ************************************************************************************************************** */
// Specify which "Format" terms we want to display post blocks for
// ("reporting" here is a wildcard, used to accommodate posts without a "Format" term set)
$formats = array("interview","executive","analyst","oped","reporting","ma","earnings","financialanalysis","ipo","marketindicators","industrymoves");
// For each of them,
foreach ($formats as $format) {
// 1. Get actual term of the slug above
$format_term = get_term_by('slug', $format, "format");
// 2. Formulate the secondary tax_query for "format" with some conditionality
/* *********************************** */
/* Posts by Format? */
/* *********************************** */
if ($format!="reporting") {
// $posts_per_page = 8;
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $format_term->slug,
'include_children' => false
);
// Oh, and set a title for output below
$section_title = $format_term->name;
/* *********************************** */
/* Format without Format? */
/* *********************************** */
} elseif ($format=="reporting") {
// $posts_per_page = 12;
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'operator' => 'NOT EXISTS', // or 'EXISTS'
);
// Oh, and set a title for output below
$section_title = 'Reporting';
}
// 3. Set query arguments
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
// pagination
// 'nopaging' => false,
'posts_per_page' => '8', // $posts_per_page,
// 'offset' => '4',
'paged' => $paged,
// posts
'post_type' => array( 'article', 'viewpoint' ),
// order
'orderby' => 'date',
'order' => 'DESC',
// taxonomy
'tax_query' => array(
// #1 Organisation: the current one
array(
'taxonomy' => 'company', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $organisation->slug,
'include_children' => false
),
// #2 Format: as above
$tax_q_format_array
),
);
// 4. Query for posts
$posts_org = new WP_Query($args);
// 5. Output
if ( $posts_org->have_posts() ) { ?>
<h5 class="mt-0 pt-4 pb-3 text-secondary"><?php echo $section_title; ?> <span class="badge badge-secondary badge-pill"><?php echo $posts_org->found_posts; ?></span></h5>
<div class="row pb-0 my-posts" id="<?php echo $format; ?>">
<?php
while( $posts_org->have_posts() ) {
$posts_org->the_post();
get_template_part('partials/loops/col', 'vertical');
}
?>
</div>
<?php
// wp_reset_postdata(); // reset the query
// "More" posts link
if ($posts_org->found_posts > $posts_per_page) {
echo '<p class="text-secondary pb-0" style="opacity: 0.6"><a href="javascript:;" class="loadmore" id="'.$format.'"><i class="fas fa-plus-circle"></i> <span class="moretext">More</span></a></p>';
}
} else {
// echo '<div class="col"><p>'.__('Sorry, no posts matched your criteria.').'</p></div>';
} // end if have_posts
}
?>
<script type="text/javascript">
// Set starting values which to send from Javascript to WP query function...
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2; // Infer page #2 to start, then increment at end
var org_slug = "<?php echo $organisation->slug; ?>"; // Slug of this "organisation" term
jQuery(function($) {
// When this selector is clicked
$('body').on('click', '.loadmore', function() {
// Get ID of clicked link (corresponds to original $format value, eg. "executive"/"reporting")
var clicked_format = $(this).attr('id');
// Change link text to provide feedback
$('#'+clicked_format+' .moretext').text('Loading...');
$('#'+clicked_format+' i').attr('class', 'fas fa-cog fa-spin');
// 1. Send this package of variables to WP query function
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'org_slug': org_slug,
'clicked_format': clicked_format,
'security': '<?php echo wp_create_nonce("load_more_posts"); ?>'
};
// 2. Send to query function and get results
$.post(ajaxurl, data, function(response) {
// Append the returned output to this selector
$(response).appendTo('div#'+clicked_format).hide().fadeIn(2000); // was: $('div#'+clicked_format).append(response).fadeIn(4000); Reverse method, cf. https://stackoverflow.com/a/6534160/1375163
// Change link text back to original
$('#'+clicked_format+' .moretext').text('More');
$('#'+clicked_format+' i').attr('class', 'fas fa-plus-circle');
// Increment page for next click
page++;
});
});
});
</script>
```
In functions.php:
-----------------
```
// Called from org_deck2_many.php
add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');
function load_posts_by_ajax_callback() {
check_ajax_referer('load_more_posts', 'security');
// 1. Query values are passed from referring page, to Javascript and to this query...
$paged = $_POST['page']; // Passed from page: Which page we are on
$org_slug = $_POST['org_slug']; // Passed from page: Organisation taxonomy term slug
$clicked_format = $_POST['clicked_format']; // ID of the clicked "More" link (corresponds to original $format value, eg. "executive"/"reporting")
// $tax_q_format_array = $_POST['tax_q_format_array']; // Passed from page: 'Format' term-specifying part for 'tax_query'
// 2. Formulate the secondary tax_query for "format" with some conditionality
/* *********************************** */
/* Posts by Format? */
/* *********************************** */
if ($clicked_format!="reporting") {
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $clicked_format,
'include_children' => false
);
// $offset = NULL;
/* *********************************** */
/* Format without Format? */
/* *********************************** */
} elseif ($clicked_format=="reporting") {
$tax_q_format_array = array(
'taxonomy' => 'format', // from above, whatever this taxonomy is, eg. 'source'
'operator' => 'NOT EXISTS', // or 'EXISTS'
);
// $offset = '12'; // More articles shown in "Reporting"
}
// 3. Set query arguments
$args = array(
// posts
'post_type' => array( 'article', 'viewpoint' ),
'post_status' => 'publish',
// 'offset' => $offset,
// pages
'posts_per_page' => '8',
'paged' => $paged,
// taxonomy
'tax_query' => array(
// #1 Organisation: the current one
array(
'taxonomy' => 'company', // from above, whatever this taxonomy is, eg. 'source'
'field' => 'slug',
'terms' => $org_slug,
'include_children' => false
),
// #2 Format: as above
$tax_q_format_array
),
);
// 4. Query for posts
$posts_org = new WP_Query( $args );
// 5. Send results to Javascript
if ( $posts_org->have_posts() ) :
?>
<?php while ( $posts_org->have_posts() ) : $posts_org->the_post(); ?>
<?php get_template_part('partials/loops/col', 'vertical'); ?>
<?php endwhile; ?>
<?php
endif;
wp_die();
}
```
**However, there is a remaining issue that I know about...**
There seems to be a Javascript issue with picking up the clicked "More" link's ID as `clicked_format` and clicking some of the *multiple* "More" links on the page. I can see this because the first few "More" clicks succeed, but then clicking a different "More" link can leave the process in the "Loading" state.
I suspect it is something to do with when `clicked_format` gets set and destroyed (or not). I have tried unsetting it, but to no effect.
Should i consider filing a separate, specific question - in either WordPress Development or StackOverflow (Javascript) - for this?
<http://recordit.co/AI7OjJUVmH> | You can use ajax to load more posts on your archive page.
1. attach a js/jquery click event on the More link
2. send ajax request to `admin-ajax.php` (use `wp_localize_script` to get the ajax url to front end) with page number (track this with js variable).
3. handle ajax request in php. Add custom ajax actions with `add_action( 'wp_ajax_my_action', 'my_action' );` and `add_action( 'wp_ajax_nopriv_my_action', 'my_action' );` (for non-logged in users). Send `my_action` part of the action hook as ajax request `action` parameter.
4. query posts. Get the correct page (WP\_Query `paged` arg, *commented out in your code*) for the query from the ajax request, e.g. `$_POST['page']`
5. send queried posts back to front end
6. append posts from ajax response to the dom with js/jquery.
I don't think it matters that much if you use the default jQuery version or a newer one to load more posts.
Please have a look at the code examples here, <https://www.billerickson.net/infinite-scroll-in-wordpress/> (*not my blog*), for more detailed example and explanation. I know code examples are preferred to links, but the code examples written by Bill Erickson are rather long so I think it is more to convenient post a link insted of copy-pasting the examples here.
You should also have a look at the codex entry about ajax, it is really helpfull. <https://codex.wordpress.org/AJAX_in_Plugins>
I only took a cursory glance at the query function you posted, but I think it should be fine for the post most part for loading more posts with ajax.
---
**UPDATE 15.2.2019**
If you need to identify which "Load more" link/button is clicked you can do this in js/jquery.
```
// Html
<div id="posts-cat-1" class="posts-section">
// posts here
<button id="cat-name-1" class="load-more">Load more</button>
</div>
<div id="posts-cat-2" class="posts-section">
// posts here
<button class="load-more" data-category="cat-name-2">Load more</button>
</div>
<div id="cat-name-3" class="posts-section">
// posts here
<button class="load-more">Load more</button>
</div>
// jQuery
jQuery('.load-more').on('click',function(event){
// get cat name from id
var catName1 = jQuery(this).attr('id');
// or from data attribute
var catName2 = jQuery(this).attr('data-category'); // or .data('category');
// or from parent section, perhaps not ideal
var catName3 = jQuery(this).closest('.posts-section').attr('id');
// Then pass the catName to your ajax request data so you can identify which category to query in php.
});
```
---
**UPDATE 16.2.2019**
To hide the "Load more" button when there are no more posts to show you can add a simple if-else conditional to your jquery ajax call.
```
// 2. Send to query function and get results
$.post(ajaxurl, data, function(response) {
// Check if there's any content in the response.
// I think your ajax php should return empty string when there's no posts to show
if ( '' !== response ) {
// Append the returned output to this selector
$(response).appendTo('div#'+clicked_format).hide().fadeIn(2000); // was: $('div#'+clicked_format).append(response).fadeIn(4000); Reverse method, cf. https://stackoverflow.com/a/6534160/1375163
// Change link text back to original
$('a#'+clicked_format+' i').attr('class', 'fas fa-plus-circle'); // Icon
$('a#'+clicked_format+' .moretext').text('More'); // Text
// Increment "data-page" attribute of clicked link for next click
// page++;
$('a#'+clicked_format).find('span').data().page++
} else {
// This adds display:none to the button, use .remove() to remove the button completely
$('a#'+clicked_format).hide();
}
});
``` |
328,721 | <p>I have a piece of PHP code to grab my post title which I am putting inside of a PHP element on my page builder.</p>
<pre><code>$h4 = get_the_title();`echo '<h4>' . $h4 . '</h4>';`
</code></pre>
<p>I want it to be a H1 but want to style the H1 differently to my global H1 settings.
I would like this H1 centered with font color white and font size 60px.
Can anyone please help me with this?</p>
<p>Thanks</p>
| [
{
"answer_id": 328722,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>Why not add a CSS class to the H1?</p>\n\n<p><code>echo '<h1 class=\"custom-style\">' . get_the_title() . '</h1>';</code></p>\n\n<p>then in your child theme or custom CSS, apply the style to that class:</p>\n\n<pre><code>h1.custom-style { \n text-align:center; \n color:#fff;\n font-size:60px; \n}\n</code></pre>\n"
},
{
"answer_id": 328723,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 1,
"selected": false,
"text": "<p>Replacing your code little bit. </p>\n\n<pre><code>$title = get_the_title();\necho '<h1 class=\"centered-title\">' . $title . '</h1>';\n</code></pre>\n\n<p>I changed the heading tag to H1 tag and added a CSS classname <strong>centered-title</strong>. Open your style.css file of your theme or go to Customizer -> Additional CSS box and add this CSS:</p>\n\n<pre><code>.centered-title {\n color: #fff;\n font-size: 60px;\n text-align: center;\n}\n</code></pre>\n"
}
] | 2019/02/14 | [
"https://wordpress.stackexchange.com/questions/328721",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146090/"
] | I have a piece of PHP code to grab my post title which I am putting inside of a PHP element on my page builder.
```
$h4 = get_the_title();`echo '<h4>' . $h4 . '</h4>';`
```
I want it to be a H1 but want to style the H1 differently to my global H1 settings.
I would like this H1 centered with font color white and font size 60px.
Can anyone please help me with this?
Thanks | Why not add a CSS class to the H1?
`echo '<h1 class="custom-style">' . get_the_title() . '</h1>';`
then in your child theme or custom CSS, apply the style to that class:
```
h1.custom-style {
text-align:center;
color:#fff;
font-size:60px;
}
``` |
328,731 | <p>I have found the below code to enable viewing the author of a custom post type and it works perfectly for one custom post type. But I need it to work for 4 custom post types called: detox, recipes, movements, lifestyle.</p>
<pre><code>function add_author_support_to_posts() {
add_post_type_support( 'your_custom_post_type', 'author' );
}
add_action( 'init', 'add_author_support_to_posts' );
</code></pre>
<p>What is the correct syntax to include all 4 custom post types?</p>
| [
{
"answer_id": 328734,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p><code>wp-config.php</code> includes files, it's not just a config file, and WordPress isn't built to allow putting the file 2 levels up.</p>\n\n<p>However, WordPress already supports loading <code>wp-config.php</code> from 1 level up.</p>\n\n<p>With all of this in mind though, this is only really a protection if you're worried about mis-configuring your server. Unless PHP execution is turned off, which would be a major issue in of itself, <code>wp-config.php</code> won't leak any information.</p>\n\n<blockquote>\n <p>this gave me white screen of death on admin pages and some other pages</p>\n</blockquote>\n\n<p>A WSOD is a HTTP 500 error code, to see the real error message you have to look in the PHP error logs. It's the difference between a plane disappearing, and finding its flight recorder/black box.</p>\n"
},
{
"answer_id": 328744,
"author": "orionsweb",
"author_id": 130225,
"author_profile": "https://wordpress.stackexchange.com/users/130225",
"pm_score": 0,
"selected": false,
"text": "<p>wp-config needs to be accessible to the public.. I'm guessing that 2 levels up means above the public_html folder (cpanel) at the /home level. If you found a work around to allow access to it at that level you're potentially compromising security. Best to leave it at the same, or only one level up. </p>\n"
}
] | 2019/02/14 | [
"https://wordpress.stackexchange.com/questions/328731",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161243/"
] | I have found the below code to enable viewing the author of a custom post type and it works perfectly for one custom post type. But I need it to work for 4 custom post types called: detox, recipes, movements, lifestyle.
```
function add_author_support_to_posts() {
add_post_type_support( 'your_custom_post_type', 'author' );
}
add_action( 'init', 'add_author_support_to_posts' );
```
What is the correct syntax to include all 4 custom post types? | `wp-config.php` includes files, it's not just a config file, and WordPress isn't built to allow putting the file 2 levels up.
However, WordPress already supports loading `wp-config.php` from 1 level up.
With all of this in mind though, this is only really a protection if you're worried about mis-configuring your server. Unless PHP execution is turned off, which would be a major issue in of itself, `wp-config.php` won't leak any information.
>
> this gave me white screen of death on admin pages and some other pages
>
>
>
A WSOD is a HTTP 500 error code, to see the real error message you have to look in the PHP error logs. It's the difference between a plane disappearing, and finding its flight recorder/black box. |
328,747 | <p>I accidentally changed my wordpress website url from what it was to the url which is same as my site url and after then I am not able to login into my admin it shows error of page not found(while using my original wordpress site url) and if I try to login through my site url it shows me redirected you too many times.</p>
<p>Please help me!
I tried accesing file through ftp but got no luck in that, also tried to go to wp-login.php but in that also page not found error is coming.
and also tried deleting cookies.Tried disabling plugins and themes from filezilla but nothing is working.</p>
| [
{
"answer_id": 328748,
"author": "Fabrizio Mele",
"author_id": 40463,
"author_profile": "https://wordpress.stackexchange.com/users/40463",
"pm_score": 0,
"selected": false,
"text": "<p>I you accidentally changed the site url you can change it back manually, via your database manager (usually phpmyadmin): look at the <code>wp_options</code> table and search for <code>home</code> and <code>siteurl</code> options and edit them back to the original value (your website url).</p>\n"
},
{
"answer_id": 328755,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't have database access for some reason, you can also use</p>\n\n<pre><code>// use these in your wp-config.php\ndefine( 'WP_HOME', 'http://example.com' );\ndefine( 'WP_SITEURL', 'http://example.com' );\n</code></pre>\n\n<p>or</p>\n\n<pre><code>// use these in your functions.php\nupdate_option( 'siteurl', 'http://example.com' );\nupdate_option( 'home', 'http://example.com' );\n</code></pre>\n\n<p>to regain access to your site. You can read more about changing the site urls from the codex, <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">Changing The Site URL</a></p>\n"
}
] | 2019/02/14 | [
"https://wordpress.stackexchange.com/questions/328747",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I accidentally changed my wordpress website url from what it was to the url which is same as my site url and after then I am not able to login into my admin it shows error of page not found(while using my original wordpress site url) and if I try to login through my site url it shows me redirected you too many times.
Please help me!
I tried accesing file through ftp but got no luck in that, also tried to go to wp-login.php but in that also page not found error is coming.
and also tried deleting cookies.Tried disabling plugins and themes from filezilla but nothing is working. | If you don't have database access for some reason, you can also use
```
// use these in your wp-config.php
define( 'WP_HOME', 'http://example.com' );
define( 'WP_SITEURL', 'http://example.com' );
```
or
```
// use these in your functions.php
update_option( 'siteurl', 'http://example.com' );
update_option( 'home', 'http://example.com' );
```
to regain access to your site. You can read more about changing the site urls from the codex, [Changing The Site URL](https://codex.wordpress.org/Changing_The_Site_URL) |
328,749 | <p>I use <code>get_the_content</code> to pass to a javascript variable, and then back to another PHP function. This works great, but there is an issue when using <code>get_the_content</code>. If the post contains only one line (no line breaks) it works great.
But if the post contains line breaks I get this error in the console:</p>
<p><code>SyntaxError: '' string literal contains an unescaped line break</code></p>
<p>Using <code>the_content</code> doesn't work for me in this application, as it returns nothing at all.</p>
<p>How do I solve this?</p>
<p>EDIT:</p>
<p>This is how I pass the PHP variable to Javascript on button click:</p>
<pre><code>onclick="searchEmail('<?php echo the_author_email(); ?>', '<?php echo the_title(); ?>', '<?php echo get_the_content(); ?>', '<?php echo $location ?>');"
</code></pre>
<p>And this is the javascript:</p>
<pre><code>function searchEmail(email,title,content,location) {
var $url = (admin_ajax.url);
$.ajax({
type: "POST",
url: $url,
datatype: "html",
data: { 'action': 'search_notify_email', email: email, title: title, content: content, location: location },
success: function() {
searchNotification();
},error:function() {
searchNotificationError();
}
});
}
</code></pre>
<p>And lastly, this is the PHP function which receives the variable from Javascript and sends them via email:</p>
<pre><code>function search_notify_email() {
// Set variables
$email = $_POST['email'];
$title = $_POST['title'];
$content = $_POST['content'];
$location = $_POST['location'];
// Change Email to HTML
add_filter( 'wp_mail_content_type', 'set_email_content_type' );
$to = $email;
$subject = "Test subjest";
$message = "<img src='https://example.com/favicon.png'><br><b>Test!</b>";
if (empty($title)) {
$message .= "<br><br><b>" . $_POST['content'] . "</b> test.<br> ";
}
else {
$message .= "<br><br><b>" . $_POST['content'] . "</b> test " . $_POST['title'] . " test.<br> ";
}
if (!empty($location)) {
$message .= "Test <b>" . $_POST['location'] . "</b>";
}
$headers[] = 'From: Test <[email protected]>';
if ( wp_mail($to, $subject, $message, $headers) ) {
// Success
} else {
// Error
}
die();
// Remove filter HTML content type
remove_filter( 'wp_mail_content_type', 'set_email_content_type' );
}
add_action('wp_ajax_nopriv_search_notify_email', 'search_notify_email');
add_action('wp_ajax_search_notify_email', 'search_notify_email');
// Reset Email content type to standard text/html
function set_email_content_type() {
return 'text/html';
}
</code></pre>
| [
{
"answer_id": 328758,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds like you are directly echoing the php into a JavaScript variable? get_the_content makes no guarantees that the value it returns will be sanitized in the right way for a JavaScript variable.</p>\n\n<p>You might try first encoding the output into JSON, and then doing that, i.e.</p>\n\n<pre><code><script>\n<?php\n ob_start();\n the_content();\n $content = ob_get_clean(); \n?>\nvar myVariable = <?php echo json_encode( $content ); ?>;\n</script>\n</code></pre>\n\n<p>To be honest it may not even work. It's hacky. Dropping php into JavaScript like this is really not a recommended practice, for exactly the reason you're encountering. What this solution does is poorly imitate the proper approach for when you have PHP data (i.e. the_content) that you need in JavaScript -- AJAX.</p>\n\n<p>Your JavaScript code should ask your PHP code to nicely provide sanitized data, i.e. it should make an AJAX request back to the server and your PHP code will have the opportunity to run, sanitize, and return the data cleanly.</p>\n"
},
{
"answer_id": 328759,
"author": "user141080",
"author_id": 141080,
"author_profile": "https://wordpress.stackexchange.com/users/141080",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is JavaScript. In JavaScript you can not across a string about multiple lines without to escape the line breaks. </p>\n\n<pre><code>var longString = 'This is a very long string which needs \n to wrap across multiple lines because \n otherwise my code is unreadable.';\n// SyntaxError: unterminated string literal\n</code></pre>\n\n<p>You could try to replace the line breaks with the + operator, a backslash, or template literals (ECMAScript 2015).</p>\n\n<p>text with the + operator:</p>\n\n<pre><code>var longString = 'This is a very long string which needs ' +\n 'to wrap across multiple lines because ' +\n 'otherwise my code is unreadable.';\n</code></pre>\n\n<p>text with backslashs:</p>\n\n<pre><code>var longString = 'This is a very long string which needs \\\n to wrap across multiple lines because \\\n otherwise my code is unreadable.';\n</code></pre>\n\n<p>text with template literals: </p>\n\n<pre><code>var longString = `This is a very long string which needs \n to wrap across multiple lines because\n otherwise my code is unreadable.`;\n</code></pre>\n\n<p>Source: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Unterminated_string_literal\" rel=\"nofollow noreferrer\">SyntaxError: unterminated string literal - MDN web docs</a></p>\n\n<p><strong>Edit:</strong></p>\n\n<p>To replace the new lines you could use this code:</p>\n\n<pre><code><?php \n\n// test string\n$str = \"This is a very long string which needs \nto wrap across multiple lines because \notherwise my code is unreadable.\";\n\nfunction replace_with_plus($str)\n{\n $str_array = explode ( \"\\n\" , $str );\n\n $len = count( $str_array );\n\n $str_2 = '';\n for($i = 0; $i < $len; $i ++)\n { \n $line = $str_array[$i];\n\n if($i > 0 )\n {\n $str_2 .= \"'\";\n }\n\n $str_2 .= $line;\n\n if($i < $len - 1 )\n {\n $str_2 .= \"' + \";\n }\n\n }\n\n return $str_2;\n}\n\n?>\n\n<script>\n\n// replace the \\n with the + operator\nvar test2 = '<?php echo replace_with_plus($str); ?>';\n\n</script>\n</code></pre>\n\n<p>Output in the browser:</p>\n\n<pre><code><script>\n\n// replace the \\n with the + operator\nvar test2 = 'This is a very long string which needs ' + 'to wrap across multiple lines because ' + 'otherwise my code is unreadable.';\n\n</script>\n</code></pre>\n\n<p>Like tmdesigned said the whole think with putting the content into a JavaScript value is really buggy and not the best way. </p>\n\n<p>I highly recommend you to use the way that czerspalace explained in his comment.</p>\n"
},
{
"answer_id": 328789,
"author": "joq3",
"author_id": 143279,
"author_profile": "https://wordpress.stackexchange.com/users/143279",
"pm_score": 1,
"selected": false,
"text": "<p>This is the solution:</p>\n\n<pre><code>ob_start();\nremove_filter ('the_content', 'wpautop'); the_content();\n$content = ob_get_contents();\nob_end_clean();\n</code></pre>\n\n<p>Together with:</p>\n\n<pre><code>echo str_replace(array(\"\\n\", \"\\r\"), ' + ', $content);\n</code></pre>\n\n<p>The only issue that remains now is that replacing the new lines with <code>+</code> results in duplicate <code>+ +</code> every new line. And removing either ´\\n´ or <code>\\r</code> results in the javascript error. So how do I get around that?</p>\n"
}
] | 2019/02/14 | [
"https://wordpress.stackexchange.com/questions/328749",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143279/"
] | I use `get_the_content` to pass to a javascript variable, and then back to another PHP function. This works great, but there is an issue when using `get_the_content`. If the post contains only one line (no line breaks) it works great.
But if the post contains line breaks I get this error in the console:
`SyntaxError: '' string literal contains an unescaped line break`
Using `the_content` doesn't work for me in this application, as it returns nothing at all.
How do I solve this?
EDIT:
This is how I pass the PHP variable to Javascript on button click:
```
onclick="searchEmail('<?php echo the_author_email(); ?>', '<?php echo the_title(); ?>', '<?php echo get_the_content(); ?>', '<?php echo $location ?>');"
```
And this is the javascript:
```
function searchEmail(email,title,content,location) {
var $url = (admin_ajax.url);
$.ajax({
type: "POST",
url: $url,
datatype: "html",
data: { 'action': 'search_notify_email', email: email, title: title, content: content, location: location },
success: function() {
searchNotification();
},error:function() {
searchNotificationError();
}
});
}
```
And lastly, this is the PHP function which receives the variable from Javascript and sends them via email:
```
function search_notify_email() {
// Set variables
$email = $_POST['email'];
$title = $_POST['title'];
$content = $_POST['content'];
$location = $_POST['location'];
// Change Email to HTML
add_filter( 'wp_mail_content_type', 'set_email_content_type' );
$to = $email;
$subject = "Test subjest";
$message = "<img src='https://example.com/favicon.png'><br><b>Test!</b>";
if (empty($title)) {
$message .= "<br><br><b>" . $_POST['content'] . "</b> test.<br> ";
}
else {
$message .= "<br><br><b>" . $_POST['content'] . "</b> test " . $_POST['title'] . " test.<br> ";
}
if (!empty($location)) {
$message .= "Test <b>" . $_POST['location'] . "</b>";
}
$headers[] = 'From: Test <[email protected]>';
if ( wp_mail($to, $subject, $message, $headers) ) {
// Success
} else {
// Error
}
die();
// Remove filter HTML content type
remove_filter( 'wp_mail_content_type', 'set_email_content_type' );
}
add_action('wp_ajax_nopriv_search_notify_email', 'search_notify_email');
add_action('wp_ajax_search_notify_email', 'search_notify_email');
// Reset Email content type to standard text/html
function set_email_content_type() {
return 'text/html';
}
``` | It sounds like you are directly echoing the php into a JavaScript variable? get\_the\_content makes no guarantees that the value it returns will be sanitized in the right way for a JavaScript variable.
You might try first encoding the output into JSON, and then doing that, i.e.
```
<script>
<?php
ob_start();
the_content();
$content = ob_get_clean();
?>
var myVariable = <?php echo json_encode( $content ); ?>;
</script>
```
To be honest it may not even work. It's hacky. Dropping php into JavaScript like this is really not a recommended practice, for exactly the reason you're encountering. What this solution does is poorly imitate the proper approach for when you have PHP data (i.e. the\_content) that you need in JavaScript -- AJAX.
Your JavaScript code should ask your PHP code to nicely provide sanitized data, i.e. it should make an AJAX request back to the server and your PHP code will have the opportunity to run, sanitize, and return the data cleanly. |
328,778 | <p>If you see <a href="https://askpuzzle.com/puzzle/what-can-point-in-every-direction-but-can-not-reach-the-destination-by-itself/" rel="nofollow noreferrer">this page</a>, text are aligned left side but I also want them to align centered vertically. Similar to <strong>Middle Align + Left Align</strong> in excel. </p>
<p>You can see this image to see what I am looking for <a href="https://i.stack.imgur.com/ysKpb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ysKpb.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 328758,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds like you are directly echoing the php into a JavaScript variable? get_the_content makes no guarantees that the value it returns will be sanitized in the right way for a JavaScript variable.</p>\n\n<p>You might try first encoding the output into JSON, and then doing that, i.e.</p>\n\n<pre><code><script>\n<?php\n ob_start();\n the_content();\n $content = ob_get_clean(); \n?>\nvar myVariable = <?php echo json_encode( $content ); ?>;\n</script>\n</code></pre>\n\n<p>To be honest it may not even work. It's hacky. Dropping php into JavaScript like this is really not a recommended practice, for exactly the reason you're encountering. What this solution does is poorly imitate the proper approach for when you have PHP data (i.e. the_content) that you need in JavaScript -- AJAX.</p>\n\n<p>Your JavaScript code should ask your PHP code to nicely provide sanitized data, i.e. it should make an AJAX request back to the server and your PHP code will have the opportunity to run, sanitize, and return the data cleanly.</p>\n"
},
{
"answer_id": 328759,
"author": "user141080",
"author_id": 141080,
"author_profile": "https://wordpress.stackexchange.com/users/141080",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is JavaScript. In JavaScript you can not across a string about multiple lines without to escape the line breaks. </p>\n\n<pre><code>var longString = 'This is a very long string which needs \n to wrap across multiple lines because \n otherwise my code is unreadable.';\n// SyntaxError: unterminated string literal\n</code></pre>\n\n<p>You could try to replace the line breaks with the + operator, a backslash, or template literals (ECMAScript 2015).</p>\n\n<p>text with the + operator:</p>\n\n<pre><code>var longString = 'This is a very long string which needs ' +\n 'to wrap across multiple lines because ' +\n 'otherwise my code is unreadable.';\n</code></pre>\n\n<p>text with backslashs:</p>\n\n<pre><code>var longString = 'This is a very long string which needs \\\n to wrap across multiple lines because \\\n otherwise my code is unreadable.';\n</code></pre>\n\n<p>text with template literals: </p>\n\n<pre><code>var longString = `This is a very long string which needs \n to wrap across multiple lines because\n otherwise my code is unreadable.`;\n</code></pre>\n\n<p>Source: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Unterminated_string_literal\" rel=\"nofollow noreferrer\">SyntaxError: unterminated string literal - MDN web docs</a></p>\n\n<p><strong>Edit:</strong></p>\n\n<p>To replace the new lines you could use this code:</p>\n\n<pre><code><?php \n\n// test string\n$str = \"This is a very long string which needs \nto wrap across multiple lines because \notherwise my code is unreadable.\";\n\nfunction replace_with_plus($str)\n{\n $str_array = explode ( \"\\n\" , $str );\n\n $len = count( $str_array );\n\n $str_2 = '';\n for($i = 0; $i < $len; $i ++)\n { \n $line = $str_array[$i];\n\n if($i > 0 )\n {\n $str_2 .= \"'\";\n }\n\n $str_2 .= $line;\n\n if($i < $len - 1 )\n {\n $str_2 .= \"' + \";\n }\n\n }\n\n return $str_2;\n}\n\n?>\n\n<script>\n\n// replace the \\n with the + operator\nvar test2 = '<?php echo replace_with_plus($str); ?>';\n\n</script>\n</code></pre>\n\n<p>Output in the browser:</p>\n\n<pre><code><script>\n\n// replace the \\n with the + operator\nvar test2 = 'This is a very long string which needs ' + 'to wrap across multiple lines because ' + 'otherwise my code is unreadable.';\n\n</script>\n</code></pre>\n\n<p>Like tmdesigned said the whole think with putting the content into a JavaScript value is really buggy and not the best way. </p>\n\n<p>I highly recommend you to use the way that czerspalace explained in his comment.</p>\n"
},
{
"answer_id": 328789,
"author": "joq3",
"author_id": 143279,
"author_profile": "https://wordpress.stackexchange.com/users/143279",
"pm_score": 1,
"selected": false,
"text": "<p>This is the solution:</p>\n\n<pre><code>ob_start();\nremove_filter ('the_content', 'wpautop'); the_content();\n$content = ob_get_contents();\nob_end_clean();\n</code></pre>\n\n<p>Together with:</p>\n\n<pre><code>echo str_replace(array(\"\\n\", \"\\r\"), ' + ', $content);\n</code></pre>\n\n<p>The only issue that remains now is that replacing the new lines with <code>+</code> results in duplicate <code>+ +</code> every new line. And removing either ´\\n´ or <code>\\r</code> results in the javascript error. So how do I get around that?</p>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328778",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101334/"
] | If you see [this page](https://askpuzzle.com/puzzle/what-can-point-in-every-direction-but-can-not-reach-the-destination-by-itself/), text are aligned left side but I also want them to align centered vertically. Similar to **Middle Align + Left Align** in excel.
You can see this image to see what I am looking for [](https://i.stack.imgur.com/ysKpb.png) | It sounds like you are directly echoing the php into a JavaScript variable? get\_the\_content makes no guarantees that the value it returns will be sanitized in the right way for a JavaScript variable.
You might try first encoding the output into JSON, and then doing that, i.e.
```
<script>
<?php
ob_start();
the_content();
$content = ob_get_clean();
?>
var myVariable = <?php echo json_encode( $content ); ?>;
</script>
```
To be honest it may not even work. It's hacky. Dropping php into JavaScript like this is really not a recommended practice, for exactly the reason you're encountering. What this solution does is poorly imitate the proper approach for when you have PHP data (i.e. the\_content) that you need in JavaScript -- AJAX.
Your JavaScript code should ask your PHP code to nicely provide sanitized data, i.e. it should make an AJAX request back to the server and your PHP code will have the opportunity to run, sanitize, and return the data cleanly. |
328,785 | <p>i would like to create a simple grid. You should get two columns (later more) to put content in there. But not only simple text. All content types should be available</p>
<p>My edit function</p>
<pre><code>registerBlockType(
'grids-2col', {
title: '2 Spalten',
icon: icon,
category: category,
attributes: {
paragraphLeft: {
type: "string",
selector: "div"
},
paragraphRight: {
type: "string",
selector: "div"
},
},
edit: function (props) {
var attributes = props.attributes,
className = props.className,
setAttributes = props.setAttributes;
var paragraphLeft = attributes.paragraphLeft,
paragraphRight = attributes.paragraphRight;
return [
createElement(
"div",
{ className: "main-wrapper-editor row" },
createElement(
"div",
{
className: "left col-md-6",
},
createElement(InnerBlocks, {
//tagName: "div",
className: className,
value: paragraphLeft,
onChange: function onChange(
newParagraphLeft
) {
setAttributes({
paragraphLeft: newParagraphLeft
});
},
placeholder:
"Inhalt linke Spalte"
})
),
createElement(
"div",
{
className: "right col-md-6",
},
createElement(InnerBlocks, {
//tagName: "div",
className: className,
value: paragraphRight,
onChange: function onChange(
newParagraphRight
) {
setAttributes({
paragraphRight: newParagraphRight
});
},
placeholder:
"Inhalt rechte Spalte"
})
)
)
];
},
</code></pre>
<p>The Problem is that the what i write in the left box ist cloned into the right one. How ist it possible to make more than one InnerBlock.</p>
<p>It works fine with RichText instead of InnerBlocks.</p>
| [
{
"answer_id": 329847,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>You can (at the moment) not use InnerBlocks more than once within a block. However, you can bypass this by using a template for your InnerBlocks that contain Blocks which support InnerBlocks instead, like the core/column block.</p>\n\n<p>Like this:</p>\n\n<pre><code>wp.element.createElement(InnerBlocks, {\n template: [['core/column',{},[['core/paragraph',{'placeholder':'Inhalt linke Spalte'}]]],['core/column',{},[['core/paragraph',{'placeholder':'Inhalt rechte Spalte'}]]]],\n templateLock: \"all\",\n allowedBlocks: ['core/column']});\n</code></pre>\n\n<p>Some time ago, i wrote a Block for a content/sidebar block with align left/right attributes, worked exactly like that.</p>\n\n<p>Happy Coding!</p>\n"
},
{
"answer_id": 381638,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 0,
"selected": false,
"text": "<p>Only one Innerblocks per block instance is allowed, as described in <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/inner-blocks\" rel=\"nofollow noreferrer\">Gutenberg official Innerblocks source documentation</a>. A workaround for distinct arrangement is also provided.</p>\n"
},
{
"answer_id": 381639,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>You can only have 1 innerblocks, it doesn't make sense to have separate sets of children. Just like a <code><div></div></code> element only has one "inside".</p>\n<p><strong>The official solution is to use composition.</strong></p>\n<p>So do what the <code>core/columns</code> block does, and create a new block that can only be placed inside.</p>\n<p>E.g. <code>core/columns</code> block can only contain <code>core/column</code> blocks. And <code>core/column</code> blocks can only be put inside a <code>core/columns</code> block.</p>\n<p>Likewise, if you want a container with rows, you need a container block and a row block.</p>\n<p>When building your containing block, pass the <code>allowedBlocks</code> prop to th <code>InnerBlocks</code> component.</p>\n<p>When registering your internal block ( column/row/etc ), specify the <code>parent</code> option and say that it can only be inserted inside your container block.</p>\n<p>This also means your sub-block has attributes, and can be selected. This means you can add options like width/height/style.</p>\n<p>If you need to restrict the number of child areas, you can use a template to pre-fill the sub-blocks and lock it so that they cannot be added or removed</p>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328785",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/150475/"
] | i would like to create a simple grid. You should get two columns (later more) to put content in there. But not only simple text. All content types should be available
My edit function
```
registerBlockType(
'grids-2col', {
title: '2 Spalten',
icon: icon,
category: category,
attributes: {
paragraphLeft: {
type: "string",
selector: "div"
},
paragraphRight: {
type: "string",
selector: "div"
},
},
edit: function (props) {
var attributes = props.attributes,
className = props.className,
setAttributes = props.setAttributes;
var paragraphLeft = attributes.paragraphLeft,
paragraphRight = attributes.paragraphRight;
return [
createElement(
"div",
{ className: "main-wrapper-editor row" },
createElement(
"div",
{
className: "left col-md-6",
},
createElement(InnerBlocks, {
//tagName: "div",
className: className,
value: paragraphLeft,
onChange: function onChange(
newParagraphLeft
) {
setAttributes({
paragraphLeft: newParagraphLeft
});
},
placeholder:
"Inhalt linke Spalte"
})
),
createElement(
"div",
{
className: "right col-md-6",
},
createElement(InnerBlocks, {
//tagName: "div",
className: className,
value: paragraphRight,
onChange: function onChange(
newParagraphRight
) {
setAttributes({
paragraphRight: newParagraphRight
});
},
placeholder:
"Inhalt rechte Spalte"
})
)
)
];
},
```
The Problem is that the what i write in the left box ist cloned into the right one. How ist it possible to make more than one InnerBlock.
It works fine with RichText instead of InnerBlocks. | You can (at the moment) not use InnerBlocks more than once within a block. However, you can bypass this by using a template for your InnerBlocks that contain Blocks which support InnerBlocks instead, like the core/column block.
Like this:
```
wp.element.createElement(InnerBlocks, {
template: [['core/column',{},[['core/paragraph',{'placeholder':'Inhalt linke Spalte'}]]],['core/column',{},[['core/paragraph',{'placeholder':'Inhalt rechte Spalte'}]]]],
templateLock: "all",
allowedBlocks: ['core/column']});
```
Some time ago, i wrote a Block for a content/sidebar block with align left/right attributes, worked exactly like that.
Happy Coding! |
328,793 | <p>I'm printing the last modified date via functions.php with the following code</p>
<pre><code>function wpb_last_updated_date( $content ) {
$u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
if ($u_modified_time >= $u_time + 86400) {
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a');
$custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
}
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
</code></pre>
<p>The problem is that it appears on pages too, but I need to appear only on posts. Is there an <code>if</code> command to choose only blog posts?
Thanks</p>
| [
{
"answer_id": 329847,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>You can (at the moment) not use InnerBlocks more than once within a block. However, you can bypass this by using a template for your InnerBlocks that contain Blocks which support InnerBlocks instead, like the core/column block.</p>\n\n<p>Like this:</p>\n\n<pre><code>wp.element.createElement(InnerBlocks, {\n template: [['core/column',{},[['core/paragraph',{'placeholder':'Inhalt linke Spalte'}]]],['core/column',{},[['core/paragraph',{'placeholder':'Inhalt rechte Spalte'}]]]],\n templateLock: \"all\",\n allowedBlocks: ['core/column']});\n</code></pre>\n\n<p>Some time ago, i wrote a Block for a content/sidebar block with align left/right attributes, worked exactly like that.</p>\n\n<p>Happy Coding!</p>\n"
},
{
"answer_id": 381638,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 0,
"selected": false,
"text": "<p>Only one Innerblocks per block instance is allowed, as described in <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/inner-blocks\" rel=\"nofollow noreferrer\">Gutenberg official Innerblocks source documentation</a>. A workaround for distinct arrangement is also provided.</p>\n"
},
{
"answer_id": 381639,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>You can only have 1 innerblocks, it doesn't make sense to have separate sets of children. Just like a <code><div></div></code> element only has one "inside".</p>\n<p><strong>The official solution is to use composition.</strong></p>\n<p>So do what the <code>core/columns</code> block does, and create a new block that can only be placed inside.</p>\n<p>E.g. <code>core/columns</code> block can only contain <code>core/column</code> blocks. And <code>core/column</code> blocks can only be put inside a <code>core/columns</code> block.</p>\n<p>Likewise, if you want a container with rows, you need a container block and a row block.</p>\n<p>When building your containing block, pass the <code>allowedBlocks</code> prop to th <code>InnerBlocks</code> component.</p>\n<p>When registering your internal block ( column/row/etc ), specify the <code>parent</code> option and say that it can only be inserted inside your container block.</p>\n<p>This also means your sub-block has attributes, and can be selected. This means you can add options like width/height/style.</p>\n<p>If you need to restrict the number of child areas, you can use a template to pre-fill the sub-blocks and lock it so that they cannot be added or removed</p>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328793",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161294/"
] | I'm printing the last modified date via functions.php with the following code
```
function wpb_last_updated_date( $content ) {
$u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
if ($u_modified_time >= $u_time + 86400) {
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a');
$custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
}
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
```
The problem is that it appears on pages too, but I need to appear only on posts. Is there an `if` command to choose only blog posts?
Thanks | You can (at the moment) not use InnerBlocks more than once within a block. However, you can bypass this by using a template for your InnerBlocks that contain Blocks which support InnerBlocks instead, like the core/column block.
Like this:
```
wp.element.createElement(InnerBlocks, {
template: [['core/column',{},[['core/paragraph',{'placeholder':'Inhalt linke Spalte'}]]],['core/column',{},[['core/paragraph',{'placeholder':'Inhalt rechte Spalte'}]]]],
templateLock: "all",
allowedBlocks: ['core/column']});
```
Some time ago, i wrote a Block for a content/sidebar block with align left/right attributes, worked exactly like that.
Happy Coding! |
328,803 | <p>I noticed in my wordpress/woocommerce setup that every time i add a tag to a product or a blog post. It adds that tag as a class into the listed item (Product/blog)</p>
<p>I also noticed it adds a class in the same place for every category i put these post items into.</p>
<p>How can i prevent wordpress and woocommerce from addings these tag and category names into my html markup as classes? As i do not need them and its creating a mess. </p>
<p>Thanks for any help! I could not locate a similar function anywhere.</p>
| [
{
"answer_id": 329847,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>You can (at the moment) not use InnerBlocks more than once within a block. However, you can bypass this by using a template for your InnerBlocks that contain Blocks which support InnerBlocks instead, like the core/column block.</p>\n\n<p>Like this:</p>\n\n<pre><code>wp.element.createElement(InnerBlocks, {\n template: [['core/column',{},[['core/paragraph',{'placeholder':'Inhalt linke Spalte'}]]],['core/column',{},[['core/paragraph',{'placeholder':'Inhalt rechte Spalte'}]]]],\n templateLock: \"all\",\n allowedBlocks: ['core/column']});\n</code></pre>\n\n<p>Some time ago, i wrote a Block for a content/sidebar block with align left/right attributes, worked exactly like that.</p>\n\n<p>Happy Coding!</p>\n"
},
{
"answer_id": 381638,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 0,
"selected": false,
"text": "<p>Only one Innerblocks per block instance is allowed, as described in <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/inner-blocks\" rel=\"nofollow noreferrer\">Gutenberg official Innerblocks source documentation</a>. A workaround for distinct arrangement is also provided.</p>\n"
},
{
"answer_id": 381639,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>You can only have 1 innerblocks, it doesn't make sense to have separate sets of children. Just like a <code><div></div></code> element only has one "inside".</p>\n<p><strong>The official solution is to use composition.</strong></p>\n<p>So do what the <code>core/columns</code> block does, and create a new block that can only be placed inside.</p>\n<p>E.g. <code>core/columns</code> block can only contain <code>core/column</code> blocks. And <code>core/column</code> blocks can only be put inside a <code>core/columns</code> block.</p>\n<p>Likewise, if you want a container with rows, you need a container block and a row block.</p>\n<p>When building your containing block, pass the <code>allowedBlocks</code> prop to th <code>InnerBlocks</code> component.</p>\n<p>When registering your internal block ( column/row/etc ), specify the <code>parent</code> option and say that it can only be inserted inside your container block.</p>\n<p>This also means your sub-block has attributes, and can be selected. This means you can add options like width/height/style.</p>\n<p>If you need to restrict the number of child areas, you can use a template to pre-fill the sub-blocks and lock it so that they cannot be added or removed</p>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328803",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136343/"
] | I noticed in my wordpress/woocommerce setup that every time i add a tag to a product or a blog post. It adds that tag as a class into the listed item (Product/blog)
I also noticed it adds a class in the same place for every category i put these post items into.
How can i prevent wordpress and woocommerce from addings these tag and category names into my html markup as classes? As i do not need them and its creating a mess.
Thanks for any help! I could not locate a similar function anywhere. | You can (at the moment) not use InnerBlocks more than once within a block. However, you can bypass this by using a template for your InnerBlocks that contain Blocks which support InnerBlocks instead, like the core/column block.
Like this:
```
wp.element.createElement(InnerBlocks, {
template: [['core/column',{},[['core/paragraph',{'placeholder':'Inhalt linke Spalte'}]]],['core/column',{},[['core/paragraph',{'placeholder':'Inhalt rechte Spalte'}]]]],
templateLock: "all",
allowedBlocks: ['core/column']});
```
Some time ago, i wrote a Block for a content/sidebar block with align left/right attributes, worked exactly like that.
Happy Coding! |
328,805 | <p>Hi everyone I have a question how can you create a dynamic copyright in WordPress with URL that goes back to the home page as well as a URL that goes to the designer of the theme</p>
| [
{
"answer_id": 328812,
"author": "Fabrizio Mele",
"author_id": 40463,
"author_profile": "https://wordpress.stackexchange.com/users/40463",
"pm_score": 1,
"selected": false,
"text": "<p>The fastest way is to look for the current copyright text inside your theme's <code>footer.php</code> file and substitute it with something more of your liking.</p>\n\n<p>My suggestion, as I don't know what you mean for \"dynamic\", is to substitute the current text with a function call, like <code><?php my_copyright_text() ?></code>, and then define that function in your theme's <code>function.php</code> file in which you do whatever you need to do.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function my_copyright_text(){\n\n $year = date(\"Y\",time());\n $company = \"Mycompany.com\";\n echo \"© 2018-$year $company\"; //this is effectively HTML code\n}\n</code></pre>\n\n<p>As the output of the function is HTML code you can insert tags and css classes as you like. For example <code>\"© 2018-$year <span class=\"company\">Mycompany.com</span>\"</code>.</p>\n\n<p><strong>It is strongly suggested to <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">use a child theme</a></strong>, as not to let theme updates overwrite your tweaks. </p>\n\n<p>If you feel brave you can put some of the parameters in the theme customizer, <a href=\"https://developer.wordpress.org/themes/customize-api/\" rel=\"nofollow noreferrer\">take a look here</a>.</p>\n"
},
{
"answer_id": 328823,
"author": "yogesh chatrola",
"author_id": 161314,
"author_profile": "https://wordpress.stackexchange.com/users/161314",
"pm_score": 0,
"selected": false,
"text": "<p>below code Update Copyright Year in a Website Dynamically </p>\n\n<pre><code>&copy; 2018 – <?php echo date('Y'); ?> <a href=\"#url\">YourSite.com</a>\n</code></pre>\n"
},
{
"answer_id": 328831,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p><strong>First you can put below code in your theme's functions.php file.</strong></p>\n</blockquote>\n\n<pre><code><?php\nfunction copyright_text(){\n $previous_year = date('Y') - 1;\n $current_year = date('Y');\n $company_url = esc_url(home_url('/'));\n $designer_url = 'http://www.designer-url.com';\n echo '<div>&copy; copyright '.$previous_year.' - '.$current_year.'<a href='.$company_url.' class=\"comp\"> company </a> and <a href='.$designer_url.' class=\"desg\" taret=\"_blank\"> designer </a></div>';\n}\n?>\n</code></pre>\n\n<p><strong>And Second you can use this code</strong> <code><?php echo copyright_text(); ?></code> <strong>where you want to display copyright in footer like your theme's footer.php file.</strong></p>\n\n<p><strong><em>Hope this code may help you. I have tested this code and it's working fine.</em></strong></p>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328805",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161300/"
] | Hi everyone I have a question how can you create a dynamic copyright in WordPress with URL that goes back to the home page as well as a URL that goes to the designer of the theme | The fastest way is to look for the current copyright text inside your theme's `footer.php` file and substitute it with something more of your liking.
My suggestion, as I don't know what you mean for "dynamic", is to substitute the current text with a function call, like `<?php my_copyright_text() ?>`, and then define that function in your theme's `function.php` file in which you do whatever you need to do.
```php
function my_copyright_text(){
$year = date("Y",time());
$company = "Mycompany.com";
echo "© 2018-$year $company"; //this is effectively HTML code
}
```
As the output of the function is HTML code you can insert tags and css classes as you like. For example `"© 2018-$year <span class="company">Mycompany.com</span>"`.
**It is strongly suggested to [use a child theme](https://developer.wordpress.org/themes/advanced-topics/child-themes/)**, as not to let theme updates overwrite your tweaks.
If you feel brave you can put some of the parameters in the theme customizer, [take a look here](https://developer.wordpress.org/themes/customize-api/). |
328,813 | <p>I have a page with with address localhost/ .
.In the navigation bar I have a new page link named Blog. SO wheni travel to that page the link is localhost/blog .
Now here is my thing ...when i click on any post of that page the next page permalink become
localhost/{The-post-name}.
what i want is to print the link fully...
like /localhost/blog/{the-post-name}. for every post i walk through this page</p>
| [
{
"answer_id": 328815,
"author": "tmdesigned",
"author_id": 28273,
"author_profile": "https://wordpress.stackexchange.com/users/28273",
"pm_score": -1,
"selected": false,
"text": "<p>You can add a rewrite rule to WordPress:</p>\n\n<pre><code>add_action( 'init', 'wpse_328813_rewrite' );\nfunction wpse_328813_rewrite()\n{\n add_rewrite_rule(\n '^blog/(.+)/?$', \n 'index.php?pagename=$matches[1]',\n 'top'\n );\n}\n</code></pre>\n\n<p>What that is saying is, \"WordPress, when someone requests a URL with \"blog\", followed by a slash, and then some text, maybe followed by another slash, try to load a page matching that slug. Oh, and do this before you try any of your other rewrite rules.\"</p>\n"
},
{
"answer_id": 328816,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>Just go to <em>Settings > Permalinks</em>, select <em>Custom Structure</em> and enter the following:</p>\n\n<pre><code>/blog/%postname%/\n</code></pre>\n\n<p>That will add <code>/blog/</code> to the beginning of post names in their permalinks. This will not affect Pages.</p>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328813",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161305/"
] | I have a page with with address localhost/ .
.In the navigation bar I have a new page link named Blog. SO wheni travel to that page the link is localhost/blog .
Now here is my thing ...when i click on any post of that page the next page permalink become
localhost/{The-post-name}.
what i want is to print the link fully...
like /localhost/blog/{the-post-name}. for every post i walk through this page | Just go to *Settings > Permalinks*, select *Custom Structure* and enter the following:
```
/blog/%postname%/
```
That will add `/blog/` to the beginning of post names in their permalinks. This will not affect Pages. |
328,830 | <p>I have a website where the home page is created in CodeIgniter (www.myweb.com) and the blogs are created in WordPress as a subdirectory (blog.myweb.com) and is hosted in AWS. I am trying to update the plugins and WordPress core but after I give FTP credentials, the error is <strong>Unable to locate WordPress content directory (wp-content)</strong>. What should I do. </p>
<p>I have tried setting the permission as per one of the <a href="https://wordpress.stackexchange.com/questions/206022/unable-to-locate-wordpress-content-directory-wp-content">thread</a> here. But no luck.</p>
<p>I have gone through some documentation and tried defining the plugin directory to <code>define( 'WP_PLUGIN_DIR', dirname(__FILE__) . '/blog/wp-content/plugins' );</code> but no luck here too.</p>
<p>Please advice to resolve the issue.</p>
| [
{
"answer_id": 328845,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>All files should be owned by the actual user's account, not the user account used for the httpd process.</li>\n<li>Group ownership is irrelevant unless there are specific group requirements for the web-server process permissions checking. This is not usually the case.</li>\n<li>All directories should be 755 or 750.</li>\n<li>All files should be 644 or 640. Exception: wp-config.php should be 440 or 400 to prevent other users on the server from reading it.</li>\n<li>No directories should ever be given 777, even upload directories. Since the PHP process is running as the owner of the files, it gets the owners permissions and - - can write to even a 755 directory.</li>\n</ul>\n\n<p>You can use </p>\n\n<pre><code>chown www-data:www-data -R * \nfind . -type d -exec chmod 755 {} \\; \nfind . -type f -exec chmod 644 {} \\; \n</code></pre>\n"
},
{
"answer_id": 329953,
"author": "Rony Samuel",
"author_id": 130682,
"author_profile": "https://wordpress.stackexchange.com/users/130682",
"pm_score": 0,
"selected": false,
"text": "<p>I tried the following and it worked</p>\n\n<pre><code>add_filter('filesystem_method', create_function('$a', 'return \"direct\";' ));\ndefine( 'FS_CHMOD_DIR', 0751 );\ndefine('WP_TEMP_DIR', ABSPATH . 'wp-content/tmp');\n</code></pre>\n\n<p>The <code>tmp</code> folder wasn't having the permission and that caused the website plugins from updating.</p>\n"
},
{
"answer_id": 381706,
"author": "Abhi",
"author_id": 200537,
"author_profile": "https://wordpress.stackexchange.com/users/200537",
"pm_score": 0,
"selected": false,
"text": "<p>This is user’s permission problem !!</p>\n<p>step-1 : First open wp-config.php file.</p>\n<p>step-2: paste it at the end of the <strong>wp-config.php</strong> file.</p>\n<p><strong>define('FS_METHOD','direct');</strong></p>\n<p>step-3: login as (root) username and its password.</p>\n<p>step-4: Copy below code and paste it into access console where you have to specify your plugin directory path and then hit enter.</p>\n<p><strong>chmod 777 /yourwebsitename/public/wp-content/plugins/</strong></p>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328830",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130682/"
] | I have a website where the home page is created in CodeIgniter (www.myweb.com) and the blogs are created in WordPress as a subdirectory (blog.myweb.com) and is hosted in AWS. I am trying to update the plugins and WordPress core but after I give FTP credentials, the error is **Unable to locate WordPress content directory (wp-content)**. What should I do.
I have tried setting the permission as per one of the [thread](https://wordpress.stackexchange.com/questions/206022/unable-to-locate-wordpress-content-directory-wp-content) here. But no luck.
I have gone through some documentation and tried defining the plugin directory to `define( 'WP_PLUGIN_DIR', dirname(__FILE__) . '/blog/wp-content/plugins' );` but no luck here too.
Please advice to resolve the issue. | * All files should be owned by the actual user's account, not the user account used for the httpd process.
* Group ownership is irrelevant unless there are specific group requirements for the web-server process permissions checking. This is not usually the case.
* All directories should be 755 or 750.
* All files should be 644 or 640. Exception: wp-config.php should be 440 or 400 to prevent other users on the server from reading it.
* No directories should ever be given 777, even upload directories. Since the PHP process is running as the owner of the files, it gets the owners permissions and - - can write to even a 755 directory.
You can use
```
chown www-data:www-data -R *
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
``` |
328,837 | <p>This code works really well. It displays the title of the post randomly with permalink but my objective is to display the thumbnail and/or featured image instead.</p>
<p>Any help would be appreciated.<a href="https://i.stack.imgur.com/0jlkE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0jlkE.jpg" alt="enter image description here"></a></p>
<pre><code><?php function wpb_rand_posts() {
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 5,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$string = '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .' </a></li>';
}
$string .= '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
$string .= 'no posts found';
}
return $string;
}
add_shortcode('random-posts','wpb_rand_posts');
add_filter('widget_text', 'do_shortcode'); ?>
</code></pre>
| [
{
"answer_id": 328845,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>All files should be owned by the actual user's account, not the user account used for the httpd process.</li>\n<li>Group ownership is irrelevant unless there are specific group requirements for the web-server process permissions checking. This is not usually the case.</li>\n<li>All directories should be 755 or 750.</li>\n<li>All files should be 644 or 640. Exception: wp-config.php should be 440 or 400 to prevent other users on the server from reading it.</li>\n<li>No directories should ever be given 777, even upload directories. Since the PHP process is running as the owner of the files, it gets the owners permissions and - - can write to even a 755 directory.</li>\n</ul>\n\n<p>You can use </p>\n\n<pre><code>chown www-data:www-data -R * \nfind . -type d -exec chmod 755 {} \\; \nfind . -type f -exec chmod 644 {} \\; \n</code></pre>\n"
},
{
"answer_id": 329953,
"author": "Rony Samuel",
"author_id": 130682,
"author_profile": "https://wordpress.stackexchange.com/users/130682",
"pm_score": 0,
"selected": false,
"text": "<p>I tried the following and it worked</p>\n\n<pre><code>add_filter('filesystem_method', create_function('$a', 'return \"direct\";' ));\ndefine( 'FS_CHMOD_DIR', 0751 );\ndefine('WP_TEMP_DIR', ABSPATH . 'wp-content/tmp');\n</code></pre>\n\n<p>The <code>tmp</code> folder wasn't having the permission and that caused the website plugins from updating.</p>\n"
},
{
"answer_id": 381706,
"author": "Abhi",
"author_id": 200537,
"author_profile": "https://wordpress.stackexchange.com/users/200537",
"pm_score": 0,
"selected": false,
"text": "<p>This is user’s permission problem !!</p>\n<p>step-1 : First open wp-config.php file.</p>\n<p>step-2: paste it at the end of the <strong>wp-config.php</strong> file.</p>\n<p><strong>define('FS_METHOD','direct');</strong></p>\n<p>step-3: login as (root) username and its password.</p>\n<p>step-4: Copy below code and paste it into access console where you have to specify your plugin directory path and then hit enter.</p>\n<p><strong>chmod 777 /yourwebsitename/public/wp-content/plugins/</strong></p>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328837",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161323/"
] | This code works really well. It displays the title of the post randomly with permalink but my objective is to display the thumbnail and/or featured image instead.
Any help would be appreciated.[](https://i.stack.imgur.com/0jlkE.jpg)
```
<?php function wpb_rand_posts() {
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 5,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$string = '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .' </a></li>';
}
$string .= '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
$string .= 'no posts found';
}
return $string;
}
add_shortcode('random-posts','wpb_rand_posts');
add_filter('widget_text', 'do_shortcode'); ?>
``` | * All files should be owned by the actual user's account, not the user account used for the httpd process.
* Group ownership is irrelevant unless there are specific group requirements for the web-server process permissions checking. This is not usually the case.
* All directories should be 755 or 750.
* All files should be 644 or 640. Exception: wp-config.php should be 440 or 400 to prevent other users on the server from reading it.
* No directories should ever be given 777, even upload directories. Since the PHP process is running as the owner of the files, it gets the owners permissions and - - can write to even a 755 directory.
You can use
```
chown www-data:www-data -R *
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
``` |
328,844 | <p>I want to convert my navigation menu into WordPress. tried with lots of snippets. But something I am missing. </p>
<p>Here is my menu example html: </p>
<p><code><div class="menu">
<a class="some-class" href="#">menu1</a>
<a class="some-class" href="#">menu2</a>
<a class="some-class" href="#">menu3</a>
<a class="some-class is-active" href="/sell">Menu4</a>
</div>
</code>
I have tried with this method: </p>
<p><code>
$menuLocations = get_nav_menu_locations();
$menuID = $menuLocations['primary'];
$primaryNav = wp_get_nav_menu_items($menuID);
foreach ( $primaryNav as $navItem ) {
echo '<a class="some-class" href="'.$navItem->url.'" title="'.$navItem->title.'">'.$navItem->title.'</a>';
}
</code>
I am getting good output. only problem with active menu item. </p>
<p>I am trying to add class <code>is-active</code> for the active navigation menu.
Thanks.
(updated question)</p>
| [
{
"answer_id": 328870,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>You need the current object id and compare it to the menu item id, I think. Maybe something like this,</p>\n\n<pre><code>$menuLocations = get_nav_menu_locations(); \n$menuID = $menuLocations['primary']; \n$primaryNav = wp_get_nav_menu_items($menuID);\n$current_object_id = get_queried_object_id();\nforeach ( $primaryNav as $navItem ) {\n // can't remember if this is the right way to get the page id or if there's a better way\n $menu_item_object_id = get_post_meta( $navItem, '_menu_item_object_id', true );\n $item_classes = ( $menu_item_object_id === $current_object_id ) ? 'some-class is-active': 'some-class';\n echo '<a class=\"' . $item_classes . '\" href=\"'.$navItem->url.'\" title=\"'.$navItem->title.'\">'.$navItem->title.'</a>';\n}\n</code></pre>\n"
},
{
"answer_id": 328882,
"author": "Sunny Johal",
"author_id": 161335,
"author_profile": "https://wordpress.stackexchange.com/users/161335",
"pm_score": 2,
"selected": true,
"text": "<p>You don't need to write a custom walker to achieve this. You can modify the output of the <code>wp_nav_menu()</code> function and hook into the appropriate default nav menu filter to modify the output of the individual menu items. E.g. (assuming your theme menu location is called primary)</p>\n\n<p>Put this in your functions.php file</p>\n\n<pre><code>/**\n * Output Custom Menu\n * \n * Call this function within your template\n * files wherever you want to output your\n * custom menu.\n * \n */\nfunction custom_theme_menu() {\n $menu = wp_nav_menu( array(\n 'theme_location' => 'primary',\n 'container_class' => 'menu',\n 'items_wrap' => '%3$s', // needed to remove the <ul> container tags\n 'fallback_cb' => false,\n 'echo' => false\n ) );\n\n // Strip out the <li> tags from the output.\n echo strip_tags( $menu,'<a>, <div>' );\n}\n\n\n/**\n * Add Nav Menu Item Link Classes\n * \n * Detects if we are rendering the custom menu\n * and adds the appropriate classnames.\n * \n */\nfunction custom_theme_nav_menu_link_attributes( $atts, $item, $args, $depth ) {\n // For all other menus return the defaults.\n if ( $args->theme_location !== 'primary' ) {\n return $atts;\n }\n\n // Add the link classes.\n $class_names = array( 'some-class' );\n\n if ( $item->current ) {\n $class_names[] = 'is-active';\n }\n\n $atts['class'] = join( ' ', $class_names );\n return $atts;\n}\nadd_filter( 'nav_menu_link_attributes', 'custom_theme_nav_menu_link_attributes', 10, 4 );\n</code></pre>\n\n<p>Then in your template files just call the following function wherever you want to output the menu:</p>\n\n<pre><code>custom_theme_menu();\n</code></pre>\n"
},
{
"answer_id": 328921,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 0,
"selected": false,
"text": "<p>Try with this one I think it's the simplest way to do what you want if you just want to add your desire classes. but if you want also markup as well better to follow @Sunny Johal answer.</p>\n\n<pre><code>/**\n * Filters the CSS class(es) applied to a menu item's list item element.\n *\n * @param array $classes The CSS classes that are applied to the menu item's `<li>` element.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\nfunction wpse64458_nav_class ($classes, $item, $args) {\n // Only affect the menu placed in the 'primary' wp_nav_bar() theme location\n // So change with your nav menu id\n if ( 'primary' === $args->theme_location ) {\n $classes[] = 'some-class';\n if (in_array('current-menu-item', $classes) ){\n $classes[] = 'is-active';\n }\n }\n return $classes;\n}\nadd_filter('nav_menu_css_class' , 'wpse64458_nav_class' , 10 , 3);\n</code></pre>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328844",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20831/"
] | I want to convert my navigation menu into WordPress. tried with lots of snippets. But something I am missing.
Here is my menu example html:
`<div class="menu">
<a class="some-class" href="#">menu1</a>
<a class="some-class" href="#">menu2</a>
<a class="some-class" href="#">menu3</a>
<a class="some-class is-active" href="/sell">Menu4</a>
</div>`
I have tried with this method:
`$menuLocations = get_nav_menu_locations();
$menuID = $menuLocations['primary'];
$primaryNav = wp_get_nav_menu_items($menuID);
foreach ( $primaryNav as $navItem ) {
echo '<a class="some-class" href="'.$navItem->url.'" title="'.$navItem->title.'">'.$navItem->title.'</a>';
}`
I am getting good output. only problem with active menu item.
I am trying to add class `is-active` for the active navigation menu.
Thanks.
(updated question) | You don't need to write a custom walker to achieve this. You can modify the output of the `wp_nav_menu()` function and hook into the appropriate default nav menu filter to modify the output of the individual menu items. E.g. (assuming your theme menu location is called primary)
Put this in your functions.php file
```
/**
* Output Custom Menu
*
* Call this function within your template
* files wherever you want to output your
* custom menu.
*
*/
function custom_theme_menu() {
$menu = wp_nav_menu( array(
'theme_location' => 'primary',
'container_class' => 'menu',
'items_wrap' => '%3$s', // needed to remove the <ul> container tags
'fallback_cb' => false,
'echo' => false
) );
// Strip out the <li> tags from the output.
echo strip_tags( $menu,'<a>, <div>' );
}
/**
* Add Nav Menu Item Link Classes
*
* Detects if we are rendering the custom menu
* and adds the appropriate classnames.
*
*/
function custom_theme_nav_menu_link_attributes( $atts, $item, $args, $depth ) {
// For all other menus return the defaults.
if ( $args->theme_location !== 'primary' ) {
return $atts;
}
// Add the link classes.
$class_names = array( 'some-class' );
if ( $item->current ) {
$class_names[] = 'is-active';
}
$atts['class'] = join( ' ', $class_names );
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'custom_theme_nav_menu_link_attributes', 10, 4 );
```
Then in your template files just call the following function wherever you want to output the menu:
```
custom_theme_menu();
``` |
328,849 | <p>Working on Wordpress / Woocommerce architecture,
I'm new in woocommerce, before i've worked on django and laravel framework, the project is a plugin wp, where a little form is fit with select tags for give me back some products by their sku.
I can get the products objects, but I can't override the wp_query returned by the ajax response and, at the same time override the archive loop template with my custom datas and display my final result. </p>
<p>Here is my class :
<pre>
if(!defined('EXCELREADER_ASSETS_URL'))
define('EXCELREADER_ASSETS_URL', dirname( <strong>FILE</strong> ));</p>
<p>class GetAllMenu
{</p>
<pre><code>public $tab;
public $id_product;
public function __construct(){
add_action( 'search-phone', array( $this, 'render_phone_search' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'init_plugin' ) );
add_action('wp_ajax_render_phone_search', array($this,'render_phone_search'));
add_action('wp_ajax_nopriv_render_phone_search', array($this,'render_phone_search'));
add_action( 'search-phone', array( $this, 'display_search_result' ) );
add_action('wp_ajax_display_search_result', array($this,'display_search_result'));
add_action('wp_ajax_nopriv_display_search_result', array($this,'display_search_result'));
}
public function init_plugin()
{
wp_enqueue_script(
'ajax_script',
plugins_url( 'assets/js/admin.js', EXCELREADER_ASSETS_URL ),
array('jquery'),
TRUE
);
wp_localize_script(
'ajax_script',
'searchAjax',
array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce( "search-phone" ),
)
);
}
public function render_phone_search(){
$id = urldecode($_POST['phone_id']);
if(isset($id)){
$objPhone = new ER_PhoneName();
$phone = $objPhone->get_phones_by_mark(trim($id));
include(EXCELREADER_TEMPLATE_URL . '/search-phone-widget.php');
}
exit;
}
public function render_mark_search(){
$mark = new ER_PhoneMark();
$data = $mark->call_all_mark_in_db();
include(EXCELREADER_TEMPLATE_URL . '/search-widget.php');
}
public function display_search_result(){
$sku = urldecode($_POST['sku_universel']);
$sku = explode(',',$sku);
$this->tab = array();
foreach($sku as $res){
$product = PhpSpreadReader::select_product_by_sku($res);
if($product){
$this->id_product[] = $product->get_id();
$this->tab[] = $product;
}
}
$args = array(
'post_type' => array('products'),
'post_status' => array('publish'),
'post__in' => $this->id_product
);
// The Query here is my problem =====================================
$ajaxposts = new WP_Query( $args );
$response = '';
// The Query i want to use my archive product in my theme not this one
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part('woocommerce/content-product');
}
} else {
$response .= get_template_part('none');
}
echo $response;
//echo get_language_attributes();
//echo $this->display_product_result();
exit;
}
public function changing_query_post($wp_query){
$wp_query->posts;
if ( $wp_query->is_home() && $wp_query->is_main_query() ) {
$wp_query->set( 'post__in', array($this->tab) );
}
return $wp_query;
}
public function render_search(){
$this->render_mark_search();
}
</code></pre>
<p>}</p>
<p>Here is my ajax call in js :</p>
<code> $(document).on("click", "#ex-form-submit", (e) => {
e.preventDefault()
if($("#option-mark").val() === "0"){
return;
}
let str = {
'action': 'display_search_result',
'sku_universel': $("#select-phone").val(),
};
// console.log(searchAjax.url);
$.ajax({
type : "post",
dataType : "html",
url : searchAjax.url,
data : str,
success: (response) => {
$('.grilleproduits').html(response).resize();
console.log(response);
},
error : (error) => console.log(error)
});
});
</code></pre>
<p>I can display all in js but it's not a right way to do this, cause some problems like the product title translation don't follow when the result is displayed.</p>
<p>Thanks in advance for any support and sorry for my nooby skills ! I answer only during week cause i don't have the code and website for my test in week end.</p>
<blockquote>
<p>edit : I forgot to say it's a plugin that i'm developing </p>
</blockquote>
| [
{
"answer_id": 328870,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>You need the current object id and compare it to the menu item id, I think. Maybe something like this,</p>\n\n<pre><code>$menuLocations = get_nav_menu_locations(); \n$menuID = $menuLocations['primary']; \n$primaryNav = wp_get_nav_menu_items($menuID);\n$current_object_id = get_queried_object_id();\nforeach ( $primaryNav as $navItem ) {\n // can't remember if this is the right way to get the page id or if there's a better way\n $menu_item_object_id = get_post_meta( $navItem, '_menu_item_object_id', true );\n $item_classes = ( $menu_item_object_id === $current_object_id ) ? 'some-class is-active': 'some-class';\n echo '<a class=\"' . $item_classes . '\" href=\"'.$navItem->url.'\" title=\"'.$navItem->title.'\">'.$navItem->title.'</a>';\n}\n</code></pre>\n"
},
{
"answer_id": 328882,
"author": "Sunny Johal",
"author_id": 161335,
"author_profile": "https://wordpress.stackexchange.com/users/161335",
"pm_score": 2,
"selected": true,
"text": "<p>You don't need to write a custom walker to achieve this. You can modify the output of the <code>wp_nav_menu()</code> function and hook into the appropriate default nav menu filter to modify the output of the individual menu items. E.g. (assuming your theme menu location is called primary)</p>\n\n<p>Put this in your functions.php file</p>\n\n<pre><code>/**\n * Output Custom Menu\n * \n * Call this function within your template\n * files wherever you want to output your\n * custom menu.\n * \n */\nfunction custom_theme_menu() {\n $menu = wp_nav_menu( array(\n 'theme_location' => 'primary',\n 'container_class' => 'menu',\n 'items_wrap' => '%3$s', // needed to remove the <ul> container tags\n 'fallback_cb' => false,\n 'echo' => false\n ) );\n\n // Strip out the <li> tags from the output.\n echo strip_tags( $menu,'<a>, <div>' );\n}\n\n\n/**\n * Add Nav Menu Item Link Classes\n * \n * Detects if we are rendering the custom menu\n * and adds the appropriate classnames.\n * \n */\nfunction custom_theme_nav_menu_link_attributes( $atts, $item, $args, $depth ) {\n // For all other menus return the defaults.\n if ( $args->theme_location !== 'primary' ) {\n return $atts;\n }\n\n // Add the link classes.\n $class_names = array( 'some-class' );\n\n if ( $item->current ) {\n $class_names[] = 'is-active';\n }\n\n $atts['class'] = join( ' ', $class_names );\n return $atts;\n}\nadd_filter( 'nav_menu_link_attributes', 'custom_theme_nav_menu_link_attributes', 10, 4 );\n</code></pre>\n\n<p>Then in your template files just call the following function wherever you want to output the menu:</p>\n\n<pre><code>custom_theme_menu();\n</code></pre>\n"
},
{
"answer_id": 328921,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 0,
"selected": false,
"text": "<p>Try with this one I think it's the simplest way to do what you want if you just want to add your desire classes. but if you want also markup as well better to follow @Sunny Johal answer.</p>\n\n<pre><code>/**\n * Filters the CSS class(es) applied to a menu item's list item element.\n *\n * @param array $classes The CSS classes that are applied to the menu item's `<li>` element.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\nfunction wpse64458_nav_class ($classes, $item, $args) {\n // Only affect the menu placed in the 'primary' wp_nav_bar() theme location\n // So change with your nav menu id\n if ( 'primary' === $args->theme_location ) {\n $classes[] = 'some-class';\n if (in_array('current-menu-item', $classes) ){\n $classes[] = 'is-active';\n }\n }\n return $classes;\n}\nadd_filter('nav_menu_css_class' , 'wpse64458_nav_class' , 10 , 3);\n</code></pre>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161218/"
] | Working on Wordpress / Woocommerce architecture,
I'm new in woocommerce, before i've worked on django and laravel framework, the project is a plugin wp, where a little form is fit with select tags for give me back some products by their sku.
I can get the products objects, but I can't override the wp\_query returned by the ajax response and, at the same time override the archive loop template with my custom datas and display my final result.
Here is my class :
```
if(!defined('EXCELREADER_ASSETS_URL'))
define('EXCELREADER_ASSETS_URL', dirname( **FILE** ));
```
class GetAllMenu
{
```
public $tab;
public $id_product;
public function __construct(){
add_action( 'search-phone', array( $this, 'render_phone_search' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'init_plugin' ) );
add_action('wp_ajax_render_phone_search', array($this,'render_phone_search'));
add_action('wp_ajax_nopriv_render_phone_search', array($this,'render_phone_search'));
add_action( 'search-phone', array( $this, 'display_search_result' ) );
add_action('wp_ajax_display_search_result', array($this,'display_search_result'));
add_action('wp_ajax_nopriv_display_search_result', array($this,'display_search_result'));
}
public function init_plugin()
{
wp_enqueue_script(
'ajax_script',
plugins_url( 'assets/js/admin.js', EXCELREADER_ASSETS_URL ),
array('jquery'),
TRUE
);
wp_localize_script(
'ajax_script',
'searchAjax',
array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce( "search-phone" ),
)
);
}
public function render_phone_search(){
$id = urldecode($_POST['phone_id']);
if(isset($id)){
$objPhone = new ER_PhoneName();
$phone = $objPhone->get_phones_by_mark(trim($id));
include(EXCELREADER_TEMPLATE_URL . '/search-phone-widget.php');
}
exit;
}
public function render_mark_search(){
$mark = new ER_PhoneMark();
$data = $mark->call_all_mark_in_db();
include(EXCELREADER_TEMPLATE_URL . '/search-widget.php');
}
public function display_search_result(){
$sku = urldecode($_POST['sku_universel']);
$sku = explode(',',$sku);
$this->tab = array();
foreach($sku as $res){
$product = PhpSpreadReader::select_product_by_sku($res);
if($product){
$this->id_product[] = $product->get_id();
$this->tab[] = $product;
}
}
$args = array(
'post_type' => array('products'),
'post_status' => array('publish'),
'post__in' => $this->id_product
);
// The Query here is my problem =====================================
$ajaxposts = new WP_Query( $args );
$response = '';
// The Query i want to use my archive product in my theme not this one
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part('woocommerce/content-product');
}
} else {
$response .= get_template_part('none');
}
echo $response;
//echo get_language_attributes();
//echo $this->display_product_result();
exit;
}
public function changing_query_post($wp_query){
$wp_query->posts;
if ( $wp_query->is_home() && $wp_query->is_main_query() ) {
$wp_query->set( 'post__in', array($this->tab) );
}
return $wp_query;
}
public function render_search(){
$this->render_mark_search();
}
```
}
Here is my ajax call in js :
`$(document).on("click", "#ex-form-submit", (e) => {
e.preventDefault()
if($("#option-mark").val() === "0"){
return;
}
let str = {
'action': 'display_search_result',
'sku_universel': $("#select-phone").val(),
};
// console.log(searchAjax.url);
$.ajax({
type : "post",
dataType : "html",
url : searchAjax.url,
data : str,
success: (response) => {
$('.grilleproduits').html(response).resize();
console.log(response);
},
error : (error) => console.log(error)
});
});`
I can display all in js but it's not a right way to do this, cause some problems like the product title translation don't follow when the result is displayed.
Thanks in advance for any support and sorry for my nooby skills ! I answer only during week cause i don't have the code and website for my test in week end.
>
> edit : I forgot to say it's a plugin that i'm developing
>
>
> | You don't need to write a custom walker to achieve this. You can modify the output of the `wp_nav_menu()` function and hook into the appropriate default nav menu filter to modify the output of the individual menu items. E.g. (assuming your theme menu location is called primary)
Put this in your functions.php file
```
/**
* Output Custom Menu
*
* Call this function within your template
* files wherever you want to output your
* custom menu.
*
*/
function custom_theme_menu() {
$menu = wp_nav_menu( array(
'theme_location' => 'primary',
'container_class' => 'menu',
'items_wrap' => '%3$s', // needed to remove the <ul> container tags
'fallback_cb' => false,
'echo' => false
) );
// Strip out the <li> tags from the output.
echo strip_tags( $menu,'<a>, <div>' );
}
/**
* Add Nav Menu Item Link Classes
*
* Detects if we are rendering the custom menu
* and adds the appropriate classnames.
*
*/
function custom_theme_nav_menu_link_attributes( $atts, $item, $args, $depth ) {
// For all other menus return the defaults.
if ( $args->theme_location !== 'primary' ) {
return $atts;
}
// Add the link classes.
$class_names = array( 'some-class' );
if ( $item->current ) {
$class_names[] = 'is-active';
}
$atts['class'] = join( ' ', $class_names );
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'custom_theme_nav_menu_link_attributes', 10, 4 );
```
Then in your template files just call the following function wherever you want to output the menu:
```
custom_theme_menu();
``` |
328,850 | <p>I got this error message when trying to upload EPS-files to my WordPress Media Library:</p>
<blockquote>
<p>Sorry, this file type is not permitted for security reasons</p>
</blockquote>
<p>So I added this snippet to my functions.php</p>
<pre><code>add_filter( 'upload_mimes', function ( $mime_types ) {
$mime_types[ 'eps' ] = 'application/postscript';
return $mime_types;
} );
</code></pre>
<p>After that I can upload several different EPS files locally on my development machine (Windows 10, PHP 7.0.19). However, on the remote server (CentOS, PHP 7.2.15), I still get the error message for <em>certain</em> EPS files. </p>
<p>After some debugging and troubleshooting I realized that the PHP versions differed so I downgraded PHP to version 7.0.33 on the remote server and suddenly I could upload all EPS files.</p>
<p>Any ideas regarding what the problem might be? Has something changed between PHP 7.0 and 7.2 that would make the <code>upload_mimes</code> filter fail?</p>
<p>WordPress is the latest version, 5.0.3.</p>
| [
{
"answer_id": 329362,
"author": "Tomas Eklund",
"author_id": 125005,
"author_profile": "https://wordpress.stackexchange.com/users/125005",
"pm_score": 4,
"selected": true,
"text": "<p>In recent versions of WordPress (<a href=\"https://make.wordpress.org/core/2018/12/13/backwards-compatibility-breaks-in-5-0-1/\" rel=\"noreferrer\">5.0.1</a> or higher) file upload security has been tightened by actually checking the content of an uploaded file using the PHP function <a href=\"http://php.net/manual/en/function.finfo-file.php\" rel=\"noreferrer\">finfo_file()</a> to determine if the file extension matches the MIME type. This has proven problematic since files with the same file type and extension may yield different MIME types.</p>\n\n<p>In my case one EPS file (let's call it <code>one.eps</code>) was detected as \"application/postscript\" while another file (let's call it <code>two.eps</code>) as \"image/x-eps\" or \"application/octet-stream\" depending on which PHP version the server was running.</p>\n\n<p>After adding the below PHP snippet I was consistently able to upload file <code>one.eps</code> to the WordPress Media Library no matter what version of PHP I was using. But the file <code>two.eps</code> could not be uploaded if the server was running PHP 7.2 or higher.</p>\n\n<pre><code>add_filter( 'upload_mimes', function ( $mime_types ) {\n $mime_types[ 'eps' ] = 'application/postscript';\n return $mime_types;\n} );\n</code></pre>\n\n<p>I'm by no means an expert on the EPS file format but I think it's safe to assume that different variations on the format exists. Opening the two files in different applications and checking the content strengthens this belief:</p>\n\n<p>Opening the files in a text editor:</p>\n\n<ul>\n<li><code>one.eps</code> Has an ASCII/human readable file header</li>\n<li><code>two.eps</code> Appears binary</li>\n</ul>\n\n<p>Format according to GIMP:</p>\n\n<ul>\n<li><code>one.eps</code> application/postscript</li>\n<li><code>two.eps</code> image/epsf</li>\n</ul>\n\n<p>Format according to finfo_file() on PHP 7.0.10:</p>\n\n<ul>\n<li><code>one.eps</code> application/postscript</li>\n<li><code>two.eps</code> application/octet-stream</li>\n</ul>\n\n<p>Format according to finfo_file() on PHP 7.3.2: </p>\n\n<ul>\n<li><code>one.eps</code> application/postscript</li>\n<li><code>two.eps</code> image/x-eps</li>\n</ul>\n\n<p>In the WordPress core file <code>wp-includes/functions.php</code>, function <code>wp_check_filetype_and_ext()</code> you will find the following:</p>\n\n<pre><code>// fileinfo often misidentifies obscure files as one of these types\n$nonspecific_types = array(\n 'application/octet-stream',\n 'application/encrypted',\n 'application/CDFV2-encrypted',\n 'application/zip',\n);\n</code></pre>\n\n<p>Further down in the function there is a hard-coded exception to allow these MIME types under certain circumstances. This is what made it possible to upload <code>two.eps</code> on earlier PHP versions, since <code>finfo_file()</code> reported \"application/octet-stream\" as its MIME type and this is one of the hard-coded exceptions.</p>\n\n<p>Unfortunately, there seems to be no mechanism in WordPress to allow the same extension to be mapped to different MIME types, which (to me) would be the most obvious solution. Something along the lines of:</p>\n\n<pre><code>add_filter( 'upload_mimes', function ( $mime_types ) {\n $mime_types[ 'eps' ] = array('application/postscript', 'image/x-eps');\n return $mime_types;\n} );\n</code></pre>\n\n<p>However, the user @birgire <a href=\"https://wordpress.stackexchange.com/questions/323750/how-to-assign-multiple-file-mime-types-to-extension/323757#323757\">posted a workaround as an answer</a> to a similar question.</p>\n"
},
{
"answer_id": 366650,
"author": "ALPHA-ALI Moise Moustapha hyme",
"author_id": 188114,
"author_profile": "https://wordpress.stackexchange.com/users/188114",
"pm_score": 2,
"selected": false,
"text": "<p>this is my solution for uploading eps or ai files in wordpress </p>\n\n<pre><code>function custom_wp_check_filetype_and_ext($filetype_and_ext, $file, $filename) {\n if(!$filetype_and_ext['ext'] || !$filetype_and_ext['type'] || !$filetype_and_ext['proper_filename']) {\n $extension = pathinfo($filename)['extension'];\n $mime_type = mime_content_type($file);\n $allowed_ext = array(\n 'eps' => array('application/postscript', 'image/x-eps'),\n 'ai' => array('application/postscript'),\n );\n if($allowed_ext[$extension]) {\n if(in_array($mime_type, $allowed_ext[$extension])) {\n $filetype_and_ext['ext'] = $extension;\n $filetype_and_ext['type'] = $mime_type;\n $filetype_and_ext['proper_filename'] = $filename;\n }\n }\n }\n return $filetype_and_ext;\n}\n\n/** **/\nadd_filter('wp_check_filetype_and_ext', 'custom_wp_check_filetype_and_ext', 5, 5);\n</code></pre>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125005/"
] | I got this error message when trying to upload EPS-files to my WordPress Media Library:
>
> Sorry, this file type is not permitted for security reasons
>
>
>
So I added this snippet to my functions.php
```
add_filter( 'upload_mimes', function ( $mime_types ) {
$mime_types[ 'eps' ] = 'application/postscript';
return $mime_types;
} );
```
After that I can upload several different EPS files locally on my development machine (Windows 10, PHP 7.0.19). However, on the remote server (CentOS, PHP 7.2.15), I still get the error message for *certain* EPS files.
After some debugging and troubleshooting I realized that the PHP versions differed so I downgraded PHP to version 7.0.33 on the remote server and suddenly I could upload all EPS files.
Any ideas regarding what the problem might be? Has something changed between PHP 7.0 and 7.2 that would make the `upload_mimes` filter fail?
WordPress is the latest version, 5.0.3. | In recent versions of WordPress ([5.0.1](https://make.wordpress.org/core/2018/12/13/backwards-compatibility-breaks-in-5-0-1/) or higher) file upload security has been tightened by actually checking the content of an uploaded file using the PHP function [finfo\_file()](http://php.net/manual/en/function.finfo-file.php) to determine if the file extension matches the MIME type. This has proven problematic since files with the same file type and extension may yield different MIME types.
In my case one EPS file (let's call it `one.eps`) was detected as "application/postscript" while another file (let's call it `two.eps`) as "image/x-eps" or "application/octet-stream" depending on which PHP version the server was running.
After adding the below PHP snippet I was consistently able to upload file `one.eps` to the WordPress Media Library no matter what version of PHP I was using. But the file `two.eps` could not be uploaded if the server was running PHP 7.2 or higher.
```
add_filter( 'upload_mimes', function ( $mime_types ) {
$mime_types[ 'eps' ] = 'application/postscript';
return $mime_types;
} );
```
I'm by no means an expert on the EPS file format but I think it's safe to assume that different variations on the format exists. Opening the two files in different applications and checking the content strengthens this belief:
Opening the files in a text editor:
* `one.eps` Has an ASCII/human readable file header
* `two.eps` Appears binary
Format according to GIMP:
* `one.eps` application/postscript
* `two.eps` image/epsf
Format according to finfo\_file() on PHP 7.0.10:
* `one.eps` application/postscript
* `two.eps` application/octet-stream
Format according to finfo\_file() on PHP 7.3.2:
* `one.eps` application/postscript
* `two.eps` image/x-eps
In the WordPress core file `wp-includes/functions.php`, function `wp_check_filetype_and_ext()` you will find the following:
```
// fileinfo often misidentifies obscure files as one of these types
$nonspecific_types = array(
'application/octet-stream',
'application/encrypted',
'application/CDFV2-encrypted',
'application/zip',
);
```
Further down in the function there is a hard-coded exception to allow these MIME types under certain circumstances. This is what made it possible to upload `two.eps` on earlier PHP versions, since `finfo_file()` reported "application/octet-stream" as its MIME type and this is one of the hard-coded exceptions.
Unfortunately, there seems to be no mechanism in WordPress to allow the same extension to be mapped to different MIME types, which (to me) would be the most obvious solution. Something along the lines of:
```
add_filter( 'upload_mimes', function ( $mime_types ) {
$mime_types[ 'eps' ] = array('application/postscript', 'image/x-eps');
return $mime_types;
} );
```
However, the user @birgire [posted a workaround as an answer](https://wordpress.stackexchange.com/questions/323750/how-to-assign-multiple-file-mime-types-to-extension/323757#323757) to a similar question. |
328,852 | <p>I have this piece of code and, although it works, I do not understand how.
First, I created a custom post type into my mu-plugins folder:</p>
<pre><code>function actor_init() {
$args = array(
'label' => 'actors',
'description' => 'hollywood & stuff',
'supports' => array(
'thumbnail',
'title',
'editor',
'comments'
),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
);
register_post_type('actor', $args);
}
</code></pre>
<p>then, in functions.php I hooked it.</p>
<pre><code>add_action( 'init', 'actor_init' );
</code></pre>
<p>Also, inside functions.php I created a function to display, if there is, the title of the post / page / custom-post</p>
<pre><code><?php
function provahel($arg) {
if (!$arg['title']) {
$arg['title'] = get_the_title();
}
?>
<h1><?php echo $arg['title'] ?></h1>
<?php } ?>
</code></pre>
<p>Finally, In my page.php, single-actor.php and single.php files I call the function inside the loop.</p>
<pre><code><?php
while(have_posts()) {
the_post();
provahel($argf);
?>
</code></pre>
<p>On the front end, correctly the title of the post gets rendered, either if it is a page, a post or the custom-post-type (in this case actor). Why? How Wordpress knows what parameter is passed into the provahel() functions? What is this parameter $argf (P.S. could be called in any way and it would still work)?<br>
Thanks in advance for any contribution. </p>
| [
{
"answer_id": 329362,
"author": "Tomas Eklund",
"author_id": 125005,
"author_profile": "https://wordpress.stackexchange.com/users/125005",
"pm_score": 4,
"selected": true,
"text": "<p>In recent versions of WordPress (<a href=\"https://make.wordpress.org/core/2018/12/13/backwards-compatibility-breaks-in-5-0-1/\" rel=\"noreferrer\">5.0.1</a> or higher) file upload security has been tightened by actually checking the content of an uploaded file using the PHP function <a href=\"http://php.net/manual/en/function.finfo-file.php\" rel=\"noreferrer\">finfo_file()</a> to determine if the file extension matches the MIME type. This has proven problematic since files with the same file type and extension may yield different MIME types.</p>\n\n<p>In my case one EPS file (let's call it <code>one.eps</code>) was detected as \"application/postscript\" while another file (let's call it <code>two.eps</code>) as \"image/x-eps\" or \"application/octet-stream\" depending on which PHP version the server was running.</p>\n\n<p>After adding the below PHP snippet I was consistently able to upload file <code>one.eps</code> to the WordPress Media Library no matter what version of PHP I was using. But the file <code>two.eps</code> could not be uploaded if the server was running PHP 7.2 or higher.</p>\n\n<pre><code>add_filter( 'upload_mimes', function ( $mime_types ) {\n $mime_types[ 'eps' ] = 'application/postscript';\n return $mime_types;\n} );\n</code></pre>\n\n<p>I'm by no means an expert on the EPS file format but I think it's safe to assume that different variations on the format exists. Opening the two files in different applications and checking the content strengthens this belief:</p>\n\n<p>Opening the files in a text editor:</p>\n\n<ul>\n<li><code>one.eps</code> Has an ASCII/human readable file header</li>\n<li><code>two.eps</code> Appears binary</li>\n</ul>\n\n<p>Format according to GIMP:</p>\n\n<ul>\n<li><code>one.eps</code> application/postscript</li>\n<li><code>two.eps</code> image/epsf</li>\n</ul>\n\n<p>Format according to finfo_file() on PHP 7.0.10:</p>\n\n<ul>\n<li><code>one.eps</code> application/postscript</li>\n<li><code>two.eps</code> application/octet-stream</li>\n</ul>\n\n<p>Format according to finfo_file() on PHP 7.3.2: </p>\n\n<ul>\n<li><code>one.eps</code> application/postscript</li>\n<li><code>two.eps</code> image/x-eps</li>\n</ul>\n\n<p>In the WordPress core file <code>wp-includes/functions.php</code>, function <code>wp_check_filetype_and_ext()</code> you will find the following:</p>\n\n<pre><code>// fileinfo often misidentifies obscure files as one of these types\n$nonspecific_types = array(\n 'application/octet-stream',\n 'application/encrypted',\n 'application/CDFV2-encrypted',\n 'application/zip',\n);\n</code></pre>\n\n<p>Further down in the function there is a hard-coded exception to allow these MIME types under certain circumstances. This is what made it possible to upload <code>two.eps</code> on earlier PHP versions, since <code>finfo_file()</code> reported \"application/octet-stream\" as its MIME type and this is one of the hard-coded exceptions.</p>\n\n<p>Unfortunately, there seems to be no mechanism in WordPress to allow the same extension to be mapped to different MIME types, which (to me) would be the most obvious solution. Something along the lines of:</p>\n\n<pre><code>add_filter( 'upload_mimes', function ( $mime_types ) {\n $mime_types[ 'eps' ] = array('application/postscript', 'image/x-eps');\n return $mime_types;\n} );\n</code></pre>\n\n<p>However, the user @birgire <a href=\"https://wordpress.stackexchange.com/questions/323750/how-to-assign-multiple-file-mime-types-to-extension/323757#323757\">posted a workaround as an answer</a> to a similar question.</p>\n"
},
{
"answer_id": 366650,
"author": "ALPHA-ALI Moise Moustapha hyme",
"author_id": 188114,
"author_profile": "https://wordpress.stackexchange.com/users/188114",
"pm_score": 2,
"selected": false,
"text": "<p>this is my solution for uploading eps or ai files in wordpress </p>\n\n<pre><code>function custom_wp_check_filetype_and_ext($filetype_and_ext, $file, $filename) {\n if(!$filetype_and_ext['ext'] || !$filetype_and_ext['type'] || !$filetype_and_ext['proper_filename']) {\n $extension = pathinfo($filename)['extension'];\n $mime_type = mime_content_type($file);\n $allowed_ext = array(\n 'eps' => array('application/postscript', 'image/x-eps'),\n 'ai' => array('application/postscript'),\n );\n if($allowed_ext[$extension]) {\n if(in_array($mime_type, $allowed_ext[$extension])) {\n $filetype_and_ext['ext'] = $extension;\n $filetype_and_ext['type'] = $mime_type;\n $filetype_and_ext['proper_filename'] = $filename;\n }\n }\n }\n return $filetype_and_ext;\n}\n\n/** **/\nadd_filter('wp_check_filetype_and_ext', 'custom_wp_check_filetype_and_ext', 5, 5);\n</code></pre>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328852",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158939/"
] | I have this piece of code and, although it works, I do not understand how.
First, I created a custom post type into my mu-plugins folder:
```
function actor_init() {
$args = array(
'label' => 'actors',
'description' => 'hollywood & stuff',
'supports' => array(
'thumbnail',
'title',
'editor',
'comments'
),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
);
register_post_type('actor', $args);
}
```
then, in functions.php I hooked it.
```
add_action( 'init', 'actor_init' );
```
Also, inside functions.php I created a function to display, if there is, the title of the post / page / custom-post
```
<?php
function provahel($arg) {
if (!$arg['title']) {
$arg['title'] = get_the_title();
}
?>
<h1><?php echo $arg['title'] ?></h1>
<?php } ?>
```
Finally, In my page.php, single-actor.php and single.php files I call the function inside the loop.
```
<?php
while(have_posts()) {
the_post();
provahel($argf);
?>
```
On the front end, correctly the title of the post gets rendered, either if it is a page, a post or the custom-post-type (in this case actor). Why? How Wordpress knows what parameter is passed into the provahel() functions? What is this parameter $argf (P.S. could be called in any way and it would still work)?
Thanks in advance for any contribution. | In recent versions of WordPress ([5.0.1](https://make.wordpress.org/core/2018/12/13/backwards-compatibility-breaks-in-5-0-1/) or higher) file upload security has been tightened by actually checking the content of an uploaded file using the PHP function [finfo\_file()](http://php.net/manual/en/function.finfo-file.php) to determine if the file extension matches the MIME type. This has proven problematic since files with the same file type and extension may yield different MIME types.
In my case one EPS file (let's call it `one.eps`) was detected as "application/postscript" while another file (let's call it `two.eps`) as "image/x-eps" or "application/octet-stream" depending on which PHP version the server was running.
After adding the below PHP snippet I was consistently able to upload file `one.eps` to the WordPress Media Library no matter what version of PHP I was using. But the file `two.eps` could not be uploaded if the server was running PHP 7.2 or higher.
```
add_filter( 'upload_mimes', function ( $mime_types ) {
$mime_types[ 'eps' ] = 'application/postscript';
return $mime_types;
} );
```
I'm by no means an expert on the EPS file format but I think it's safe to assume that different variations on the format exists. Opening the two files in different applications and checking the content strengthens this belief:
Opening the files in a text editor:
* `one.eps` Has an ASCII/human readable file header
* `two.eps` Appears binary
Format according to GIMP:
* `one.eps` application/postscript
* `two.eps` image/epsf
Format according to finfo\_file() on PHP 7.0.10:
* `one.eps` application/postscript
* `two.eps` application/octet-stream
Format according to finfo\_file() on PHP 7.3.2:
* `one.eps` application/postscript
* `two.eps` image/x-eps
In the WordPress core file `wp-includes/functions.php`, function `wp_check_filetype_and_ext()` you will find the following:
```
// fileinfo often misidentifies obscure files as one of these types
$nonspecific_types = array(
'application/octet-stream',
'application/encrypted',
'application/CDFV2-encrypted',
'application/zip',
);
```
Further down in the function there is a hard-coded exception to allow these MIME types under certain circumstances. This is what made it possible to upload `two.eps` on earlier PHP versions, since `finfo_file()` reported "application/octet-stream" as its MIME type and this is one of the hard-coded exceptions.
Unfortunately, there seems to be no mechanism in WordPress to allow the same extension to be mapped to different MIME types, which (to me) would be the most obvious solution. Something along the lines of:
```
add_filter( 'upload_mimes', function ( $mime_types ) {
$mime_types[ 'eps' ] = array('application/postscript', 'image/x-eps');
return $mime_types;
} );
```
However, the user @birgire [posted a workaround as an answer](https://wordpress.stackexchange.com/questions/323750/how-to-assign-multiple-file-mime-types-to-extension/323757#323757) to a similar question. |
328,862 | <p>I try to implement a function to notify users about changes on the webpage. I tried to use sessions for that but it did not work very well. For example:</p>
<p>A User can attend an event. To do that he has to register for it. So the status of his registration is 'on hold' at that moment. In the backend, i can accept his registration and change the status to 'accepted'. Now I want the user to see a notification on his dashboard that he was accepted.</p>
<p>For this, I use his last login date. I check if the change_date of his status was after his last login date. The value for registration_notifications is stored in a wp_session variable. This works without problem. If the user opens the page with the list of his registrations, this wp_session variable is reseted. And here comes the problem:</p>
<p>If I now change the status of a second registration of the same user, the notification is not shown.</p>
<p>My codes:</p>
<p>the function to get the notifications:</p>
<pre><code>if(!isset(wp_session['event'])){
wp_session['event']= $wpdb->get_var(SELECT COUNT..... change_date > last_login_date);
}
</code></pre>
<p>show notification:</p>
<pre><code>if(wp_session['event']!=-1){ echo wp_session['event']}
</code></pre>
<p>change session on the overview page:</p>
<pre><code>wp_session['event']=-1;
</code></pre>
<p>I need to change the code so, that I can recognize if there was a change in the amount of the notifications while the user was already online. But I could not figure out how to do that the best way.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 328863,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>Are the registrations saved as custom posts in the database? </p>\n\n<p>If so, perhaps you could have a private taxonomy / term call \"not_seen\". Whenever there are changes on the registration you would attach the custom term to it. </p>\n\n<p>Then add ajax to the page with the list of registrations. When the user visits the page the ajax kicks in and unsets the \"not_seen\" term from the registrations. </p>\n"
},
{
"answer_id": 328867,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>PHP only runs when you request a page. When the request is over, everything is gone. It's not like a Node application where the same program handles all the requests and variables can persist across pages just by defining them, so doing things with a <code>$wp_session</code> variable will only do things on that request.</p>\n\n<p>If you navigate to another page, it has to load WordPress again from scratch, and figure everything out fresh. This is why your code doesn't work, and that's how all PHP programs work.</p>\n\n<p>If you want to persist something, you have to store it somewhere, such as the database, the filesystem, or an object cache. That's what things like user meta for logged in users are used for.</p>\n\n<p>There is 1 exception, PHP Sessions using <code>$_SESSION</code> variables, but, they're not used by WordPress and need some setup. Additionally, they're incompatible with page caching solutions such as Varnish, Supercache, etc. Additionally, not all hosts support it. For example, PHP Sessions will not work correctly on WP Engine.</p>\n\n<p>Other notes:</p>\n\n<ul>\n<li>In PHP variables begin with <code>$</code> but yours don't for some reason. I would have expected PHP fatal errors.</li>\n<li>Global variables need to be declared before they're used</li>\n<li>You're doing an SQL query then dumping the result in a variable with no error processing which is a security risk</li>\n<li>You're displaying the result of that query without any formatting or escaping, which is also a security risk</li>\n<li>You need to end each statement in a <code>;</code>, your show notification example doesn't do this, and will generate syntax errors</li>\n<li><code>wp_session</code> is never created anywhere, so initially it's completely undefined. This will generate warnings and notices at runtime that fill your PHP error log</li>\n</ul>\n"
}
] | 2019/02/15 | [
"https://wordpress.stackexchange.com/questions/328862",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161342/"
] | I try to implement a function to notify users about changes on the webpage. I tried to use sessions for that but it did not work very well. For example:
A User can attend an event. To do that he has to register for it. So the status of his registration is 'on hold' at that moment. In the backend, i can accept his registration and change the status to 'accepted'. Now I want the user to see a notification on his dashboard that he was accepted.
For this, I use his last login date. I check if the change\_date of his status was after his last login date. The value for registration\_notifications is stored in a wp\_session variable. This works without problem. If the user opens the page with the list of his registrations, this wp\_session variable is reseted. And here comes the problem:
If I now change the status of a second registration of the same user, the notification is not shown.
My codes:
the function to get the notifications:
```
if(!isset(wp_session['event'])){
wp_session['event']= $wpdb->get_var(SELECT COUNT..... change_date > last_login_date);
}
```
show notification:
```
if(wp_session['event']!=-1){ echo wp_session['event']}
```
change session on the overview page:
```
wp_session['event']=-1;
```
I need to change the code so, that I can recognize if there was a change in the amount of the notifications while the user was already online. But I could not figure out how to do that the best way.
Thanks in advance. | PHP only runs when you request a page. When the request is over, everything is gone. It's not like a Node application where the same program handles all the requests and variables can persist across pages just by defining them, so doing things with a `$wp_session` variable will only do things on that request.
If you navigate to another page, it has to load WordPress again from scratch, and figure everything out fresh. This is why your code doesn't work, and that's how all PHP programs work.
If you want to persist something, you have to store it somewhere, such as the database, the filesystem, or an object cache. That's what things like user meta for logged in users are used for.
There is 1 exception, PHP Sessions using `$_SESSION` variables, but, they're not used by WordPress and need some setup. Additionally, they're incompatible with page caching solutions such as Varnish, Supercache, etc. Additionally, not all hosts support it. For example, PHP Sessions will not work correctly on WP Engine.
Other notes:
* In PHP variables begin with `$` but yours don't for some reason. I would have expected PHP fatal errors.
* Global variables need to be declared before they're used
* You're doing an SQL query then dumping the result in a variable with no error processing which is a security risk
* You're displaying the result of that query without any formatting or escaping, which is also a security risk
* You need to end each statement in a `;`, your show notification example doesn't do this, and will generate syntax errors
* `wp_session` is never created anywhere, so initially it's completely undefined. This will generate warnings and notices at runtime that fill your PHP error log |
328,914 | <p>I have added the custom Gutenberg block for my shortcode, but in checkbox control check uncheck does not work, please check code done as below:</p>
<pre><code>el( components.CheckboxControl, {
label: i18n.__( 'Display it?', 'txt-domain' ),
checked: props.attributes.myAttr,
onChange: function( val ) {
if( val ) {
props.setAttributes({ myAttr: '1' })
} else {
props.setAttributes({ myAttr: '0' })
}
}
} ),
</code></pre>
<p>if I remove the <code>checked: props.attributes.myAttr,</code> then it works fine but here, checkbox does not stay checked or uncheck. by the way it saves the value.</p>
| [
{
"answer_id": 328863,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>Are the registrations saved as custom posts in the database? </p>\n\n<p>If so, perhaps you could have a private taxonomy / term call \"not_seen\". Whenever there are changes on the registration you would attach the custom term to it. </p>\n\n<p>Then add ajax to the page with the list of registrations. When the user visits the page the ajax kicks in and unsets the \"not_seen\" term from the registrations. </p>\n"
},
{
"answer_id": 328867,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>PHP only runs when you request a page. When the request is over, everything is gone. It's not like a Node application where the same program handles all the requests and variables can persist across pages just by defining them, so doing things with a <code>$wp_session</code> variable will only do things on that request.</p>\n\n<p>If you navigate to another page, it has to load WordPress again from scratch, and figure everything out fresh. This is why your code doesn't work, and that's how all PHP programs work.</p>\n\n<p>If you want to persist something, you have to store it somewhere, such as the database, the filesystem, or an object cache. That's what things like user meta for logged in users are used for.</p>\n\n<p>There is 1 exception, PHP Sessions using <code>$_SESSION</code> variables, but, they're not used by WordPress and need some setup. Additionally, they're incompatible with page caching solutions such as Varnish, Supercache, etc. Additionally, not all hosts support it. For example, PHP Sessions will not work correctly on WP Engine.</p>\n\n<p>Other notes:</p>\n\n<ul>\n<li>In PHP variables begin with <code>$</code> but yours don't for some reason. I would have expected PHP fatal errors.</li>\n<li>Global variables need to be declared before they're used</li>\n<li>You're doing an SQL query then dumping the result in a variable with no error processing which is a security risk</li>\n<li>You're displaying the result of that query without any formatting or escaping, which is also a security risk</li>\n<li>You need to end each statement in a <code>;</code>, your show notification example doesn't do this, and will generate syntax errors</li>\n<li><code>wp_session</code> is never created anywhere, so initially it's completely undefined. This will generate warnings and notices at runtime that fill your PHP error log</li>\n</ul>\n"
}
] | 2019/02/16 | [
"https://wordpress.stackexchange.com/questions/328914",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123295/"
] | I have added the custom Gutenberg block for my shortcode, but in checkbox control check uncheck does not work, please check code done as below:
```
el( components.CheckboxControl, {
label: i18n.__( 'Display it?', 'txt-domain' ),
checked: props.attributes.myAttr,
onChange: function( val ) {
if( val ) {
props.setAttributes({ myAttr: '1' })
} else {
props.setAttributes({ myAttr: '0' })
}
}
} ),
```
if I remove the `checked: props.attributes.myAttr,` then it works fine but here, checkbox does not stay checked or uncheck. by the way it saves the value. | PHP only runs when you request a page. When the request is over, everything is gone. It's not like a Node application where the same program handles all the requests and variables can persist across pages just by defining them, so doing things with a `$wp_session` variable will only do things on that request.
If you navigate to another page, it has to load WordPress again from scratch, and figure everything out fresh. This is why your code doesn't work, and that's how all PHP programs work.
If you want to persist something, you have to store it somewhere, such as the database, the filesystem, or an object cache. That's what things like user meta for logged in users are used for.
There is 1 exception, PHP Sessions using `$_SESSION` variables, but, they're not used by WordPress and need some setup. Additionally, they're incompatible with page caching solutions such as Varnish, Supercache, etc. Additionally, not all hosts support it. For example, PHP Sessions will not work correctly on WP Engine.
Other notes:
* In PHP variables begin with `$` but yours don't for some reason. I would have expected PHP fatal errors.
* Global variables need to be declared before they're used
* You're doing an SQL query then dumping the result in a variable with no error processing which is a security risk
* You're displaying the result of that query without any formatting or escaping, which is also a security risk
* You need to end each statement in a `;`, your show notification example doesn't do this, and will generate syntax errors
* `wp_session` is never created anywhere, so initially it's completely undefined. This will generate warnings and notices at runtime that fill your PHP error log |
328,934 | <p>I moved my WordPress installations from my old server to a new one.
I copied all databases..etc and things seem to be working fine. (I have already migrated servers before, so I guess I know how to do the migration part correctly).
However I only have one problem with ALL my wp installations, when adding new items to navigation menu, the “add to menu” doesn’t work.
This video illustrates my problem: <a href="https://drive.google.com/file/d/1hEa2lNkavCm-EFfU7Ct8c88LOhRH9vl1/view" rel="nofollow noreferrer">https://drive.google.com/file/d/1hEa2lNkavCm-EFfU7Ct8c88LOhRH9vl1/view</a></p>
<p>I even did a new test installation from scratch just to see if the problem is due to copying files from another server, but I still have this issue with the new installation. So I guess it might be a server issue?</p>
<p>When I click add to menu the page reloads(which is unusual) then this appears in my console:</p>
<blockquote>
<p>"[Violation] Added non-passive event listener to a scroll-blocking
‘touchstart’ event. Consider marking event handler as ‘passive’ to
make the page more responsive. See
chromestatus.com/feature/5745543795965952</p>
</blockquote>
<p>" in load-scripts.php
I tried changing these in my php.ini</p>
<pre><code>post_max_size 20M
max_input_vars 10000
</code></pre>
<p>But it didn't solve the issue, however now nothing appears in the console.</p>
<p>I tried clearing my browser cache and the .htaccess file and I already have the following in my wp-config right before "that's all stop editing"</p>
<pre><code>define('WP_DEBUG', true);
define( 'CONCATENATE_SCRIPTS', true );
define( 'WP_MEMORY_LIMIT', '256M' );
</code></pre>
<p>The old server uses mariaDB 5.5, the new one uses 10.2, I’m not sure if this is related to the problem though…</p>
<p>Can anyone suggest a solution for this?
Hope someone can help me
And thanks in advance</p>
| [
{
"answer_id": 328863,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>Are the registrations saved as custom posts in the database? </p>\n\n<p>If so, perhaps you could have a private taxonomy / term call \"not_seen\". Whenever there are changes on the registration you would attach the custom term to it. </p>\n\n<p>Then add ajax to the page with the list of registrations. When the user visits the page the ajax kicks in and unsets the \"not_seen\" term from the registrations. </p>\n"
},
{
"answer_id": 328867,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>PHP only runs when you request a page. When the request is over, everything is gone. It's not like a Node application where the same program handles all the requests and variables can persist across pages just by defining them, so doing things with a <code>$wp_session</code> variable will only do things on that request.</p>\n\n<p>If you navigate to another page, it has to load WordPress again from scratch, and figure everything out fresh. This is why your code doesn't work, and that's how all PHP programs work.</p>\n\n<p>If you want to persist something, you have to store it somewhere, such as the database, the filesystem, or an object cache. That's what things like user meta for logged in users are used for.</p>\n\n<p>There is 1 exception, PHP Sessions using <code>$_SESSION</code> variables, but, they're not used by WordPress and need some setup. Additionally, they're incompatible with page caching solutions such as Varnish, Supercache, etc. Additionally, not all hosts support it. For example, PHP Sessions will not work correctly on WP Engine.</p>\n\n<p>Other notes:</p>\n\n<ul>\n<li>In PHP variables begin with <code>$</code> but yours don't for some reason. I would have expected PHP fatal errors.</li>\n<li>Global variables need to be declared before they're used</li>\n<li>You're doing an SQL query then dumping the result in a variable with no error processing which is a security risk</li>\n<li>You're displaying the result of that query without any formatting or escaping, which is also a security risk</li>\n<li>You need to end each statement in a <code>;</code>, your show notification example doesn't do this, and will generate syntax errors</li>\n<li><code>wp_session</code> is never created anywhere, so initially it's completely undefined. This will generate warnings and notices at runtime that fill your PHP error log</li>\n</ul>\n"
}
] | 2019/02/16 | [
"https://wordpress.stackexchange.com/questions/328934",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153834/"
] | I moved my WordPress installations from my old server to a new one.
I copied all databases..etc and things seem to be working fine. (I have already migrated servers before, so I guess I know how to do the migration part correctly).
However I only have one problem with ALL my wp installations, when adding new items to navigation menu, the “add to menu” doesn’t work.
This video illustrates my problem: <https://drive.google.com/file/d/1hEa2lNkavCm-EFfU7Ct8c88LOhRH9vl1/view>
I even did a new test installation from scratch just to see if the problem is due to copying files from another server, but I still have this issue with the new installation. So I guess it might be a server issue?
When I click add to menu the page reloads(which is unusual) then this appears in my console:
>
> "[Violation] Added non-passive event listener to a scroll-blocking
> ‘touchstart’ event. Consider marking event handler as ‘passive’ to
> make the page more responsive. See
> chromestatus.com/feature/5745543795965952
>
>
>
" in load-scripts.php
I tried changing these in my php.ini
```
post_max_size 20M
max_input_vars 10000
```
But it didn't solve the issue, however now nothing appears in the console.
I tried clearing my browser cache and the .htaccess file and I already have the following in my wp-config right before "that's all stop editing"
```
define('WP_DEBUG', true);
define( 'CONCATENATE_SCRIPTS', true );
define( 'WP_MEMORY_LIMIT', '256M' );
```
The old server uses mariaDB 5.5, the new one uses 10.2, I’m not sure if this is related to the problem though…
Can anyone suggest a solution for this?
Hope someone can help me
And thanks in advance | PHP only runs when you request a page. When the request is over, everything is gone. It's not like a Node application where the same program handles all the requests and variables can persist across pages just by defining them, so doing things with a `$wp_session` variable will only do things on that request.
If you navigate to another page, it has to load WordPress again from scratch, and figure everything out fresh. This is why your code doesn't work, and that's how all PHP programs work.
If you want to persist something, you have to store it somewhere, such as the database, the filesystem, or an object cache. That's what things like user meta for logged in users are used for.
There is 1 exception, PHP Sessions using `$_SESSION` variables, but, they're not used by WordPress and need some setup. Additionally, they're incompatible with page caching solutions such as Varnish, Supercache, etc. Additionally, not all hosts support it. For example, PHP Sessions will not work correctly on WP Engine.
Other notes:
* In PHP variables begin with `$` but yours don't for some reason. I would have expected PHP fatal errors.
* Global variables need to be declared before they're used
* You're doing an SQL query then dumping the result in a variable with no error processing which is a security risk
* You're displaying the result of that query without any formatting or escaping, which is also a security risk
* You need to end each statement in a `;`, your show notification example doesn't do this, and will generate syntax errors
* `wp_session` is never created anywhere, so initially it's completely undefined. This will generate warnings and notices at runtime that fill your PHP error log |
328,964 | <p>I want to remove the JS I added and gets versioned by wp.
I have a js script called base.js,
and wordpress loads that by itself like</p>
<pre><code><script type="text/javascript" src="../base.js?ver=4.9.9"></script>
</code></pre>
<p>this code removes the version number </p>
<pre><code>function remove_cssjs_ver( $src ) {
if( strpos( $src, '?ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
add_filter( 'style_loader_src', 'remove_cssjs_ver', 1000 );
add_filter( 'script_loader_src', 'remove_cssjs_ver', 1000 );
</code></pre>
<p>But what I want to do is stop WP from loading this JS completely.
i tried deregestering and dequeueing but it didnt work.</p>
| [
{
"answer_id": 328969,
"author": "Brada",
"author_id": 161366,
"author_profile": "https://wordpress.stackexchange.com/users/161366",
"pm_score": 2,
"selected": false,
"text": "<p>If I'm reading correctly you just want to deregister a script but failed... I think that you tried to deregister it too early( before was added ).</p>\n\n<pre><code>add_action( 'wp_print_scripts', 'example' );\nfunction example() {\n wp_dequeue_script( 'name_of_script' );\n}\n</code></pre>\n\n<p>By calling the function in 'wp_print_scripts' should be fine, which is latter than 'wp_enqueue_scripts', where you usually add.</p>\n"
},
{
"answer_id": 329019,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>If you want it to stop loading the javascript file then just remove the PHP code you have adding that script.</p>\n\n<p>What it really sounds like is that you don't want it to load on specific pages. You can use Brada's answer to dequeue a script (which I have to do for my plugins ALL time time due to sloppy developers), but really you should make sure that you're correctly registering and enqueueing the script, only when needed.</p>\n\n<p>You should first register the script using the <code>wp_enqueue_scripts</code>:</p>\n\n<pre><code>function wpdocs_theme_name_scripts() {\n wp_register_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n\n<p>And then and ONLY WHEN needed should you be calling <code>wp_enqueue_script</code>. This is one of the biggest issues I see with WordPress developers --- enqueuing scripts and styles on EVERY single page load -- which is BAD WordPress development practices.</p>\n\n<p>You can then normally call <code>wp_enqueue_script</code> or <code>wp_enqueue_style</code> in PHP code or files that is ran on that specific page you need it used on. </p>\n\n<p>The other option is to check the page in the <code>wp_enqueue_scripts</code> action to make sure it's your page before calling enqueue</p>\n"
}
] | 2019/02/17 | [
"https://wordpress.stackexchange.com/questions/328964",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159409/"
] | I want to remove the JS I added and gets versioned by wp.
I have a js script called base.js,
and wordpress loads that by itself like
```
<script type="text/javascript" src="../base.js?ver=4.9.9"></script>
```
this code removes the version number
```
function remove_cssjs_ver( $src ) {
if( strpos( $src, '?ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
add_filter( 'style_loader_src', 'remove_cssjs_ver', 1000 );
add_filter( 'script_loader_src', 'remove_cssjs_ver', 1000 );
```
But what I want to do is stop WP from loading this JS completely.
i tried deregestering and dequeueing but it didnt work. | If I'm reading correctly you just want to deregister a script but failed... I think that you tried to deregister it too early( before was added ).
```
add_action( 'wp_print_scripts', 'example' );
function example() {
wp_dequeue_script( 'name_of_script' );
}
```
By calling the function in 'wp\_print\_scripts' should be fine, which is latter than 'wp\_enqueue\_scripts', where you usually add. |
328,967 | <p>Wife transferred her domain from Godaddy to HostGator. Somehow the Post page is still linked to the old site. I say old site because she started fresh on the site only wanting the domain. Her domain was hersite.wordpress.com and now is just hersite.com. </p>
<p>All the content is where it should be until I assign the post page. No matter what page I set to be the post page for her blog it automatically wipes everything form that particular page except the header. Once I switch the post page settings back to "select" or none, the content is back to normal. What she didn't tell me was two weeks ago she was able to log into the old site and everything was the same except the blog ( set at post page ) was all from the new site. Sorry for the 3rd grade explanation of the issue. How do I fix this? </p>
| [
{
"answer_id": 328969,
"author": "Brada",
"author_id": 161366,
"author_profile": "https://wordpress.stackexchange.com/users/161366",
"pm_score": 2,
"selected": false,
"text": "<p>If I'm reading correctly you just want to deregister a script but failed... I think that you tried to deregister it too early( before was added ).</p>\n\n<pre><code>add_action( 'wp_print_scripts', 'example' );\nfunction example() {\n wp_dequeue_script( 'name_of_script' );\n}\n</code></pre>\n\n<p>By calling the function in 'wp_print_scripts' should be fine, which is latter than 'wp_enqueue_scripts', where you usually add.</p>\n"
},
{
"answer_id": 329019,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>If you want it to stop loading the javascript file then just remove the PHP code you have adding that script.</p>\n\n<p>What it really sounds like is that you don't want it to load on specific pages. You can use Brada's answer to dequeue a script (which I have to do for my plugins ALL time time due to sloppy developers), but really you should make sure that you're correctly registering and enqueueing the script, only when needed.</p>\n\n<p>You should first register the script using the <code>wp_enqueue_scripts</code>:</p>\n\n<pre><code>function wpdocs_theme_name_scripts() {\n wp_register_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n\n<p>And then and ONLY WHEN needed should you be calling <code>wp_enqueue_script</code>. This is one of the biggest issues I see with WordPress developers --- enqueuing scripts and styles on EVERY single page load -- which is BAD WordPress development practices.</p>\n\n<p>You can then normally call <code>wp_enqueue_script</code> or <code>wp_enqueue_style</code> in PHP code or files that is ran on that specific page you need it used on. </p>\n\n<p>The other option is to check the page in the <code>wp_enqueue_scripts</code> action to make sure it's your page before calling enqueue</p>\n"
}
] | 2019/02/17 | [
"https://wordpress.stackexchange.com/questions/328967",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161405/"
] | Wife transferred her domain from Godaddy to HostGator. Somehow the Post page is still linked to the old site. I say old site because she started fresh on the site only wanting the domain. Her domain was hersite.wordpress.com and now is just hersite.com.
All the content is where it should be until I assign the post page. No matter what page I set to be the post page for her blog it automatically wipes everything form that particular page except the header. Once I switch the post page settings back to "select" or none, the content is back to normal. What she didn't tell me was two weeks ago she was able to log into the old site and everything was the same except the blog ( set at post page ) was all from the new site. Sorry for the 3rd grade explanation of the issue. How do I fix this? | If I'm reading correctly you just want to deregister a script but failed... I think that you tried to deregister it too early( before was added ).
```
add_action( 'wp_print_scripts', 'example' );
function example() {
wp_dequeue_script( 'name_of_script' );
}
```
By calling the function in 'wp\_print\_scripts' should be fine, which is latter than 'wp\_enqueue\_scripts', where you usually add. |
328,978 | <p>I want to get the wp_editor (tinymce) content then find a sentence by specific word with regex. However, have no idea how to get the content</p>
<p>When a post is published or updated, the function will get the content and then find a sentence by the specific word.</p>
<p>My regex to get a whole sentence:</p>
<pre><code>$regex = '/<p>Chapter(.*?)<\/p>/'; //Specific Word = Chapter
$chapnumber = '';
$chaptitle = '';
$chapcontent = "<p>Chapter 136 – Tibet and West Turk</p>"; //This should be the content
if (preg_match($regex, $chapcontent, $matches)) {
echo $matches[1];
}
</code></pre>
<p>Any solution about this?</p>
| [
{
"answer_id": 328969,
"author": "Brada",
"author_id": 161366,
"author_profile": "https://wordpress.stackexchange.com/users/161366",
"pm_score": 2,
"selected": false,
"text": "<p>If I'm reading correctly you just want to deregister a script but failed... I think that you tried to deregister it too early( before was added ).</p>\n\n<pre><code>add_action( 'wp_print_scripts', 'example' );\nfunction example() {\n wp_dequeue_script( 'name_of_script' );\n}\n</code></pre>\n\n<p>By calling the function in 'wp_print_scripts' should be fine, which is latter than 'wp_enqueue_scripts', where you usually add.</p>\n"
},
{
"answer_id": 329019,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>If you want it to stop loading the javascript file then just remove the PHP code you have adding that script.</p>\n\n<p>What it really sounds like is that you don't want it to load on specific pages. You can use Brada's answer to dequeue a script (which I have to do for my plugins ALL time time due to sloppy developers), but really you should make sure that you're correctly registering and enqueueing the script, only when needed.</p>\n\n<p>You should first register the script using the <code>wp_enqueue_scripts</code>:</p>\n\n<pre><code>function wpdocs_theme_name_scripts() {\n wp_register_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n\n<p>And then and ONLY WHEN needed should you be calling <code>wp_enqueue_script</code>. This is one of the biggest issues I see with WordPress developers --- enqueuing scripts and styles on EVERY single page load -- which is BAD WordPress development practices.</p>\n\n<p>You can then normally call <code>wp_enqueue_script</code> or <code>wp_enqueue_style</code> in PHP code or files that is ran on that specific page you need it used on. </p>\n\n<p>The other option is to check the page in the <code>wp_enqueue_scripts</code> action to make sure it's your page before calling enqueue</p>\n"
}
] | 2019/02/17 | [
"https://wordpress.stackexchange.com/questions/328978",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149809/"
] | I want to get the wp\_editor (tinymce) content then find a sentence by specific word with regex. However, have no idea how to get the content
When a post is published or updated, the function will get the content and then find a sentence by the specific word.
My regex to get a whole sentence:
```
$regex = '/<p>Chapter(.*?)<\/p>/'; //Specific Word = Chapter
$chapnumber = '';
$chaptitle = '';
$chapcontent = "<p>Chapter 136 – Tibet and West Turk</p>"; //This should be the content
if (preg_match($regex, $chapcontent, $matches)) {
echo $matches[1];
}
```
Any solution about this? | If I'm reading correctly you just want to deregister a script but failed... I think that you tried to deregister it too early( before was added ).
```
add_action( 'wp_print_scripts', 'example' );
function example() {
wp_dequeue_script( 'name_of_script' );
}
```
By calling the function in 'wp\_print\_scripts' should be fine, which is latter than 'wp\_enqueue\_scripts', where you usually add. |
328,986 | <p>Users can upload an avatar as a local image file on my website. If they didn't do so, it will fall back to the WordPress default (Gravatar). But I want any occurrence of Gravatar to be replaced with a locally stored placeholder image.</p>
| [
{
"answer_id": 328988,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>OK, so there are some occurrences of <code>get_avatar()</code> in your site. If you'll take a look at docs for this function, you'll see, that:</p>\n\n<ul>\n<li>you pass URL for default avatar image as 3rd param,</li>\n<li>you pass <code>args</code> as 5th param.</li>\n</ul>\n\n<p>And one of these <code>args</code> is:</p>\n\n<blockquote>\n <p><strong>force_default</strong> (bool) (optional) Whether to always show the default\n image, never the Gravatar. Default: false.</p>\n</blockquote>\n\n<p>And as <code>default</code> you can use:</p>\n\n<blockquote>\n <p>URL for the default image or a default type. Accepts '404' (return a\n 404 instead of a default image), 'retro' (8bit), 'monsterid'\n (monster), 'wavatar' (cartoon face), 'indenticon' (the \"quilt\"),\n 'mystery', 'mm', or 'mysteryman' (The Oyster Man), 'blank'\n (transparent GIF), or 'gravatar_default' (the Gravatar logo). Default:\n Default is the value of the 'avatar_default' option, with a fallback\n of 'mystery'.</p>\n</blockquote>\n\n<h2>But...</h2>\n\n<p>if there are a lot of occurrences of <code>get_avatar</code> or you don't want to modify these occurrences (for example some of them come from plugins), then you can achieve this using filters.</p>\n\n<p>One way to do this would be to use <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_avatar/\" rel=\"nofollow noreferrer\"><code>pre_get_avatar</code></a> filter.</p>\n\n<p>If you'll return any non-null value, the rest of <code>get_avatar</code> function will get ignored and your result will be used as avatar. So you can use something like this, to do the trick:</p>\n\n<pre><code>function replace_all_avatars_with_default_one( $html, $id_or_email, $args ) {\n $url = '<URL TO DEFAULT AVATAR';\n $class = array();\n return $avatar = sprintf(\n \"<img alt='%s' src='%s' class='%s' height='%d' width='%d' %s/>\",\n esc_attr( $args['alt'] ),\n esc_url( $url ),\n esc_attr( join( ' ', $class ) ),\n (int) $args['height'],\n (int) $args['width'],\n $args['extra_attr']\n );\n}\nadd_filter( 'pre_get_avatar', 'replace_all_avatars_with_default_one', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 329261,
"author": "Trisha",
"author_id": 56458,
"author_profile": "https://wordpress.stackexchange.com/users/56458",
"pm_score": 1,
"selected": false,
"text": "<p>Krzysiek has a good solution, but I do this a bit differently...because I also want to allow users to upload a locally stored image and then fall back to Gravatar if they don't (or a default image if they have no Gravatar setup).</p>\n\n<p>I use ACF (Advanced Custom Fields) to let authors upload an image because it easily adds the image upload function to every user's profile page, but you may be using something different - however you allow them to upload and store the image you'll need the name of the usermeta field, my example below uses the meta field name 'author_profile_picture'.</p>\n\n<p>Also, I'm sure you already know this but for the benefit of others who may find this and need help, Gravatars are added by the Theme using WP's \"get_avatar\" function, so all you need to do is find where they're being added by the Theme and change that code. In SOME Themes, it calls code that is in a functions.php file or other includes in order to use get_avatar with a number of theme-controlled parameters, but you can just remove it entirely and replace it with new code to do what YOU want rather than what the Theme wants - just pay attention to image sizes so your styling still looks good.</p>\n\n<p>I use the code in my example below to find and display my usermeta field (if it exists) OR default to the gravatar/default image if it does not......this is a graceful way to allow users to choose a locally stored image or their Gravatar, but you could also choose to display no image if you really don't want Gravatar images used.</p>\n\n<p>Here's my code with notes </p>\n\n<pre><code> <?php \n\n global $user; \\\\ necessary to access ALL user meta fields\n\n $authorimage = get_the_author_meta('author_profile_picture', $user->ID );\n\n if ( $authorimage ) { ?>\n <img src=\"<?php echo $authorimage; ?>\" class=\"authorimg\" /> \n <?php\n } else { \n echo get_avatar( get_the_author_meta( 'user_email' ) ); \\\\ to display the Gravatar or Default image\n \\\\ OR you can do something different if you DON'T want Gravatar\n echo 'no author image available'; \\\\ Lots of options here, you can choose to do whatever if no image has been uploaded\n } ?>\n\n<h4>Meet The Author: <?php the_author(); ?></h4>\n<div itemprop=\"description\" class=\"description\">\n<p><?php echo get_the_author_meta('description',$user->ID); ?></p>\n</div>\n</code></pre>\n"
}
] | 2019/02/17 | [
"https://wordpress.stackexchange.com/questions/328986",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133010/"
] | Users can upload an avatar as a local image file on my website. If they didn't do so, it will fall back to the WordPress default (Gravatar). But I want any occurrence of Gravatar to be replaced with a locally stored placeholder image. | OK, so there are some occurrences of `get_avatar()` in your site. If you'll take a look at docs for this function, you'll see, that:
* you pass URL for default avatar image as 3rd param,
* you pass `args` as 5th param.
And one of these `args` is:
>
> **force\_default** (bool) (optional) Whether to always show the default
> image, never the Gravatar. Default: false.
>
>
>
And as `default` you can use:
>
> URL for the default image or a default type. Accepts '404' (return a
> 404 instead of a default image), 'retro' (8bit), 'monsterid'
> (monster), 'wavatar' (cartoon face), 'indenticon' (the "quilt"),
> 'mystery', 'mm', or 'mysteryman' (The Oyster Man), 'blank'
> (transparent GIF), or 'gravatar\_default' (the Gravatar logo). Default:
> Default is the value of the 'avatar\_default' option, with a fallback
> of 'mystery'.
>
>
>
But...
------
if there are a lot of occurrences of `get_avatar` or you don't want to modify these occurrences (for example some of them come from plugins), then you can achieve this using filters.
One way to do this would be to use [`pre_get_avatar`](https://developer.wordpress.org/reference/hooks/pre_get_avatar/) filter.
If you'll return any non-null value, the rest of `get_avatar` function will get ignored and your result will be used as avatar. So you can use something like this, to do the trick:
```
function replace_all_avatars_with_default_one( $html, $id_or_email, $args ) {
$url = '<URL TO DEFAULT AVATAR';
$class = array();
return $avatar = sprintf(
"<img alt='%s' src='%s' class='%s' height='%d' width='%d' %s/>",
esc_attr( $args['alt'] ),
esc_url( $url ),
esc_attr( join( ' ', $class ) ),
(int) $args['height'],
(int) $args['width'],
$args['extra_attr']
);
}
add_filter( 'pre_get_avatar', 'replace_all_avatars_with_default_one', 10, 3 );
``` |
328,990 | <p>I have two drop downs. The first one contains list of parent taxonomies from a custom post type. And the second one contains all the sub-taxonomies at a time. But I'm trying to display only those sub-taxonomies of <strong>selected</strong> parent taxonomy (not all the sub-taxonomies from other parent taxonomies). For example, if I select a parent taxonomy from the first dropdown, then second dropdown should only display the sub-taxonomies of it. I'm not finding any <code>php</code> logic to achieve this goal. I'm displaying these two dropdowns on 'Edit Profile' page. Here is my code on <code>functions.php</code></p>
<pre><code><?php
function slcustom_user_profile_fields($user) { ?>
<h1 id="temppp">Select a parent taxonomy</h1>
<select name="parent_category" id="parent_category">
<?php
global $wpdb;
$parentCat = $wpdb->get_results( "SELECT name FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE taxonomy = 'project_category' AND parent = 0)" );
foreach ( $parentCat as $cat ) { ?>
<option value="<?php echo esc_attr( $cat->name ) ?>"<?php echo selected( $user->parent_category, $cat->name ); ?>><?php echo $cat->name; ?></option>
<?php }
?>
</select>
<p>Select a child taxonomy</p>
<select name="child_category" id="child_category">
<?php
//trying to bring this $termName value from JS
if(isset($_POST['selectedParentName'])) {
$termName = isset($_POST['selectedParentName']);
}
$termId = get_term_by('name', $termName, 'project_category');
$selectedTermId = $termId->term_id;
$id = $selectedTermId;
$childCats = $wpdb->get_results( "SELECT name FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE taxonomy = 'project_category' AND parent = ".$id." )" );
foreach ($childCats as $childCat) { ?>
<option value="<?php echo esc_attr( $childCat->name ) ?>"<?php echo selected( $user->child_category, $childCat->name ); ?>><?php echo $childCat->name; ?></option>
<?php }
?>
</select>
<?php
}
add_action('show_user_profile', 'slcustom_user_profile_fields');
add_action('edit_user_profile', 'slcustom_user_profile_fields');
function save_custom_user_profile_fields($user_id) {
if( current_user_can('edit_user', $user_id) ) {
update_user_meta($user_id, 'parent_category', $_POST['parent_category']);
update_user_meta($user_id, 'child_category', $_POST['child_category']);
}
}
add_action('personal_options_update', 'save_custom_user_profile_fields');
add_action('edit_user_profile_update', 'save_custom_user_profile_fields');
</code></pre>
<p><strong>script.js</strong></p>
<pre><code>$('select#parent_category').on('change', function() {
var selectedParentName = this.value; //it tracks changes dropdown value
$.ajax({
type: 'POST',
url: 'http://localhost:3000/wp-content/themes/mytheme/functions.php',
data: { selectedParentName : selectedParentName }, //trying to send this 'selectedParentName' to functions.php
success: function(data) {
var sendThisDataToPHP = selectedParentName;
}
});
});
</code></pre>
<p>Updated Feb 19, 2019: script.js added and few lines on functions.php to receiving JS variable.</p>
| [
{
"answer_id": 328992,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 1,
"selected": false,
"text": "<p>You could achieve that by using js / jQuery. There might be more ways to it, but two comes into my mind. </p>\n\n<ol>\n<li>Watch for changes on the parent select and populate the child select\noptions with ajax based on the selected parent option.</li>\n<li>Watch for changes on the parent select and hide the unrelated options from the\nchild select based on the selected parent option.</li>\n</ol>\n\n<hr>\n\n<p><strong>EDIT 19.2.2019</strong></p>\n\n<pre><code>add_action( 'wp_ajax_my_action', 'my_action' );\nfunction my_action() {\n\n // check if user is logged in\n // is ajax request nonce valid\n // other stuff to make sure we can trust this request\n\n $selected_aprent_tax = strip_tags($_POST['parent_cat']);\n\n $tax_query = new WP_Tax_Query(array(\n 'taxonomy' => 'project_category',\n 'parent' => $selected_aprent_tax,\n ));\n\n if ( $tax_query->terms ) {\n wp_send_json_success( $tax_query->terms );\n } else {\n wp_send_json( array() );\n wp_die();\n }\n\n}\n</code></pre>\n\n<p>Then use <code>my_action</code> as the action parameter in your ajax request to trigger the function above. And send the ajax request to <code>admin_url( 'admin-ajax.php' )</code>.</p>\n\n<p>With your jQuery script you would then grab the terms the php returns and do whatever you want with them. E.g. create select options from them.</p>\n\n<p><strong>NB</strong> It's quite late as I'm typing this so it's not a perfect example, but a rough one. Please refer to the codex to make the example work in your case, <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n"
},
{
"answer_id": 329228,
"author": "hamdirizal",
"author_id": 133145,
"author_profile": "https://wordpress.stackexchange.com/users/133145",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a simple <em>foreach</em> loop.</p>\n\n<p>Let say I have a custom taxonomy <strong>\"books\"</strong></p>\n\n<p>This is how I get all the parents terms:</p>\n\n<pre><code>$terms = get_terms(array('taxonomy' => 'books', 'hide_empty' => false ));\n$parents = array();\nforeach ($terms as $item) {\n if($item->parent===0){\n $parents[] = $item;\n }\n}\nprint_r($parents); //Show all the parent objects\n</code></pre>\n\n<p>On ajax call, send the parent id, to get the list of children objects, like this:</p>\n\n<pre><code>$parent = $_POST['parent'];\n$terms = get_terms(array('taxonomy' => 'books', 'hide_empty' => false ));\n$children = array();\nforeach ($terms as $item) {\n if($item->parent === $parent){\n $children[] = $item;\n }\n}\nprint_r($children); //show all children objects\n</code></pre>\n"
},
{
"answer_id": 329278,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 4,
"selected": true,
"text": "<p>Here's a fully functional snippet for doing this.</p>\n\n<ul>\n<li>I added the correct WordPress table stylings</li>\n<li>This requires adding my <code>smyles_get_taxonomy_hierarchy</code> to add children of taxonomy to the term object</li>\n<li>This hides the child dropdown if no children exist</li>\n<li>This handles everything (and saves) based on <code>TERM ID</code> not the <code>NAME</code> .. you should always use term ID as if you decide to change the wording/slug later on you will have all kinds of issues</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/ixMem.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ixMem.gif\" alt=\"example\"></a></p>\n\n<p>Seems code syntax highlighter on here can't handle mix of HTML/JS/PHP, so here's a GitHub Gist of working code:\n<a href=\"https://gist.github.com/tripflex/527dd82db1d1f3bf82f761486fcc3303\" rel=\"nofollow noreferrer\">https://gist.github.com/tripflex/527dd82db1d1f3bf82f761486fcc3303</a></p>\n\n<p>Breakdown:</p>\n\n<p>You first need to include my function to generate taxonomy array with children in that term object:</p>\n\n<pre><code>if ( ! function_exists( 'smyles_get_taxonomy_hierarchy' ) ) {\n /**\n * Recursively get taxonomy and its children\n *\n * @param string $taxonomy\n * @param int $parent Parent term ID (0 for top level)\n * @param array $args Array of arguments to pass to get_terms (to override default)\n *\n * @return array\n */\n function smyles_get_taxonomy_hierarchy( $taxonomy, $parent = 0, $args = array( 'hide_empty' => false ) ) {\n\n $defaults = array(\n 'parent' => $parent,\n 'hide_empty' => false\n );\n $r = wp_parse_args( $args, $defaults );\n // get all direct decendants of the $parent\n $terms = get_terms( $taxonomy, $r );\n // prepare a new array. these are the children of $parent\n // we'll ultimately copy all the $terms into this new array, but only after they\n // find their own children\n $children = array();\n // go through all the direct decendants of $parent, and gather their children\n foreach ( $terms as $term ) {\n // recurse to get the direct decendants of \"this\" term\n $term->children = smyles_get_taxonomy_hierarchy( $taxonomy, $term->term_id );\n // add the term to our new array\n $children[ $term->term_id ] = $term;\n }\n\n // send the results back to the caller\n return $children;\n }\n}\n</code></pre>\n\n<p>jQuery/JavaScript code handling:</p>\n\n<pre><code>jQuery( function($){\n // slcustom_categories var should be available here\n $('#parent_category').change( function(e){\n var child_cat_select = $( '#child_category' );\n var term_id = $(this).val();\n\n console.log( 'Parent Category Changed', term_id );\n\n // Remove any existing\n child_cat_select.find( 'option' ).remove();\n\n // Loop through children and add to children dropdown\n if( slcustom_categories && slcustom_categories[ term_id ] && slcustom_categories[ term_id ]['children'] ){\n console.log( 'Adding Children', slcustom_categories[ term_id ]['children'] );\n $.each( slcustom_categories[term_id]['children'], function( i, v ){\n console.log( 'Adding Child: ', v );\n child_cat_select.append( '<option value=\"' + v['term_id'] + '\">' + v[ 'name' ] + '</option>');\n });\n\n // Show if child cats\n $( '#child_category_row' ).show();\n } else {\n // Hide if no child cats\n $( '#child_category_row' ).hide();\n }\n });\n\n // Trigger change on initial page load to load child categories\n $('#parent_category').change();\n});\n</code></pre>\n\n<p>Function to output fields:</p>\n\n<pre><code>function slcustom_user_profile_fields( $user ){\n\n $categories = smyles_get_taxonomy_hierarchy( 'project_category' );\n $parent_category = $user->parent_category;\n $child_category = $user->child_category;\n// $parent_category = 52; // used for testing\n// $child_category = 82; // used for testing\n $parent_has_children = ! empty( $parent_category ) && $categories[ $parent_category ] && ! empty( $categories[ $parent_category ]->children );\n\n // Creative way to use wp_localize_script which creates a JS variable from array\n // You should actually change this to load your JavaScript file and move JS below to that file\n wp_register_script( 'slcustom_user_profile_fields', '' );\n wp_localize_script( 'slcustom_user_profile_fields', 'slcustom_categories', $categories );\n wp_enqueue_script( 'slcustom_user_profile_fields' );\n ?>\n <h1 id=\"temppp\">Select a parent taxonomy</h1>\n <table class=\"form-table\">\n <tbody>\n <tr>\n <th>\n Parent\n </th>\n <td>\n <select name=\"parent_category\" id=\"parent_category\">\n <?php\n foreach( (array) $categories as $term_id => $cat ){\n ?>\n <option value=\"<?php echo esc_attr( $term_id ) ?>\"<?php echo selected( $parent_category, $term_id ); ?>><?php echo $cat->name; ?></option>\n <?php\n }\n ?>\n </select>\n </td>\n </tr>\n <tr id=\"child_category_row\" style=\"<?php if( ! $parent_has_children ){ echo 'display: none;'; }?>\">\n <th>\n Child\n </th>\n <td>\n <select name=\"child_category\" id=\"child_category\">\n <?php\n if( $parent_has_children ){\n foreach( (array) $categories[$parent_category]->children as $c_term_id => $child ){\n ?>\n <option value=\"<?php echo esc_attr( $c_term_id ) ?>\"<?php echo selected( $child_category, $c_term_id ); ?>><?php echo $child->name; ?></option>\n <?php\n }\n }\n ?>\n </select>\n </td>\n </tr>\n </tbody>\n </table>\n <?php\n}\n</code></pre>\n"
}
] | 2019/02/17 | [
"https://wordpress.stackexchange.com/questions/328990",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113702/"
] | I have two drop downs. The first one contains list of parent taxonomies from a custom post type. And the second one contains all the sub-taxonomies at a time. But I'm trying to display only those sub-taxonomies of **selected** parent taxonomy (not all the sub-taxonomies from other parent taxonomies). For example, if I select a parent taxonomy from the first dropdown, then second dropdown should only display the sub-taxonomies of it. I'm not finding any `php` logic to achieve this goal. I'm displaying these two dropdowns on 'Edit Profile' page. Here is my code on `functions.php`
```
<?php
function slcustom_user_profile_fields($user) { ?>
<h1 id="temppp">Select a parent taxonomy</h1>
<select name="parent_category" id="parent_category">
<?php
global $wpdb;
$parentCat = $wpdb->get_results( "SELECT name FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE taxonomy = 'project_category' AND parent = 0)" );
foreach ( $parentCat as $cat ) { ?>
<option value="<?php echo esc_attr( $cat->name ) ?>"<?php echo selected( $user->parent_category, $cat->name ); ?>><?php echo $cat->name; ?></option>
<?php }
?>
</select>
<p>Select a child taxonomy</p>
<select name="child_category" id="child_category">
<?php
//trying to bring this $termName value from JS
if(isset($_POST['selectedParentName'])) {
$termName = isset($_POST['selectedParentName']);
}
$termId = get_term_by('name', $termName, 'project_category');
$selectedTermId = $termId->term_id;
$id = $selectedTermId;
$childCats = $wpdb->get_results( "SELECT name FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE taxonomy = 'project_category' AND parent = ".$id." )" );
foreach ($childCats as $childCat) { ?>
<option value="<?php echo esc_attr( $childCat->name ) ?>"<?php echo selected( $user->child_category, $childCat->name ); ?>><?php echo $childCat->name; ?></option>
<?php }
?>
</select>
<?php
}
add_action('show_user_profile', 'slcustom_user_profile_fields');
add_action('edit_user_profile', 'slcustom_user_profile_fields');
function save_custom_user_profile_fields($user_id) {
if( current_user_can('edit_user', $user_id) ) {
update_user_meta($user_id, 'parent_category', $_POST['parent_category']);
update_user_meta($user_id, 'child_category', $_POST['child_category']);
}
}
add_action('personal_options_update', 'save_custom_user_profile_fields');
add_action('edit_user_profile_update', 'save_custom_user_profile_fields');
```
**script.js**
```
$('select#parent_category').on('change', function() {
var selectedParentName = this.value; //it tracks changes dropdown value
$.ajax({
type: 'POST',
url: 'http://localhost:3000/wp-content/themes/mytheme/functions.php',
data: { selectedParentName : selectedParentName }, //trying to send this 'selectedParentName' to functions.php
success: function(data) {
var sendThisDataToPHP = selectedParentName;
}
});
});
```
Updated Feb 19, 2019: script.js added and few lines on functions.php to receiving JS variable. | Here's a fully functional snippet for doing this.
* I added the correct WordPress table stylings
* This requires adding my `smyles_get_taxonomy_hierarchy` to add children of taxonomy to the term object
* This hides the child dropdown if no children exist
* This handles everything (and saves) based on `TERM ID` not the `NAME` .. you should always use term ID as if you decide to change the wording/slug later on you will have all kinds of issues
[](https://i.stack.imgur.com/ixMem.gif)
Seems code syntax highlighter on here can't handle mix of HTML/JS/PHP, so here's a GitHub Gist of working code:
<https://gist.github.com/tripflex/527dd82db1d1f3bf82f761486fcc3303>
Breakdown:
You first need to include my function to generate taxonomy array with children in that term object:
```
if ( ! function_exists( 'smyles_get_taxonomy_hierarchy' ) ) {
/**
* Recursively get taxonomy and its children
*
* @param string $taxonomy
* @param int $parent Parent term ID (0 for top level)
* @param array $args Array of arguments to pass to get_terms (to override default)
*
* @return array
*/
function smyles_get_taxonomy_hierarchy( $taxonomy, $parent = 0, $args = array( 'hide_empty' => false ) ) {
$defaults = array(
'parent' => $parent,
'hide_empty' => false
);
$r = wp_parse_args( $args, $defaults );
// get all direct decendants of the $parent
$terms = get_terms( $taxonomy, $r );
// prepare a new array. these are the children of $parent
// we'll ultimately copy all the $terms into this new array, but only after they
// find their own children
$children = array();
// go through all the direct decendants of $parent, and gather their children
foreach ( $terms as $term ) {
// recurse to get the direct decendants of "this" term
$term->children = smyles_get_taxonomy_hierarchy( $taxonomy, $term->term_id );
// add the term to our new array
$children[ $term->term_id ] = $term;
}
// send the results back to the caller
return $children;
}
}
```
jQuery/JavaScript code handling:
```
jQuery( function($){
// slcustom_categories var should be available here
$('#parent_category').change( function(e){
var child_cat_select = $( '#child_category' );
var term_id = $(this).val();
console.log( 'Parent Category Changed', term_id );
// Remove any existing
child_cat_select.find( 'option' ).remove();
// Loop through children and add to children dropdown
if( slcustom_categories && slcustom_categories[ term_id ] && slcustom_categories[ term_id ]['children'] ){
console.log( 'Adding Children', slcustom_categories[ term_id ]['children'] );
$.each( slcustom_categories[term_id]['children'], function( i, v ){
console.log( 'Adding Child: ', v );
child_cat_select.append( '<option value="' + v['term_id'] + '">' + v[ 'name' ] + '</option>');
});
// Show if child cats
$( '#child_category_row' ).show();
} else {
// Hide if no child cats
$( '#child_category_row' ).hide();
}
});
// Trigger change on initial page load to load child categories
$('#parent_category').change();
});
```
Function to output fields:
```
function slcustom_user_profile_fields( $user ){
$categories = smyles_get_taxonomy_hierarchy( 'project_category' );
$parent_category = $user->parent_category;
$child_category = $user->child_category;
// $parent_category = 52; // used for testing
// $child_category = 82; // used for testing
$parent_has_children = ! empty( $parent_category ) && $categories[ $parent_category ] && ! empty( $categories[ $parent_category ]->children );
// Creative way to use wp_localize_script which creates a JS variable from array
// You should actually change this to load your JavaScript file and move JS below to that file
wp_register_script( 'slcustom_user_profile_fields', '' );
wp_localize_script( 'slcustom_user_profile_fields', 'slcustom_categories', $categories );
wp_enqueue_script( 'slcustom_user_profile_fields' );
?>
<h1 id="temppp">Select a parent taxonomy</h1>
<table class="form-table">
<tbody>
<tr>
<th>
Parent
</th>
<td>
<select name="parent_category" id="parent_category">
<?php
foreach( (array) $categories as $term_id => $cat ){
?>
<option value="<?php echo esc_attr( $term_id ) ?>"<?php echo selected( $parent_category, $term_id ); ?>><?php echo $cat->name; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr id="child_category_row" style="<?php if( ! $parent_has_children ){ echo 'display: none;'; }?>">
<th>
Child
</th>
<td>
<select name="child_category" id="child_category">
<?php
if( $parent_has_children ){
foreach( (array) $categories[$parent_category]->children as $c_term_id => $child ){
?>
<option value="<?php echo esc_attr( $c_term_id ) ?>"<?php echo selected( $child_category, $c_term_id ); ?>><?php echo $child->name; ?></option>
<?php
}
}
?>
</select>
</td>
</tr>
</tbody>
</table>
<?php
}
``` |
329,007 | <p>I am trying to build an Custom Post Type for showing information about events. The Custom Post Type has name 'Event', with the following meta fields: </p>
<ul>
<li>event_startdate <em>(date in format YYYY-MM-DD)</em></li>
<li>event_enddate <em>(date in format YYYY-MM-DD)</em></li>
</ul>
<p>This works fine for the single-event listing, however in the archive listing I would like to see a grouping like: </p>
<h2>2019</h2>
<h3>March</h3>
<ul>
<li>Title of event starting in march</li>
<li>Title of another event starting in march</li>
</ul>
<h3>May</h3>
<ul>
<li>Title of may event</li>
</ul>
<h3>December</h3>
<ul>
<li>Title of Christmas event</li>
</ul>
<h2>2020</h2>
<h3>January</h3>
<ul>
<li>Title of 2020 vision event</li>
</ul>
<p>I have found some questions and answers on using wp_get_archives(), however this seems to group the posts by published date, rather on the actual date of the event (event.startdate). I also found some posts on sorting by metavalue, however not grouping. Thanks in advance for any advice or hint on how to accomplish this!</p>
| [
{
"answer_id": 329012,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>OK, so this problem has two parts:</p>\n\n<ol>\n<li>Make WordPress to sort these posts properly.</li>\n<li>Make WordPress to display them with all that grouping.</li>\n</ol>\n\n<h2>1. Sorting CPT by meta value on archive</h2>\n\n<p>You can use <code>pre_get_posts</code> to achieve this. </p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $query ) {\n if ( is_post_type_archive( 'event' ) && $query->is_main_query() ) {\n $query->set( 'orderby', 'meta_value' );\n $query->set( 'order', 'ASC' );\n $query->set( 'meta_key', 'event_startdate' );\n }\n} );\n</code></pre>\n\n<p>So now events will be sorted ascending by start_date. </p>\n\n<h2>2. Displaying and grouping</h2>\n\n<p>You'll have to modify the <code>archive-event.php</code> file, so these events get in their groups.</p>\n\n<pre><code><?php\n $current_year = $current_month = '';\n\n while ( have_posts() ) :\n the_post();\n\n $last_year = $current_year;\n $last_month = $current_month;\n\n $current_year = date( 'Y', strtotime( get_post_meta( get_the_ID(), 'event_startdate', true ) ) );\n if ( $last_year != $current_year ) {\n $last_month = '';\n }\n $current_month = date( 'F', strtotime( get_post_meta( get_the_ID(), 'event_startdate', true ) ) );\n?>\n <?php if ( $last_year != $current_year ) : ?><h2><?php echo $current_year; ?></h2><?php endif; ?>\n <?php if ( $last_month != $current_month ) : ?><h3><?php echo $current_month; ?></h3><?php endif; ?>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n<?php endwhile; ?>\n</code></pre>\n"
},
{
"answer_id": 329023,
"author": "Ole Kristian Losvik",
"author_id": 107055,
"author_profile": "https://wordpress.stackexchange.com/users/107055",
"pm_score": 0,
"selected": false,
"text": "<p>Based on the code from @krzysiek-dróżdż my <code>archive-eventi.php</code> is now like below. Posting it here incase anyone else is trying to achieve the same thing. Note that the event custom post type is named <code>eventi</code>. </p>\n\n<pre><code><?php\n/**\n * The template for displaying event archive\n *\n * @package Eventi\n * @since 1.0.0\n */\nget_header();\n?>\n\n <section id=\"primary\" class=\"content-area\">\n <main id=\"main\" class=\"site-main\">\n\n <?php\n if ( have_posts() ) :\n ?>\n\n <header class=\"page-header\">\n <?php\n the_archive_title( '<h1 class=\"page-title\">', '</h1>' );\n ?>\n </header><!-- .page-header -->\n\n <?php\n // Start the Loop.\n $args = [\n 'post_status' => 'publish',\n 'post_type' => 'eventi',\n 'posts_per_page' => 100,\n 'orderby' => 'meta_value',\n 'order' => 'ASC',\n 'meta_type' => 'DATE',\n 'meta_key' => 'eventi_startdate',\n ];\n\n $posts = new WP_Query( $args );\n $current_year = '';\n $current_month = '';\n while ( $posts->have_posts() ) {\n ?>\n <article id=\"event-<?php the_ID(); ?>\" <?php post_class(); ?>>\n <div class=\"entry-content\">\n <?php\n $posts->the_post();\n $post_id = get_the_id();\n\n $startdate = strtotime( get_post_meta( $post_id, 'eventi_startdate', true ) );\n $enddate = strtotime( get_post_meta( $post_id, 'eventi_enddate', true ) );\n $dateformat = get_option( 'date_format' );\n\n $last_year = $current_year;\n $last_month = $current_month;\n $current_year = date_i18n( 'Y', $startdate );\n if ( $last_year != $current_year ) {\n $last_month = '';\n }\n $current_month = date_i18n( 'F', $startdate );\n\n if ( $last_year != $current_year ) {\n echo '<h2>' . $current_year . '</h2>';\n }\n\n if ( $last_month != $current_month ) {\n echo '<h3>' . $current_month . '</h3>';\n }\n\n $post_id = get_the_ID();\n if ( is_sticky() && is_home() && ! is_paged() ) {\n printf( '<span class=\"sticky-post\">%s</span>', _x( 'Featured', 'post', 'eventi' ) );\n }\n echo '<a href=\"' . esc_url( get_permalink() ) . '\" class=\"event-details-link\">' . get_the_title() . '</a>';\n echo '&nbsp;&nbsp;&mdash;&nbsp;&nbsp;' . get_the_excerpt();\n\n // Date and times\n\n\n echo '&nbsp;&nbsp;&mdash;&nbsp;&nbsp;' . date_i18n( $dateformat, $startdate );\n if ( $startdate !== $enddate ) {\n echo ' - ' . date_i18n( $dateformat, $enddate );\n }\n\n ?>\n </div>\n </article>\n <?php\n }\n wp_reset_postdata();\n\n // If no content, include the \"No posts found\" template.\n else :\n ?>\n <section class=\"no-results not-found\">\n <header class=\"page-header\">\n <h1 class=\"page-title\"><?php _e( 'No events yet!', 'eventi' ); ?></h1>\n </header><!-- .page-header -->\n\n <div class=\"page-content\">\n <?php\n if ( current_user_can( 'publish_posts' ) ) :\n\n printf(\n '<p>' . wp_kses(\n /* translators: 1: link to WP admin new post page. */\n __( 'Ready to publish your first event? <a href=\"%1$s\">Get started here</a>.', 'eventi' ),\n array(\n 'a' => array(\n 'href' => array(),\n ),\n )\n ) . '</p>',\n esc_url( admin_url( 'post-new.php?post_type=eventi' ) )\n );\n else :\n ?>\n\n <p><?php _e( 'It seems we can&rsquo;t find any events.', 'eventi' ); ?></p>\n <?php\n\n endif;\n ?>\n </div><!-- .page-content -->\n </section><!-- .no-results -->\n <?php\n endif;\n ?>\n </main><!-- #main -->\n </section><!-- #primary -->\n\n<?php\nget_footer();\n</code></pre>\n"
}
] | 2019/02/17 | [
"https://wordpress.stackexchange.com/questions/329007",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107055/"
] | I am trying to build an Custom Post Type for showing information about events. The Custom Post Type has name 'Event', with the following meta fields:
* event\_startdate *(date in format YYYY-MM-DD)*
* event\_enddate *(date in format YYYY-MM-DD)*
This works fine for the single-event listing, however in the archive listing I would like to see a grouping like:
2019
----
### March
* Title of event starting in march
* Title of another event starting in march
### May
* Title of may event
### December
* Title of Christmas event
2020
----
### January
* Title of 2020 vision event
I have found some questions and answers on using wp\_get\_archives(), however this seems to group the posts by published date, rather on the actual date of the event (event.startdate). I also found some posts on sorting by metavalue, however not grouping. Thanks in advance for any advice or hint on how to accomplish this! | OK, so this problem has two parts:
1. Make WordPress to sort these posts properly.
2. Make WordPress to display them with all that grouping.
1. Sorting CPT by meta value on archive
---------------------------------------
You can use `pre_get_posts` to achieve this.
```
add_action( 'pre_get_posts', function ( $query ) {
if ( is_post_type_archive( 'event' ) && $query->is_main_query() ) {
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'ASC' );
$query->set( 'meta_key', 'event_startdate' );
}
} );
```
So now events will be sorted ascending by start\_date.
2. Displaying and grouping
--------------------------
You'll have to modify the `archive-event.php` file, so these events get in their groups.
```
<?php
$current_year = $current_month = '';
while ( have_posts() ) :
the_post();
$last_year = $current_year;
$last_month = $current_month;
$current_year = date( 'Y', strtotime( get_post_meta( get_the_ID(), 'event_startdate', true ) ) );
if ( $last_year != $current_year ) {
$last_month = '';
}
$current_month = date( 'F', strtotime( get_post_meta( get_the_ID(), 'event_startdate', true ) ) );
?>
<?php if ( $last_year != $current_year ) : ?><h2><?php echo $current_year; ?></h2><?php endif; ?>
<?php if ( $last_month != $current_month ) : ?><h3><?php echo $current_month; ?></h3><?php endif; ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endwhile; ?>
``` |
329,009 | <p>I am trying to create a basic plugin to send user details to a CRM when a user signs up on the WordPress website as a basic subscriber.</p>
<p>I have reached a sticking point, I have tried to interpret the API details as best as I can, but I am unsure, if I am formatting my body data properly as it just isn't working.</p>
<p>I can get the POST to work using Postman, however that is via json/javascript and on-site I am trying to achieve the same result using <code>wp_remote_post</code>. </p>
<p>Any pointers or observations would be appreciated.</p>
<pre><code>add_action( 'user_register', 'send_new_user', 10, 1 );
function send_new_user($user_id) {
$new_user = get_userdata($user_id);
$useremail = $new_user -> user_email;
$url = 'https://api.capsulecrm.com/api/v2/parties';
$body = array(
'firstName' => 'WhyWontYouWork',
'email' => $useremail
);
$args = array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'sslverify' => false,
'blocking' => false,
'headers' => array(
'Authorization' => 'Bearer {private token goes here!!!!}',
'Content-Type' => 'application/json',
'Accept' => 'application/json',
),
'body' => json_encode($body),
'cookies' => array()
);
$request = wp_remote_post ($url, $args);
};
</code></pre>
| [
{
"answer_id": 329010,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend only setting the arguments you absolutely need to change from defaults, to eliminate potential issues while testing. It's best to only add additional arguments as they are needed.</p>\n\n<p>All arguments can be found here:\n<a href=\"https://developer.wordpress.org/reference/classes/WP_Http/request/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/WP_Http/request/</a></p>\n\n<p>If possible also remove the required authentication at first to just test the POST before adding in security/authentication.</p>\n\n<p>You also don't need to close a function with a semicolon <code>;</code></p>\n\n<p>I recommend looking up how to setup xdebug so you can debug your code locally, if you can't do that, then I recommend using <code>error_log</code> to log to your hosting providers error log, so you can see what the response is.</p>\n\n<p>You also set <code>blocking</code> to false, do you not want a response from the server?</p>\n\n<pre><code>// If this file is called directly, abort.\nif ( ! defined( 'WPINC' ) ) {\n die;\n}\n\n//Find the details of a new user\n\nadd_action('user_register', 'send_doqaru_user', 10, 1);\n\nfunction send_doqaru_user ($user_id){\n\n $new_doqaru_user = get_userdata($user_id);\n $doqaru_user_email = $new_doqaru_user -> user_email;\n\n // get all the meta data of the newly registered user\n $new_user_data = get_user_meta($user_id);\n\n // get the first name of the user as a string\n $doqaru_user_firstname = get_user_meta( $user_id, 'first_name', true );\n $doqaru_user_lastname = get_user_meta( $user_id, 'last_name', true );\n\n\n if( ! $new_user ){\n error_log( 'Unable to get userdata!' );\n return;\n }\n\n $url = 'https://api.capsulecrm.com/api/v2/parties';\n $body = array(\n 'type' => 'person',\n 'firstName' => $doqaru_user_firstname,\n 'lastName' => $doqaru_user_lastname,\n 'emailAddresses' => array(\n 'type' => 'Work',\n 'address' => $new_user->user_email\n\n ));\n\n $args = array(\n 'method' => 'POST',\n 'timeout' => 45,\n 'sslverify' => false,\n 'headers' => array(\n 'Authorization' => 'Bearer {token goes here}',\n 'Content-Type' => 'application/json',\n ),\n 'body' => json_encode($body),\n );\n\n $request = wp_remote_post( $url, $args );\n\n if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) {\n error_log( print_r( $request, true ) );\n }\n\n $response = wp_remote_retrieve_body( $request );\n}\n</code></pre>\n"
},
{
"answer_id": 411104,
"author": "Allan",
"author_id": 210688,
"author_profile": "https://wordpress.stackexchange.com/users/210688",
"pm_score": 0,
"selected": false,
"text": "<p>Can you try this? This should be working:</p>\n<pre><code>$args = array(\n 'headers' => array(\n 'Authorization' => 'Bearer {private token goes here!!!!}',\n 'Content-Type' => 'application/json'\n ),\n 'body' => json_encode($body)\n);\n\n$request = wp_remote_post ($url, $args);\n\n</code></pre>\n"
}
] | 2019/02/17 | [
"https://wordpress.stackexchange.com/questions/329009",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161436/"
] | I am trying to create a basic plugin to send user details to a CRM when a user signs up on the WordPress website as a basic subscriber.
I have reached a sticking point, I have tried to interpret the API details as best as I can, but I am unsure, if I am formatting my body data properly as it just isn't working.
I can get the POST to work using Postman, however that is via json/javascript and on-site I am trying to achieve the same result using `wp_remote_post`.
Any pointers or observations would be appreciated.
```
add_action( 'user_register', 'send_new_user', 10, 1 );
function send_new_user($user_id) {
$new_user = get_userdata($user_id);
$useremail = $new_user -> user_email;
$url = 'https://api.capsulecrm.com/api/v2/parties';
$body = array(
'firstName' => 'WhyWontYouWork',
'email' => $useremail
);
$args = array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'sslverify' => false,
'blocking' => false,
'headers' => array(
'Authorization' => 'Bearer {private token goes here!!!!}',
'Content-Type' => 'application/json',
'Accept' => 'application/json',
),
'body' => json_encode($body),
'cookies' => array()
);
$request = wp_remote_post ($url, $args);
};
``` | I recommend only setting the arguments you absolutely need to change from defaults, to eliminate potential issues while testing. It's best to only add additional arguments as they are needed.
All arguments can be found here:
<https://developer.wordpress.org/reference/classes/WP_Http/request/>
If possible also remove the required authentication at first to just test the POST before adding in security/authentication.
You also don't need to close a function with a semicolon `;`
I recommend looking up how to setup xdebug so you can debug your code locally, if you can't do that, then I recommend using `error_log` to log to your hosting providers error log, so you can see what the response is.
You also set `blocking` to false, do you not want a response from the server?
```
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
//Find the details of a new user
add_action('user_register', 'send_doqaru_user', 10, 1);
function send_doqaru_user ($user_id){
$new_doqaru_user = get_userdata($user_id);
$doqaru_user_email = $new_doqaru_user -> user_email;
// get all the meta data of the newly registered user
$new_user_data = get_user_meta($user_id);
// get the first name of the user as a string
$doqaru_user_firstname = get_user_meta( $user_id, 'first_name', true );
$doqaru_user_lastname = get_user_meta( $user_id, 'last_name', true );
if( ! $new_user ){
error_log( 'Unable to get userdata!' );
return;
}
$url = 'https://api.capsulecrm.com/api/v2/parties';
$body = array(
'type' => 'person',
'firstName' => $doqaru_user_firstname,
'lastName' => $doqaru_user_lastname,
'emailAddresses' => array(
'type' => 'Work',
'address' => $new_user->user_email
));
$args = array(
'method' => 'POST',
'timeout' => 45,
'sslverify' => false,
'headers' => array(
'Authorization' => 'Bearer {token goes here}',
'Content-Type' => 'application/json',
),
'body' => json_encode($body),
);
$request = wp_remote_post( $url, $args );
if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) {
error_log( print_r( $request, true ) );
}
$response = wp_remote_retrieve_body( $request );
}
``` |
329,033 | <p>Every time I select a featured photo for a single post, the size is always adjusted and it's massive. I have changed the size of the photo within WordPress, outside of WordPress, added code to functions, added widgets and still cannot seem to change the picture size. I may need hands on help as I have followed most videos on this topic and cannot figure it out. Please help! I think it has to do with the child theme I am using, which is Ace Blog, a child of Adventure Blog.</p>
| [
{
"answer_id": 329010,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend only setting the arguments you absolutely need to change from defaults, to eliminate potential issues while testing. It's best to only add additional arguments as they are needed.</p>\n\n<p>All arguments can be found here:\n<a href=\"https://developer.wordpress.org/reference/classes/WP_Http/request/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/WP_Http/request/</a></p>\n\n<p>If possible also remove the required authentication at first to just test the POST before adding in security/authentication.</p>\n\n<p>You also don't need to close a function with a semicolon <code>;</code></p>\n\n<p>I recommend looking up how to setup xdebug so you can debug your code locally, if you can't do that, then I recommend using <code>error_log</code> to log to your hosting providers error log, so you can see what the response is.</p>\n\n<p>You also set <code>blocking</code> to false, do you not want a response from the server?</p>\n\n<pre><code>// If this file is called directly, abort.\nif ( ! defined( 'WPINC' ) ) {\n die;\n}\n\n//Find the details of a new user\n\nadd_action('user_register', 'send_doqaru_user', 10, 1);\n\nfunction send_doqaru_user ($user_id){\n\n $new_doqaru_user = get_userdata($user_id);\n $doqaru_user_email = $new_doqaru_user -> user_email;\n\n // get all the meta data of the newly registered user\n $new_user_data = get_user_meta($user_id);\n\n // get the first name of the user as a string\n $doqaru_user_firstname = get_user_meta( $user_id, 'first_name', true );\n $doqaru_user_lastname = get_user_meta( $user_id, 'last_name', true );\n\n\n if( ! $new_user ){\n error_log( 'Unable to get userdata!' );\n return;\n }\n\n $url = 'https://api.capsulecrm.com/api/v2/parties';\n $body = array(\n 'type' => 'person',\n 'firstName' => $doqaru_user_firstname,\n 'lastName' => $doqaru_user_lastname,\n 'emailAddresses' => array(\n 'type' => 'Work',\n 'address' => $new_user->user_email\n\n ));\n\n $args = array(\n 'method' => 'POST',\n 'timeout' => 45,\n 'sslverify' => false,\n 'headers' => array(\n 'Authorization' => 'Bearer {token goes here}',\n 'Content-Type' => 'application/json',\n ),\n 'body' => json_encode($body),\n );\n\n $request = wp_remote_post( $url, $args );\n\n if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) {\n error_log( print_r( $request, true ) );\n }\n\n $response = wp_remote_retrieve_body( $request );\n}\n</code></pre>\n"
},
{
"answer_id": 411104,
"author": "Allan",
"author_id": 210688,
"author_profile": "https://wordpress.stackexchange.com/users/210688",
"pm_score": 0,
"selected": false,
"text": "<p>Can you try this? This should be working:</p>\n<pre><code>$args = array(\n 'headers' => array(\n 'Authorization' => 'Bearer {private token goes here!!!!}',\n 'Content-Type' => 'application/json'\n ),\n 'body' => json_encode($body)\n);\n\n$request = wp_remote_post ($url, $args);\n\n</code></pre>\n"
}
] | 2019/02/18 | [
"https://wordpress.stackexchange.com/questions/329033",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161456/"
] | Every time I select a featured photo for a single post, the size is always adjusted and it's massive. I have changed the size of the photo within WordPress, outside of WordPress, added code to functions, added widgets and still cannot seem to change the picture size. I may need hands on help as I have followed most videos on this topic and cannot figure it out. Please help! I think it has to do with the child theme I am using, which is Ace Blog, a child of Adventure Blog. | I recommend only setting the arguments you absolutely need to change from defaults, to eliminate potential issues while testing. It's best to only add additional arguments as they are needed.
All arguments can be found here:
<https://developer.wordpress.org/reference/classes/WP_Http/request/>
If possible also remove the required authentication at first to just test the POST before adding in security/authentication.
You also don't need to close a function with a semicolon `;`
I recommend looking up how to setup xdebug so you can debug your code locally, if you can't do that, then I recommend using `error_log` to log to your hosting providers error log, so you can see what the response is.
You also set `blocking` to false, do you not want a response from the server?
```
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
//Find the details of a new user
add_action('user_register', 'send_doqaru_user', 10, 1);
function send_doqaru_user ($user_id){
$new_doqaru_user = get_userdata($user_id);
$doqaru_user_email = $new_doqaru_user -> user_email;
// get all the meta data of the newly registered user
$new_user_data = get_user_meta($user_id);
// get the first name of the user as a string
$doqaru_user_firstname = get_user_meta( $user_id, 'first_name', true );
$doqaru_user_lastname = get_user_meta( $user_id, 'last_name', true );
if( ! $new_user ){
error_log( 'Unable to get userdata!' );
return;
}
$url = 'https://api.capsulecrm.com/api/v2/parties';
$body = array(
'type' => 'person',
'firstName' => $doqaru_user_firstname,
'lastName' => $doqaru_user_lastname,
'emailAddresses' => array(
'type' => 'Work',
'address' => $new_user->user_email
));
$args = array(
'method' => 'POST',
'timeout' => 45,
'sslverify' => false,
'headers' => array(
'Authorization' => 'Bearer {token goes here}',
'Content-Type' => 'application/json',
),
'body' => json_encode($body),
);
$request = wp_remote_post( $url, $args );
if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) {
error_log( print_r( $request, true ) );
}
$response = wp_remote_retrieve_body( $request );
}
``` |
329,034 | <p>Display featured image file size, extension, filename, type, orientation?
How to display some information of featured image in post.</p>
<p>I need to display like this in post:</p>
<p>Detail Of Easter Desktop Wallpaper Widescreen
Posted : February 13, 2017 At 9:46 Am</p>
<p>Author : Admin</p>
<p>Category : Easter</p>
<p>Tags : Beautiful, Cool, Desktop</p>
<p>Viewed : 1334 Visitor</p>
<p>File Size : 324 KB</p>
<p>File Type : Image/Jpeg</p>
<p>Resolution : 2560x1920 Pixel</p>
<p>Download : Smartphone ° Tablet ° Desktop (Original)</p>
<p>Download Many Resolution: Click Here (To Attachment Page)</p>
<p>pls, i am newbie, make it easy for me to understand. thnks</p>
| [
{
"answer_id": 329036,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>The featured image is just an attachment, and you can retrieve its post ID via <code>get_post_thumbnail_id</code>, e.g.</p>\n\n<pre><code>$featured_image_id = get_post_thumbnail_id( $post );\n</code></pre>\n\n<p>At which point you're dealing with a standard post of type <code>attachment</code>. Other than checking that there is a featured image, no special handling is needed and it can be treated as any other attachment post.</p>\n\n<p>In fact, internally setting the featured image is just putting a post ID in a particular post meta field.</p>\n\n<pre><code>function get_post_thumbnail_id( $post = null ) {\n $post = get_post( $post );\n if ( ! $post ) {\n return '';\n }\n return get_post_meta( $post->ID, '_thumbnail_id', true );\n}\n</code></pre>\n\n<p>Though I would recommend using the function instead of going straight for the post meta.</p>\n\n<p>As for how to get the size, type, format of an <code>attachment</code> post, that's another question that you should open a new question for ( or refer to the main good answers that already exist )</p>\n"
},
{
"answer_id": 329433,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the code as you wanted <em>except this \"Download : Smartphone ° Tablet ° Desktop (Original)\"</em>. you can see in this screenshot <a href=\"http://prntscr.com/mmidnl\" rel=\"nofollow noreferrer\">http://prntscr.com/mmidnl</a></p>\n\n<blockquote>\n <p><strong><em>1. you can below code in functions.php file for visitors count.</em></strong>\n <strong><em>Reference:</em></strong> <a href=\"https://www.themexpert.com/blog/track-display-post-views-in-wordpress\" rel=\"nofollow noreferrer\">https://www.themexpert.com/blog/track-display-post-views-in-wordpress</a></p>\n</blockquote>\n\n<p><strong>function to display number of posts.</strong></p>\n\n<pre><code>function getPostViews($postID){\n $count_key = 'post_views_count';\n $count = get_post_meta($postID, $count_key, true);\n if($count==''){\n delete_post_meta($postID, $count_key);\n add_post_meta($postID, $count_key, '0');\n return \"0 Visitor\";\n }\n return $count.' Visitors';\n}\n</code></pre>\n\n<p><strong>function to count views.</strong></p>\n\n<pre><code>function setPostViews($postID) {\n $count_key = 'post_views_count';\n $count = get_post_meta($postID, $count_key, true);\n if($count==''){\n $count = 0;\n delete_post_meta($postID, $count_key);\n add_post_meta($postID, $count_key, '0');\n }else{\n $count++;\n update_post_meta($postID, $count_key, $count);\n }\n}\n</code></pre>\n\n<p><strong>Remove issues with prefetching adding extra views</strong></p>\n\n<pre><code>remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); \n</code></pre>\n\n<blockquote>\n <p><strong>2. Put this below code in single.php file.</strong></p>\n</blockquote>\n\n<p><strong><em>This part of the tracking views code will set the post views. Just place this code below within the single.php file inside the WordPress Loop.</em></strong></p>\n\n<pre><code><div class=\"data\">\n<div>Detail Of <?php the_title(); ?> Posted : <?php the_time('F j, Y'); ?> At <?php the_time('g:i a'); ?></div>\n<div>Author : <?php the_author(); ?></div>\n<div>Category : <?php the_category( ', ' ); ?></div>\n<div><?php the_tags( 'Tags: '); ?> </div>\n<div><?php setPostViews(get_the_ID()); ?>Viewed : <?php echo getPostViews(get_the_ID()); ?></div>\n<div><?php $image_data = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \"full\" ); $img_s = get_headers($image_data[0], 1); $img_size_wd = $img_s[\"Content-Length\"]/1024; $img_size_kb = number_format((float)$img_size_wd, 2, '.', ''); ?>File Size : <?php echo $img_size_kb; ?> KB</div>\n<div><?php $img_id = get_post_thumbnail_id($post->ID); $type = get_post_mime_type( $img_id ); ?>File Type : <?php echo $type; ?></div>\n<div><?php $image_data = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \"full\" ); ?> Resolution : <?php echo $image_data[1]; ?> x <?php echo $image_data[2]; ?> Pixel</div>\n<div><?php $img_id = get_post_thumbnail_id($post->ID); ?>Download Many Resolution: <?php echo '<a href=\"'. get_attachment_link($img_id) . '\">Click Here</a>'; ?></div>\n</div>\n</code></pre>\n"
}
] | 2019/02/18 | [
"https://wordpress.stackexchange.com/questions/329034",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161455/"
] | Display featured image file size, extension, filename, type, orientation?
How to display some information of featured image in post.
I need to display like this in post:
Detail Of Easter Desktop Wallpaper Widescreen
Posted : February 13, 2017 At 9:46 Am
Author : Admin
Category : Easter
Tags : Beautiful, Cool, Desktop
Viewed : 1334 Visitor
File Size : 324 KB
File Type : Image/Jpeg
Resolution : 2560x1920 Pixel
Download : Smartphone ° Tablet ° Desktop (Original)
Download Many Resolution: Click Here (To Attachment Page)
pls, i am newbie, make it easy for me to understand. thnks | The featured image is just an attachment, and you can retrieve its post ID via `get_post_thumbnail_id`, e.g.
```
$featured_image_id = get_post_thumbnail_id( $post );
```
At which point you're dealing with a standard post of type `attachment`. Other than checking that there is a featured image, no special handling is needed and it can be treated as any other attachment post.
In fact, internally setting the featured image is just putting a post ID in a particular post meta field.
```
function get_post_thumbnail_id( $post = null ) {
$post = get_post( $post );
if ( ! $post ) {
return '';
}
return get_post_meta( $post->ID, '_thumbnail_id', true );
}
```
Though I would recommend using the function instead of going straight for the post meta.
As for how to get the size, type, format of an `attachment` post, that's another question that you should open a new question for ( or refer to the main good answers that already exist ) |
329,038 | <p><strong>My goal is to be able to call a plugin function per site and of course it has different result based on the site data.</strong> </p>
<p>e.g.</p>
<p>I have a plugin called: <strong>sample-plugin.php</strong></p>
<p>Inside it has a function called:</p>
<pre><code>function sp_echo_site()
{
echo get_site_url();
}
</code></pre>
<p>I have a multisite inside has 3 sites: e.g. animals.com, fruits.com and people.com</p>
<p>And in a network level, I wanted to call the <code>sp_echo_site()</code> function.</p>
<p>I wanted to do the following loop, however of course it doesn't work,
How can I make this work?</p>
<pre><code>foreach (get_sites() as $site)
{
$site->sp_echo_site();
}
</code></pre>
<p>How can i achieve the following result?:</p>
<pre><code>animals.com
fruits.com
people.com
</code></pre>
<p>Is this possible? Or do I have to go to database? Or any other alternative methods?</p>
| [
{
"answer_id": 329046,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>You're almost there... </p>\n\n<p>If you have this in your plugin:</p>\n\n<pre><code>function sp_echo_site() {\n echo get_site_url();\n}\n</code></pre>\n\n<p>Then you call this function as this:</p>\n\n<pre><code>sp_echo_site();\n</code></pre>\n\n<p>And this line will run this function in the context of current site.</p>\n\n<p>So you'll have to do something like this:</p>\n\n<pre><code>if ( function_exists( 'get_sites' ) ) {\n foreach ( get_sites() as $site ) {\n switch_to_blog( $site->blog_id );\n\n sp_echo_site();\n\n restore_current_blog();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329048,
"author": "Svetoslav Marinov",
"author_id": 26487,
"author_profile": "https://wordpress.stackexchange.com/users/26487",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, that's an option OR you can do this\nexmaple.com/?trigger_my_func\nsub1.exmaple.com/?trigger_my_func or exmaple.com/sub1/?trigger_my_func\nby triggering a method when accessing a subsite within a network it should run in the context of that site and output site specific information.</p>\n"
},
{
"answer_id": 329118,
"author": "troxxx",
"author_id": 158747,
"author_profile": "https://wordpress.stackexchange.com/users/158747",
"pm_score": 0,
"selected": false,
"text": "<p>Mark, to achieve the following result, you have to change your foreach loop. Try this code:</p>\n\n<pre><code>foreach (get_sites() as $site) {\n echo $site->__get('siteurl');\n}\n</code></pre>\n\n<p>EDIT: <a href=\"https://developer.wordpress.org/reference/classes/WP_Site/__get/\" rel=\"nofollow noreferrer\">Wordpress reference</a></p>\n"
}
] | 2019/02/18 | [
"https://wordpress.stackexchange.com/questions/329038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161460/"
] | **My goal is to be able to call a plugin function per site and of course it has different result based on the site data.**
e.g.
I have a plugin called: **sample-plugin.php**
Inside it has a function called:
```
function sp_echo_site()
{
echo get_site_url();
}
```
I have a multisite inside has 3 sites: e.g. animals.com, fruits.com and people.com
And in a network level, I wanted to call the `sp_echo_site()` function.
I wanted to do the following loop, however of course it doesn't work,
How can I make this work?
```
foreach (get_sites() as $site)
{
$site->sp_echo_site();
}
```
How can i achieve the following result?:
```
animals.com
fruits.com
people.com
```
Is this possible? Or do I have to go to database? Or any other alternative methods? | You're almost there...
If you have this in your plugin:
```
function sp_echo_site() {
echo get_site_url();
}
```
Then you call this function as this:
```
sp_echo_site();
```
And this line will run this function in the context of current site.
So you'll have to do something like this:
```
if ( function_exists( 'get_sites' ) ) {
foreach ( get_sites() as $site ) {
switch_to_blog( $site->blog_id );
sp_echo_site();
restore_current_blog();
}
}
``` |
329,089 | <p>Quick heads up, I know nothing much about php so I might need some extra help with this.
So, I have set up a while ago a child theme for Astra in Wordpress. And while everything is working well so far, I just noticed that the customizer preview page is not working, or rather not fully loading at all.</p>
<p>I went through the whole plugins deactivation stuff, but it didn't change anything, so when I switched to my parent theme, I noticed the customizer works. Meaning that the problem is from my child theme.</p>
<p>I'll put below what I have in both the style.css and functions.php files of my child theme, please do let me know if something is wrong.</p>
<pre><code>/*
Theme Name: X Child Theme // Made by Y
Author: Y
Description:
Template: astra
*/
</code></pre>
<p>Functions.php files</p>
<pre><code><?php
function astra_child_enqueue_parent_theme_style() {
// Dynamically get version number of the parent stylesheet (lets browsers re-cache your stylesheet when you update your theme)
$theme = wp_get_theme( 'astra' );
$version = $theme->get( 'Version' );
// Load the stylesheet
wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css', array(), $version );
}
add_action( 'wp_enqueue_scripts', 'astra_child_enqueue_parent_theme_style' );
?>
</code></pre>
<p>Thoughts?</p>
<p>Edit: My bad, I actually meant to write template there. It is declared as Templare: in the style.css file. and the comment blocks are there as well. I will edit it my post to fix it. Thanks a lot anyway</p>
| [
{
"answer_id": 329046,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>You're almost there... </p>\n\n<p>If you have this in your plugin:</p>\n\n<pre><code>function sp_echo_site() {\n echo get_site_url();\n}\n</code></pre>\n\n<p>Then you call this function as this:</p>\n\n<pre><code>sp_echo_site();\n</code></pre>\n\n<p>And this line will run this function in the context of current site.</p>\n\n<p>So you'll have to do something like this:</p>\n\n<pre><code>if ( function_exists( 'get_sites' ) ) {\n foreach ( get_sites() as $site ) {\n switch_to_blog( $site->blog_id );\n\n sp_echo_site();\n\n restore_current_blog();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329048,
"author": "Svetoslav Marinov",
"author_id": 26487,
"author_profile": "https://wordpress.stackexchange.com/users/26487",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, that's an option OR you can do this\nexmaple.com/?trigger_my_func\nsub1.exmaple.com/?trigger_my_func or exmaple.com/sub1/?trigger_my_func\nby triggering a method when accessing a subsite within a network it should run in the context of that site and output site specific information.</p>\n"
},
{
"answer_id": 329118,
"author": "troxxx",
"author_id": 158747,
"author_profile": "https://wordpress.stackexchange.com/users/158747",
"pm_score": 0,
"selected": false,
"text": "<p>Mark, to achieve the following result, you have to change your foreach loop. Try this code:</p>\n\n<pre><code>foreach (get_sites() as $site) {\n echo $site->__get('siteurl');\n}\n</code></pre>\n\n<p>EDIT: <a href=\"https://developer.wordpress.org/reference/classes/WP_Site/__get/\" rel=\"nofollow noreferrer\">Wordpress reference</a></p>\n"
}
] | 2019/02/18 | [
"https://wordpress.stackexchange.com/questions/329089",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161486/"
] | Quick heads up, I know nothing much about php so I might need some extra help with this.
So, I have set up a while ago a child theme for Astra in Wordpress. And while everything is working well so far, I just noticed that the customizer preview page is not working, or rather not fully loading at all.
I went through the whole plugins deactivation stuff, but it didn't change anything, so when I switched to my parent theme, I noticed the customizer works. Meaning that the problem is from my child theme.
I'll put below what I have in both the style.css and functions.php files of my child theme, please do let me know if something is wrong.
```
/*
Theme Name: X Child Theme // Made by Y
Author: Y
Description:
Template: astra
*/
```
Functions.php files
```
<?php
function astra_child_enqueue_parent_theme_style() {
// Dynamically get version number of the parent stylesheet (lets browsers re-cache your stylesheet when you update your theme)
$theme = wp_get_theme( 'astra' );
$version = $theme->get( 'Version' );
// Load the stylesheet
wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css', array(), $version );
}
add_action( 'wp_enqueue_scripts', 'astra_child_enqueue_parent_theme_style' );
?>
```
Thoughts?
Edit: My bad, I actually meant to write template there. It is declared as Templare: in the style.css file. and the comment blocks are there as well. I will edit it my post to fix it. Thanks a lot anyway | You're almost there...
If you have this in your plugin:
```
function sp_echo_site() {
echo get_site_url();
}
```
Then you call this function as this:
```
sp_echo_site();
```
And this line will run this function in the context of current site.
So you'll have to do something like this:
```
if ( function_exists( 'get_sites' ) ) {
foreach ( get_sites() as $site ) {
switch_to_blog( $site->blog_id );
sp_echo_site();
restore_current_blog();
}
}
``` |
329,115 | <p>I'm getting this error when loading my page. I have 5.0.3 of WordPress. </p>
<blockquote>
<p>Uncaught SyntaxError: missing ) after argument list<br>
:formatted:1845</p>
</blockquote>
<p>The link redirect to this code:</p>
<pre><code><script type='text/javascript'>( 'fetch' in window ) || document.write( '<script src="https://learn.blueworkforce.com/wp-includes/js/dist/vendor/wp-polyfill-fetch.min.js' defer onload='"></scr' + 'ipt>' );( document.contains ) || document.write( '<script src="https://learn.blueworkforce.com/wp-includes/js/dist/vendor/wp-polyfill-node-contains.min.js' defer onload='"></scr' + 'ipt>' );( window.FormData && window.FormData.prototype.keys ) || document.write( '<script src="https://learn.blueworkforce.com/wp-includes/js/dist/vendor/wp-polyfill-formdata.min.js' defer onload='"></scr' + 'ipt>' );( Element.prototype.matches && Element.prototype.closest ) || document.write( '<script src="https://learn.blueworkforce.com/wp-includes/js/dist/vendor/wp-polyfill-element-closest.min.js' defer onload='"></scr' + 'ipt>' );
</code></pre>
<p></p>
| [
{
"answer_id": 329046,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>You're almost there... </p>\n\n<p>If you have this in your plugin:</p>\n\n<pre><code>function sp_echo_site() {\n echo get_site_url();\n}\n</code></pre>\n\n<p>Then you call this function as this:</p>\n\n<pre><code>sp_echo_site();\n</code></pre>\n\n<p>And this line will run this function in the context of current site.</p>\n\n<p>So you'll have to do something like this:</p>\n\n<pre><code>if ( function_exists( 'get_sites' ) ) {\n foreach ( get_sites() as $site ) {\n switch_to_blog( $site->blog_id );\n\n sp_echo_site();\n\n restore_current_blog();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329048,
"author": "Svetoslav Marinov",
"author_id": 26487,
"author_profile": "https://wordpress.stackexchange.com/users/26487",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, that's an option OR you can do this\nexmaple.com/?trigger_my_func\nsub1.exmaple.com/?trigger_my_func or exmaple.com/sub1/?trigger_my_func\nby triggering a method when accessing a subsite within a network it should run in the context of that site and output site specific information.</p>\n"
},
{
"answer_id": 329118,
"author": "troxxx",
"author_id": 158747,
"author_profile": "https://wordpress.stackexchange.com/users/158747",
"pm_score": 0,
"selected": false,
"text": "<p>Mark, to achieve the following result, you have to change your foreach loop. Try this code:</p>\n\n<pre><code>foreach (get_sites() as $site) {\n echo $site->__get('siteurl');\n}\n</code></pre>\n\n<p>EDIT: <a href=\"https://developer.wordpress.org/reference/classes/WP_Site/__get/\" rel=\"nofollow noreferrer\">Wordpress reference</a></p>\n"
}
] | 2019/02/18 | [
"https://wordpress.stackexchange.com/questions/329115",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161498/"
] | I'm getting this error when loading my page. I have 5.0.3 of WordPress.
>
> Uncaught SyntaxError: missing ) after argument list
>
> :formatted:1845
>
>
>
The link redirect to this code:
```
<script type='text/javascript'>( 'fetch' in window ) || document.write( '<script src="https://learn.blueworkforce.com/wp-includes/js/dist/vendor/wp-polyfill-fetch.min.js' defer onload='"></scr' + 'ipt>' );( document.contains ) || document.write( '<script src="https://learn.blueworkforce.com/wp-includes/js/dist/vendor/wp-polyfill-node-contains.min.js' defer onload='"></scr' + 'ipt>' );( window.FormData && window.FormData.prototype.keys ) || document.write( '<script src="https://learn.blueworkforce.com/wp-includes/js/dist/vendor/wp-polyfill-formdata.min.js' defer onload='"></scr' + 'ipt>' );( Element.prototype.matches && Element.prototype.closest ) || document.write( '<script src="https://learn.blueworkforce.com/wp-includes/js/dist/vendor/wp-polyfill-element-closest.min.js' defer onload='"></scr' + 'ipt>' );
``` | You're almost there...
If you have this in your plugin:
```
function sp_echo_site() {
echo get_site_url();
}
```
Then you call this function as this:
```
sp_echo_site();
```
And this line will run this function in the context of current site.
So you'll have to do something like this:
```
if ( function_exists( 'get_sites' ) ) {
foreach ( get_sites() as $site ) {
switch_to_blog( $site->blog_id );
sp_echo_site();
restore_current_blog();
}
}
``` |
329,122 | <p>I registered a Taxonomy for a custom post type called events. </p>
<pre><code>// Register Custom Taxonomy
function events_categories() {
$labels = array(
'name' => _x( 'events_categories', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'events_category', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Kategorien', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'parent_item' => __( 'Parent Item', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'new_item_name' => __( 'New Item Name', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
'add_or_remove_items' => __( 'Add or remove items', 'text_domain' ),
'choose_from_most_used' => __( 'Choose from the most used', 'text_domain' ),
'popular_items' => __( 'Popular Items', 'text_domain' ),
'search_items' => __( 'Search Items', 'text_domain' ),
'not_found' => __( 'Not Found', 'text_domain' ),
'no_terms' => __( 'No items', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
'query_var' => true
);
register_taxonomy( 'events_category', array( 'events' ), $args );
}
add_action( 'init', 'events_categories', 0 );
</code></pre>
<p>I want to display the taxonomies like this, but iam getting an error ( invalid taxonomy )</p>
<pre><code>$terms = get_terms( array(
'taxonomy' => 'events_category',
'hide_empty' => false
) );
echo '<pre>';
var_dump( $terms );
echo '</pre>';
</code></pre>
<p>EDIT:
This is the custom post type</p>
<pre><code>// Register Custom Post Type - Veranstaltungen
// Register Custom Post Type
function leweb_events_post_type() {
$labels = array(
'name' => _x( 'Events', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Event', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Events', 'text_domain' ),
'name_admin_bar' => __( 'Event', 'text_domain' ),
'archives' => __( 'Item Archives', 'text_domain' ),
'attributes' => __( 'Item Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'view_items' => __( 'View Items', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Event', 'text_domain' ),
'description' => __( 'Veranstaltungen von Besuchern', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'revisions', 'custom-fields' ),
'taxonomies' => array( 'events_category'),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-admin-page',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'events', $args );
}
add_action( 'init', 'leweb_events_post_type', 0 );
</code></pre>
| [
{
"answer_id": 329046,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>You're almost there... </p>\n\n<p>If you have this in your plugin:</p>\n\n<pre><code>function sp_echo_site() {\n echo get_site_url();\n}\n</code></pre>\n\n<p>Then you call this function as this:</p>\n\n<pre><code>sp_echo_site();\n</code></pre>\n\n<p>And this line will run this function in the context of current site.</p>\n\n<p>So you'll have to do something like this:</p>\n\n<pre><code>if ( function_exists( 'get_sites' ) ) {\n foreach ( get_sites() as $site ) {\n switch_to_blog( $site->blog_id );\n\n sp_echo_site();\n\n restore_current_blog();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329048,
"author": "Svetoslav Marinov",
"author_id": 26487,
"author_profile": "https://wordpress.stackexchange.com/users/26487",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, that's an option OR you can do this\nexmaple.com/?trigger_my_func\nsub1.exmaple.com/?trigger_my_func or exmaple.com/sub1/?trigger_my_func\nby triggering a method when accessing a subsite within a network it should run in the context of that site and output site specific information.</p>\n"
},
{
"answer_id": 329118,
"author": "troxxx",
"author_id": 158747,
"author_profile": "https://wordpress.stackexchange.com/users/158747",
"pm_score": 0,
"selected": false,
"text": "<p>Mark, to achieve the following result, you have to change your foreach loop. Try this code:</p>\n\n<pre><code>foreach (get_sites() as $site) {\n echo $site->__get('siteurl');\n}\n</code></pre>\n\n<p>EDIT: <a href=\"https://developer.wordpress.org/reference/classes/WP_Site/__get/\" rel=\"nofollow noreferrer\">Wordpress reference</a></p>\n"
}
] | 2019/02/18 | [
"https://wordpress.stackexchange.com/questions/329122",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154739/"
] | I registered a Taxonomy for a custom post type called events.
```
// Register Custom Taxonomy
function events_categories() {
$labels = array(
'name' => _x( 'events_categories', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'events_category', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Kategorien', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'parent_item' => __( 'Parent Item', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'new_item_name' => __( 'New Item Name', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
'add_or_remove_items' => __( 'Add or remove items', 'text_domain' ),
'choose_from_most_used' => __( 'Choose from the most used', 'text_domain' ),
'popular_items' => __( 'Popular Items', 'text_domain' ),
'search_items' => __( 'Search Items', 'text_domain' ),
'not_found' => __( 'Not Found', 'text_domain' ),
'no_terms' => __( 'No items', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
'query_var' => true
);
register_taxonomy( 'events_category', array( 'events' ), $args );
}
add_action( 'init', 'events_categories', 0 );
```
I want to display the taxonomies like this, but iam getting an error ( invalid taxonomy )
```
$terms = get_terms( array(
'taxonomy' => 'events_category',
'hide_empty' => false
) );
echo '<pre>';
var_dump( $terms );
echo '</pre>';
```
EDIT:
This is the custom post type
```
// Register Custom Post Type - Veranstaltungen
// Register Custom Post Type
function leweb_events_post_type() {
$labels = array(
'name' => _x( 'Events', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Event', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Events', 'text_domain' ),
'name_admin_bar' => __( 'Event', 'text_domain' ),
'archives' => __( 'Item Archives', 'text_domain' ),
'attributes' => __( 'Item Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'view_items' => __( 'View Items', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Event', 'text_domain' ),
'description' => __( 'Veranstaltungen von Besuchern', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'revisions', 'custom-fields' ),
'taxonomies' => array( 'events_category'),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-admin-page',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'events', $args );
}
add_action( 'init', 'leweb_events_post_type', 0 );
``` | You're almost there...
If you have this in your plugin:
```
function sp_echo_site() {
echo get_site_url();
}
```
Then you call this function as this:
```
sp_echo_site();
```
And this line will run this function in the context of current site.
So you'll have to do something like this:
```
if ( function_exists( 'get_sites' ) ) {
foreach ( get_sites() as $site ) {
switch_to_blog( $site->blog_id );
sp_echo_site();
restore_current_blog();
}
}
``` |
329,126 | <p>we try to connect our Managment Software to Wordpress / Woocommerce.</p>
<p>Our customers can edit and manage product, stock and category directly from our sofware.</p>
<p>Wordpress Database is simply so we easly reach our goal.</p>
<p>The only problem left is the "Image Management".</p>
<p>Our main problem si the wp_attachment_metadata:</p>
<pre><code>a:5:{s:5:"width";i:910;s:6:"height";i:607;s:4:"file";s:10:"t-logo.jpg";s:5:"sizes";a:15:{s:9:"thumbnail";a:4:{s:4:"file";s:18:"t-logo-300x300.jpg";s:5:"width";i:300;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:18:"t-logo-600x600.jpg";s:5:"width";i:600;s:6:"height";i:600;s:9:"mime-type";s:10:"image/jpeg";}s:12:"medium_large";a:4:{s:4:"file";s:18:"t-logo-768x512.jpg";s:5:"width";i:768;s:6:"height";i:512;s:9:"mime-type";s:10:"image/jpeg";}s:5:"large";a:4:{s:4:"file";s:18:"t-logo-910x448.jpg";s:5:"width";i:910;s:6:"height";i:448;s:9:"mime-type";s:10:"image/jpeg";}s:19:"yith_wcbr_logo_size";a:4:{s:4:"file";s:16:"t-logo-45x30.jpg";s:5:"width";i:45;s:6:"height";i:30;s:9:"mime-type";s:10:"image/jpeg";}s:24:"yith_wcbr_grid_logo_size";a:4:{s:4:"file";s:16:"t-logo-90x60.jpg";s:5:"width";i:90;s:6:"height";i:60;s:9:"mime-type";s:10:"image/jpeg";}s:17:"raworganic-medium";a:4:{s:4:"file";s:18:"t-logo-680x380.jpg";s:5:"width";i:680;s:6:"height";i:380;s:9:"mime-type";s:10:"image/jpeg";}s:15:"raworganic-blog";a:4:{s:4:"file";s:18:"t-logo-680x453.jpg";s:5:"width";i:680;s:6:"height";i:453;s:9:"mime-type";s:10:"image/jpeg";}s:21:"woocommerce_thumbnail";a:5:{s:4:"file";s:18:"t-logo-300x300.jpg";s:5:"width";i:300;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";s:9:"uncropped";b:1;}s:18:"woocommerce_single";a:4:{s:4:"file";s:18:"t-logo-600x400.jpg";s:5:"width";i:600;s:6:"height";i:400;s:9:"mime-type";s:10:"image/jpeg";}s:29:"woocommerce_gallery_thumbnail";a:4:{s:4:"file";s:18:"t-logo-250x361.jpg";s:5:"width";i:250;s:6:"height";i:361;s:9:"mime-type";s:10:"image/jpeg";}s:12:"shop_catalog";a:4:{s:4:"file";s:18:"t-logo-300x300.jpg";s:5:"width";i:300;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:11:"shop_single";a:4:{s:4:"file";s:18:"t-logo-600x400.jpg";s:5:"width";i:600;s:6:"height";i:400;s:9:"mime-type";s:10:"image/jpeg";}s:14:"shop_thumbnail";a:4:{s:4:"file";s:18:"t-logo-250x361.jpg";s:5:"width";i:250;s:6:"height";i:361;s:9:"mime-type";s:10:"image/jpeg";}s:14:"shop_magnifier";a:4:{s:4:"file";s:18:"t-logo-600x600.jpg";s:5:"width";i:600;s:6:"height";i:600;s:9:"mime-type";s:10:"image/jpeg";}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:0:"";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"0";s:8:"keywords";a:0:{}}}
</code></pre>
<p>we are unable to generate this data for the image, because we can't understand these value:</p>
<p><strong><em>a:5....s:12....s:9</em></strong></p>
<p>This meta change every images.</p>
<p>You know what this fields stand for?</p>
<p>Thanks</p>
| [
{
"answer_id": 329046,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>You're almost there... </p>\n\n<p>If you have this in your plugin:</p>\n\n<pre><code>function sp_echo_site() {\n echo get_site_url();\n}\n</code></pre>\n\n<p>Then you call this function as this:</p>\n\n<pre><code>sp_echo_site();\n</code></pre>\n\n<p>And this line will run this function in the context of current site.</p>\n\n<p>So you'll have to do something like this:</p>\n\n<pre><code>if ( function_exists( 'get_sites' ) ) {\n foreach ( get_sites() as $site ) {\n switch_to_blog( $site->blog_id );\n\n sp_echo_site();\n\n restore_current_blog();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329048,
"author": "Svetoslav Marinov",
"author_id": 26487,
"author_profile": "https://wordpress.stackexchange.com/users/26487",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, that's an option OR you can do this\nexmaple.com/?trigger_my_func\nsub1.exmaple.com/?trigger_my_func or exmaple.com/sub1/?trigger_my_func\nby triggering a method when accessing a subsite within a network it should run in the context of that site and output site specific information.</p>\n"
},
{
"answer_id": 329118,
"author": "troxxx",
"author_id": 158747,
"author_profile": "https://wordpress.stackexchange.com/users/158747",
"pm_score": 0,
"selected": false,
"text": "<p>Mark, to achieve the following result, you have to change your foreach loop. Try this code:</p>\n\n<pre><code>foreach (get_sites() as $site) {\n echo $site->__get('siteurl');\n}\n</code></pre>\n\n<p>EDIT: <a href=\"https://developer.wordpress.org/reference/classes/WP_Site/__get/\" rel=\"nofollow noreferrer\">Wordpress reference</a></p>\n"
}
] | 2019/02/18 | [
"https://wordpress.stackexchange.com/questions/329126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161504/"
] | we try to connect our Managment Software to Wordpress / Woocommerce.
Our customers can edit and manage product, stock and category directly from our sofware.
Wordpress Database is simply so we easly reach our goal.
The only problem left is the "Image Management".
Our main problem si the wp\_attachment\_metadata:
```
a:5:{s:5:"width";i:910;s:6:"height";i:607;s:4:"file";s:10:"t-logo.jpg";s:5:"sizes";a:15:{s:9:"thumbnail";a:4:{s:4:"file";s:18:"t-logo-300x300.jpg";s:5:"width";i:300;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:18:"t-logo-600x600.jpg";s:5:"width";i:600;s:6:"height";i:600;s:9:"mime-type";s:10:"image/jpeg";}s:12:"medium_large";a:4:{s:4:"file";s:18:"t-logo-768x512.jpg";s:5:"width";i:768;s:6:"height";i:512;s:9:"mime-type";s:10:"image/jpeg";}s:5:"large";a:4:{s:4:"file";s:18:"t-logo-910x448.jpg";s:5:"width";i:910;s:6:"height";i:448;s:9:"mime-type";s:10:"image/jpeg";}s:19:"yith_wcbr_logo_size";a:4:{s:4:"file";s:16:"t-logo-45x30.jpg";s:5:"width";i:45;s:6:"height";i:30;s:9:"mime-type";s:10:"image/jpeg";}s:24:"yith_wcbr_grid_logo_size";a:4:{s:4:"file";s:16:"t-logo-90x60.jpg";s:5:"width";i:90;s:6:"height";i:60;s:9:"mime-type";s:10:"image/jpeg";}s:17:"raworganic-medium";a:4:{s:4:"file";s:18:"t-logo-680x380.jpg";s:5:"width";i:680;s:6:"height";i:380;s:9:"mime-type";s:10:"image/jpeg";}s:15:"raworganic-blog";a:4:{s:4:"file";s:18:"t-logo-680x453.jpg";s:5:"width";i:680;s:6:"height";i:453;s:9:"mime-type";s:10:"image/jpeg";}s:21:"woocommerce_thumbnail";a:5:{s:4:"file";s:18:"t-logo-300x300.jpg";s:5:"width";i:300;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";s:9:"uncropped";b:1;}s:18:"woocommerce_single";a:4:{s:4:"file";s:18:"t-logo-600x400.jpg";s:5:"width";i:600;s:6:"height";i:400;s:9:"mime-type";s:10:"image/jpeg";}s:29:"woocommerce_gallery_thumbnail";a:4:{s:4:"file";s:18:"t-logo-250x361.jpg";s:5:"width";i:250;s:6:"height";i:361;s:9:"mime-type";s:10:"image/jpeg";}s:12:"shop_catalog";a:4:{s:4:"file";s:18:"t-logo-300x300.jpg";s:5:"width";i:300;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:11:"shop_single";a:4:{s:4:"file";s:18:"t-logo-600x400.jpg";s:5:"width";i:600;s:6:"height";i:400;s:9:"mime-type";s:10:"image/jpeg";}s:14:"shop_thumbnail";a:4:{s:4:"file";s:18:"t-logo-250x361.jpg";s:5:"width";i:250;s:6:"height";i:361;s:9:"mime-type";s:10:"image/jpeg";}s:14:"shop_magnifier";a:4:{s:4:"file";s:18:"t-logo-600x600.jpg";s:5:"width";i:600;s:6:"height";i:600;s:9:"mime-type";s:10:"image/jpeg";}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:0:"";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"0";s:8:"keywords";a:0:{}}}
```
we are unable to generate this data for the image, because we can't understand these value:
***a:5....s:12....s:9***
This meta change every images.
You know what this fields stand for?
Thanks | You're almost there...
If you have this in your plugin:
```
function sp_echo_site() {
echo get_site_url();
}
```
Then you call this function as this:
```
sp_echo_site();
```
And this line will run this function in the context of current site.
So you'll have to do something like this:
```
if ( function_exists( 'get_sites' ) ) {
foreach ( get_sites() as $site ) {
switch_to_blog( $site->blog_id );
sp_echo_site();
restore_current_blog();
}
}
``` |
329,130 | <p>I am attempting to load a page template into a shortcode so I can easily load the content wherever I want.</p>
<p>I have done some research and many people have said this code has worked for them but for some reason this does not seem to load my template right as I just get a blank page.</p>
<p>I know the shortcode is executing as it does not show as plain text so I'm guessing there is a problem with the way I am loading the template.</p>
<p>Any help is much appreciated .</p>
<pre><code>public function register(){
add_shortcode( 'sponsor_main_page', array($this,'my_form_shortcode') );
$RegistrationFormId = esc_attr( get_option( 'ik_form_id' ) );
}
function my_form_shortcode() {
ob_start();
get_template_part( 'template-sponsors.php' );
return ob_get_clean();
}
</code></pre>
| [
{
"answer_id": 329131,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\"><code>get_template_part</code></a> takes slug as first parameter and not filename.</p>\n\n<p>So it should be:</p>\n\n<pre><code>get_template_part( 'template-sponsors' );\n</code></pre>\n\n<p>And with more details... This function takes two parameters:</p>\n\n<p>get_template_part( string $slug, string $name = null )</p>\n\n<p>And inside of it, the name of a file is built like this:</p>\n\n<pre><code>if ( '' !== $name )\n</code></pre>\n\n<p> $templates[] = \"{$slug}-{$name}.php\";\n \n $templates[] = \"{$slug}.php\";</p>\n\n<p>So, as you can see, the <code>.php</code> part is added automatically. So your code will try to load file called <code>template-sponsors.php.php</code> and there is no such file, I guess.</p>\n"
},
{
"answer_id": 329133,
"author": "Sunny Johal",
"author_id": 161335,
"author_profile": "https://wordpress.stackexchange.com/users/161335",
"pm_score": 2,
"selected": false,
"text": "<p>It's likely to be occurring because you are adding .php to the parameter in <code>get_template_part()</code>. This is how I would write the code for your question:</p>\n\n<p><strong>Prerequisites for this example to work:</strong></p>\n\n<ul>\n<li>Create a folder in your theme directory called <code>template-parts</code>.</li>\n<li>Create a new file in this directory called <code>template-sponsors.php</code></li>\n<li>This is assuming your shortcode is <code>[sponsor_main_page]</code></li>\n</ul>\n\n<p><strong>Code to put in your functions.php:</strong></p>\n\n<pre><code>function custom_theme_load_sponsors_template() {\n ob_start();\n get_template_part( 'template-parts/template-sponsors' ); \n return ob_get_clean();\n}\nadd_shortcode( 'sponsor_main_page', 'custom_theme_load_sponsors_template' );\n</code></pre>\n"
},
{
"answer_id": 329173,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": -1,
"selected": false,
"text": "<p>I like using <code>locate_template</code>, rather than <code>get_template_part</code> . The <code>locate_template</code> will do the equivalent of a PHP <code>include()</code> or <code>include_once()</code>, which is what I think you are aiming for. </p>\n\n<pre><code>locate_template(\"mycustomfunctions.php\",true,true);\n</code></pre>\n\n<p>Put your <code>mycustomfunctions.php</code> file in the active template folder (optimally, a Child Theme). Then put the <code>locate_template()</code> command in your template, at the very top (after the comment block). Any functions in your <code>mysustomfunctions.php</code> file will then be available to your template.</p>\n\n<p>The <code>locate_template</code> function is called by <code>get_template_part</code>. But the parameters allow you to define <em>how</em> the include works. See <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/locate_template/</a> for more info.</p>\n\n<p>(<strong>Added</strong> See the accepted answer to this question: <a href=\"https://wordpress.stackexchange.com/questions/146134/get-template-part-vs-locate-template-function\">Get template part vs locate template function</a> . )</p>\n"
}
] | 2019/02/18 | [
"https://wordpress.stackexchange.com/questions/329130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161506/"
] | I am attempting to load a page template into a shortcode so I can easily load the content wherever I want.
I have done some research and many people have said this code has worked for them but for some reason this does not seem to load my template right as I just get a blank page.
I know the shortcode is executing as it does not show as plain text so I'm guessing there is a problem with the way I am loading the template.
Any help is much appreciated .
```
public function register(){
add_shortcode( 'sponsor_main_page', array($this,'my_form_shortcode') );
$RegistrationFormId = esc_attr( get_option( 'ik_form_id' ) );
}
function my_form_shortcode() {
ob_start();
get_template_part( 'template-sponsors.php' );
return ob_get_clean();
}
``` | [`get_template_part`](https://developer.wordpress.org/reference/functions/get_template_part/) takes slug as first parameter and not filename.
So it should be:
```
get_template_part( 'template-sponsors' );
```
And with more details... This function takes two parameters:
get\_template\_part( string $slug, string $name = null )
And inside of it, the name of a file is built like this:
```
if ( '' !== $name )
```
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
So, as you can see, the `.php` part is added automatically. So your code will try to load file called `template-sponsors.php.php` and there is no such file, I guess. |
329,135 | <p>I am designing a website using the <a href="https://www.thinkupthemes.com/free/renden-free/" rel="nofollow noreferrer">Renden Free theme</a>, and my problem is that some long titles, when viewed in mobile, have words broken in half. For example:</p>
<p><a href="https://i.stack.imgur.com/k3sT9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k3sT9.jpg" alt="Screenshot"></a></p>
<p>As you can see, the word "Corporal" gets broken and split in two lines.</p>
<p>Why is this? Is there any way to control where does Wordpress split the title?</p>
| [
{
"answer_id": 329172,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 3,
"selected": true,
"text": "<p>It's possible that a word-break CSS rule could fix the problem. You could apply it globally with this</p>\n\n<pre><code>body {word-break:normal !important; }\n</code></pre>\n\n<p>Or maybe this:</p>\n\n<pre><code>body {overflow-wrap: normal;}\n</code></pre>\n\n<p>But it might be better to apply that to the specific class/id used by the title. And ever further tweak it to only apply that rule to smaller screens via the media query.</p>\n\n<p>But you could add the above to 'additional CSS' in your theme customization to see if that will help.</p>\n\n<p>Asking the theme developer support area is the best place for this question, though. </p>\n"
},
{
"answer_id": 329186,
"author": "Foxtrail815",
"author_id": 114848,
"author_profile": "https://wordpress.stackexchange.com/users/114848",
"pm_score": 1,
"selected": false,
"text": "<p>on your style-responsive.css file around line #127</p>\n\n<pre><code>#intro .page-title {\n font-size: 30px\n }\n</code></pre>\n\n<p>Change that to 20px or less, 30 is too big for small screens from a design standpoint. </p>\n"
},
{
"answer_id": 329202,
"author": "Jason Is My Name",
"author_id": 159876,
"author_profile": "https://wordpress.stackexchange.com/users/159876",
"pm_score": 1,
"selected": false,
"text": "<p>Obviously \"word-break: '';\" will edit how the word responds to the end of the container. But, when responsive along with the word-break I sometimes calculate the font-size as a vw value.</p>\n\n<p>Say you have a title with the font-size of 32px; when you hit the wall of container at say 480px, you can figure out the width of the text at keep it constant. The math would be:</p>\n\n<p>Your width: 480.\nDivided by the width of the doc 100%.</p>\n\n<pre><code>480 / 100 = 4.8 (one percent of the width).\n</code></pre>\n\n<p>Then you need to work out how many of these are required to maintain the 32px size.</p>\n\n<pre><code>32 / 4.8 = 6.666666vw.\n</code></pre>\n\n<p>So you can then create a css rule like:</p>\n\n<pre><code>.title {\n font-size: 32px;\n}\n@media screen and (max-width: 479px) {\n .title {\n font-size: 6.666666vw;\n }\n}\n</code></pre>\n\n<p>This will create text that can scale with the page.</p>\n"
}
] | 2019/02/18 | [
"https://wordpress.stackexchange.com/questions/329135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25139/"
] | I am designing a website using the [Renden Free theme](https://www.thinkupthemes.com/free/renden-free/), and my problem is that some long titles, when viewed in mobile, have words broken in half. For example:
[](https://i.stack.imgur.com/k3sT9.jpg)
As you can see, the word "Corporal" gets broken and split in two lines.
Why is this? Is there any way to control where does Wordpress split the title? | It's possible that a word-break CSS rule could fix the problem. You could apply it globally with this
```
body {word-break:normal !important; }
```
Or maybe this:
```
body {overflow-wrap: normal;}
```
But it might be better to apply that to the specific class/id used by the title. And ever further tweak it to only apply that rule to smaller screens via the media query.
But you could add the above to 'additional CSS' in your theme customization to see if that will help.
Asking the theme developer support area is the best place for this question, though. |
329,366 | <p>I want to make it so that when an image is added to a post, full size is selected by default. It currently defaults to large. </p>
<p>I have tried:</p>
<pre><code>function my_set_default_image_size () {
return 'full';
}
add_filter( 'pre_option_image_default_size', 'my_set_default_image_size' );
</code></pre>
<p>and </p>
<pre><code>add_filter('pre_option_image_default_size', function() { return 'full'; });
</code></pre>
<p>but neither are working for me. </p>
<p>I'm on WordPress 5.0.3, using the block editor.</p>
| [
{
"answer_id": 329206,
"author": "Jason Is My Name",
"author_id": 159876,
"author_profile": "https://wordpress.stackexchange.com/users/159876",
"pm_score": 1,
"selected": false,
"text": "<p>It must be in the included in the code somewhere. Most search forms will have a search.php or some other variation of that name if it is a custom search (located in the root of your theme).</p>\n\n<p>**EDIT: ** off the back of our short conversation below.</p>\n\n<p>You have used WooCommerce to arrange your products. This means you will want to edit the product search form. This will be located within your /plugins/woocommerce folder the file most likely called product-searchform.php.</p>\n\n<p>You shoulnt edit the form here though as when you update woocommerce you will delete your changes.</p>\n\n<p>You will want to create a folder called woocommerce in the root of your theme. yourtheme/woocommerce. Making a copy of the searchform.php and editing it within this newly created folder.</p>\n"
},
{
"answer_id": 329211,
"author": "Jos",
"author_id": 148766,
"author_profile": "https://wordpress.stackexchange.com/users/148766",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than changing the theme templates, I would recommend simply hiding the form on the page. You can do this from the Customize page, Extra CSS tab.</p>\n\n<p>In your case, the search bar is enclosed in a <code><div class=\"custom-product-search\"></code> so all we need to do is enter:</p>\n\n<pre><code>.custom-product-search {display: none}\n</code></pre>\n\n<p>to hide the search bar. As this change is stored in the database, it will survive future upgrades of the theme as well.</p>\n\n<p>In case anyone else needs to maintain the site, be sure to include some comments for your successor.</p>\n"
}
] | 2019/02/20 | [
"https://wordpress.stackexchange.com/questions/329366",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140502/"
] | I want to make it so that when an image is added to a post, full size is selected by default. It currently defaults to large.
I have tried:
```
function my_set_default_image_size () {
return 'full';
}
add_filter( 'pre_option_image_default_size', 'my_set_default_image_size' );
```
and
```
add_filter('pre_option_image_default_size', function() { return 'full'; });
```
but neither are working for me.
I'm on WordPress 5.0.3, using the block editor. | It must be in the included in the code somewhere. Most search forms will have a search.php or some other variation of that name if it is a custom search (located in the root of your theme).
\*\*EDIT: \*\* off the back of our short conversation below.
You have used WooCommerce to arrange your products. This means you will want to edit the product search form. This will be located within your /plugins/woocommerce folder the file most likely called product-searchform.php.
You shoulnt edit the form here though as when you update woocommerce you will delete your changes.
You will want to create a folder called woocommerce in the root of your theme. yourtheme/woocommerce. Making a copy of the searchform.php and editing it within this newly created folder. |
329,382 | <p>I have a custom post type movies that I have defined in function.php</p>
<pre><code>function create_post_type() {
register_post_type( 'movies',
array(
'supports' => array('title', 'editor' , 'excerpt' , 'custom-fields'),
'labels' => array( 'taxonomies' => 'mvgen',
'name' => __( 'movies' ),
'singular_name' => __( 'movies' ),
),
'public' => true,
'has_archive' => true,
)
);
}
add_action( 'init', 'create_post_type' );
</code></pre>
<p>Now the archive page and single page are working good. But I have defined two custom taxonomies for this post type, for example "DRAMA" and "Rock."</p>
<p>I want when user click on this taxonomy they get all post related to that particular taxonomy.<br>
For that I have created page <code>taxonomy-mvgen-drama.php</code>
which is copied below:</p>
<pre><code> <?php get_header(); ?>
<section class="blog_sect">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php echo get_the_date(); ?>
<p>CATEGORY: <?php the_category(', '); ?></p>
</p>
<!-- ----------------printing taxonomy for a specifuic post------------------ -->
<?php
?>
<br>
<p><?php echo "LANGUAGES :"." ".get_the_term_list($post->ID, 'mvgen', '' , ' , ') ?></p>
</b>
<?php endwhile; ?>
<?php endif; ?>
<?php get_footer(); ?>
</section>
<?php get_footer(); ?>
</code></pre>
<p>But whenever I click on this taxonomy it doesn't take me to taxonomy-mvgen-drama instead it takes me to index page with the url <a href="http://localhost/movies/mvgen/rock/" rel="nofollow noreferrer">http://localhost/movies/mvgen/rock/</a> </p>
<p>Can you help me with this?</p>
| [
{
"answer_id": 329206,
"author": "Jason Is My Name",
"author_id": 159876,
"author_profile": "https://wordpress.stackexchange.com/users/159876",
"pm_score": 1,
"selected": false,
"text": "<p>It must be in the included in the code somewhere. Most search forms will have a search.php or some other variation of that name if it is a custom search (located in the root of your theme).</p>\n\n<p>**EDIT: ** off the back of our short conversation below.</p>\n\n<p>You have used WooCommerce to arrange your products. This means you will want to edit the product search form. This will be located within your /plugins/woocommerce folder the file most likely called product-searchform.php.</p>\n\n<p>You shoulnt edit the form here though as when you update woocommerce you will delete your changes.</p>\n\n<p>You will want to create a folder called woocommerce in the root of your theme. yourtheme/woocommerce. Making a copy of the searchform.php and editing it within this newly created folder.</p>\n"
},
{
"answer_id": 329211,
"author": "Jos",
"author_id": 148766,
"author_profile": "https://wordpress.stackexchange.com/users/148766",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than changing the theme templates, I would recommend simply hiding the form on the page. You can do this from the Customize page, Extra CSS tab.</p>\n\n<p>In your case, the search bar is enclosed in a <code><div class=\"custom-product-search\"></code> so all we need to do is enter:</p>\n\n<pre><code>.custom-product-search {display: none}\n</code></pre>\n\n<p>to hide the search bar. As this change is stored in the database, it will survive future upgrades of the theme as well.</p>\n\n<p>In case anyone else needs to maintain the site, be sure to include some comments for your successor.</p>\n"
}
] | 2019/02/20 | [
"https://wordpress.stackexchange.com/questions/329382",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161305/"
] | I have a custom post type movies that I have defined in function.php
```
function create_post_type() {
register_post_type( 'movies',
array(
'supports' => array('title', 'editor' , 'excerpt' , 'custom-fields'),
'labels' => array( 'taxonomies' => 'mvgen',
'name' => __( 'movies' ),
'singular_name' => __( 'movies' ),
),
'public' => true,
'has_archive' => true,
)
);
}
add_action( 'init', 'create_post_type' );
```
Now the archive page and single page are working good. But I have defined two custom taxonomies for this post type, for example "DRAMA" and "Rock."
I want when user click on this taxonomy they get all post related to that particular taxonomy.
For that I have created page `taxonomy-mvgen-drama.php`
which is copied below:
```
<?php get_header(); ?>
<section class="blog_sect">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php echo get_the_date(); ?>
<p>CATEGORY: <?php the_category(', '); ?></p>
</p>
<!-- ----------------printing taxonomy for a specifuic post------------------ -->
<?php
?>
<br>
<p><?php echo "LANGUAGES :"." ".get_the_term_list($post->ID, 'mvgen', '' , ' , ') ?></p>
</b>
<?php endwhile; ?>
<?php endif; ?>
<?php get_footer(); ?>
</section>
<?php get_footer(); ?>
```
But whenever I click on this taxonomy it doesn't take me to taxonomy-mvgen-drama instead it takes me to index page with the url <http://localhost/movies/mvgen/rock/>
Can you help me with this? | It must be in the included in the code somewhere. Most search forms will have a search.php or some other variation of that name if it is a custom search (located in the root of your theme).
\*\*EDIT: \*\* off the back of our short conversation below.
You have used WooCommerce to arrange your products. This means you will want to edit the product search form. This will be located within your /plugins/woocommerce folder the file most likely called product-searchform.php.
You shoulnt edit the form here though as when you update woocommerce you will delete your changes.
You will want to create a folder called woocommerce in the root of your theme. yourtheme/woocommerce. Making a copy of the searchform.php and editing it within this newly created folder. |
329,452 | <p>I have a problem with an old theme that can't be updated. My hosts (1&1) are now charging to continue using PHP 5.6 but I get the following errors when switching to PHP 7.2 and I don't know what to do. If anyone can help, it would be much appreciated. Thanks in advance.</p>
<pre><code>Warning: Declaration of mysiteDescriptionWalker::start_el(&$output, $item, $depth, $args) should be compatible with Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = Array, $id = 0) in /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php on line 45
</code></pre>
<p>Warning: Declaration of mysiteResponsiveMenuWalker::start_lvl(&$output, $depth) should be compatible with Walker_Nav_Menu::start_lvl(&$output, $depth = 0, $args = Array) in /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php on line 87</p>
<p>Warning: Declaration of mysiteResponsiveMenuWalker::end_lvl(&$output, $depth) should be compatible with Walker_Nav_Menu::end_lvl(&$output, $depth = 0, $args = Array) in /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php on line 87</p>
<p>Warning: Declaration of mysiteResponsiveMenuWalker::start_el(&$output, $item, $depth, $args) should be compatible with Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = Array, $id = 0) in /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php on line 87</p>
<p>Warning: Declaration of mysiteResponsiveMenuWalker::end_el(&$output, $item, $depth) should be compatible with Walker_Nav_Menu::end_el(&$output, $item, $depth = 0, $args = Array) in /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php on line 87</p>
| [
{
"answer_id": 329467,
"author": "itsdanprice",
"author_id": 14247,
"author_profile": "https://wordpress.stackexchange.com/users/14247",
"pm_score": 1,
"selected": false,
"text": "<p>This can be tricky to help with without some more details.</p>\n\n<p>Sounds like PHP 7 has run into some compatibility errors.</p>\n\n<p>Seems that you need to look at line 87 of /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php</p>\n\n<p>Is this the Construct Theme and are you running the latest version?</p>\n"
},
{
"answer_id": 329549,
"author": "David",
"author_id": 161805,
"author_profile": "https://wordpress.stackexchange.com/users/161805",
"pm_score": 0,
"selected": false,
"text": "<p>There are <a href=\"http://php.net/manual/en/migration70.incompatible.php\" rel=\"nofollow noreferrer\">many incompatibilities between the versions</a>. Making sure everything, including the theme, is compatible with the latest WordPress and updated to that point should also ensure it's compatible with PHP 7.x</p>\n"
},
{
"answer_id": 329608,
"author": "mightyoak",
"author_id": 161740,
"author_profile": "https://wordpress.stackexchange.com/users/161740",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for the replies everyone. The problem is the theme and there are no further updates, so I've got round it for now by stopping the errors being displayed using the following in wp config file</p>\n\n<pre><code> ini_set('log_errors','On');\n ini_set('display_errors','Off');\n ini_set('error_reporting', E_ALL );\n define('WP_DEBUG', false);\n define('WP_DEBUG_LOG', true);\n define('WP_DEBUG_DISPLAY', false); \n</code></pre>\n"
}
] | 2019/02/21 | [
"https://wordpress.stackexchange.com/questions/329452",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161740/"
] | I have a problem with an old theme that can't be updated. My hosts (1&1) are now charging to continue using PHP 5.6 but I get the following errors when switching to PHP 7.2 and I don't know what to do. If anyone can help, it would be much appreciated. Thanks in advance.
```
Warning: Declaration of mysiteDescriptionWalker::start_el(&$output, $item, $depth, $args) should be compatible with Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = Array, $id = 0) in /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php on line 45
```
Warning: Declaration of mysiteResponsiveMenuWalker::start\_lvl(&$output, $depth) should be compatible with Walker\_Nav\_Menu::start\_lvl(&$output, $depth = 0, $args = Array) in /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php on line 87
Warning: Declaration of mysiteResponsiveMenuWalker::end\_lvl(&$output, $depth) should be compatible with Walker\_Nav\_Menu::end\_lvl(&$output, $depth = 0, $args = Array) in /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php on line 87
Warning: Declaration of mysiteResponsiveMenuWalker::start\_el(&$output, $item, $depth, $args) should be compatible with Walker\_Nav\_Menu::start\_el(&$output, $item, $depth = 0, $args = Array, $id = 0) in /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php on line 87
Warning: Declaration of mysiteResponsiveMenuWalker::end\_el(&$output, $item, $depth) should be compatible with Walker\_Nav\_Menu::end\_el(&$output, $item, $depth = 0, $args = Array) in /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php on line 87 | This can be tricky to help with without some more details.
Sounds like PHP 7 has run into some compatibility errors.
Seems that you need to look at line 87 of /homepages/36/d129703868/htdocs/mightyoak/bhd-wp/wp-content/themes/construct/lib/classes/menu-walker.php
Is this the Construct Theme and are you running the latest version? |
329,457 | <p>When using Gutenberg I would like to disable all users except administrator from being able to edit a post's title even though I want to allow them to edit the post, <strong>and</strong> I would like to disable the permalink editor that pops-up just above the post title.</p>
<p>I want to do this for a custom post type where we will disable to the ability to add or delete posts and where we will pre-load all the posts for that post type when launching a site. </p>
<p><em>(The use-case is for condo units; once a condo complex is built there is rarely if ever a need to add or remove condo units, so I only want administrators to be able to add or remove them, and only administrators should be able to edit condo unit titles or their URL slugs.)</em></p>
<p>I have been able to figure out how to disable editing of the title, in a non-Gutenberg/hacky regular JavaScripty way, but have not been able to get rid of the permalink. Like a zombie, it keeps coming back. <em>(Ideally I would use a Gutenbergy way to do this and not a hacky JS way.)</em></p>
<p>See code that I have below that does disable title editing but not disable permalink editing. I would prefer to get rid of this and use Gutenbergy code instead. I only include it here so I won't get answers suggesting this approach.</p>
<pre><code>jQuery(function($){
var title;
function makeTitleReadOnly() {
var textarea = title.find("textarea");
if (textarea.length > 0) {
textarea.attr("readonly",true);
return
}
setTimeout(makeTitleReadOnly,100);
}
function hidePermalink() {
var permalink = title.find(".editor-post-permalink");
if (permalink.length > 0) {
permalink.hide();
return
}
setTimeout(hidePermalink,123);
}
function waitForPostTitle() {
title = $(".editor-post-title");
if (title.length > 0 ) {
makeTitleReadOnly();
hidePermalink();
return;
}
setTimeout(waitForPostTitle,100);
}
waitForPostTitle()
});
</code></pre>
<p>Ideally I will not have to create a separate plugin for this <em>(I want to incorporate all code into an existing plugin)</em> and so ideally I don't want to have to add an <code>npm</code>/<code>webpack</code> build process meaning no <code>JSX</code>, and ideally <code>create-guten-block</code> will not be required as part of an to this question.</p>
| [
{
"answer_id": 329697,
"author": "Jon Masterson",
"author_id": 26745,
"author_profile": "https://wordpress.stackexchange.com/users/26745",
"pm_score": 1,
"selected": false,
"text": "<p>I used this, inline, on specific pages (using get_current_screen()). I'd hoped this would enable me to hide/show the permalink panel under certain conditions. However, removeEditorPanel() removes the permalink panel globally. This isn't completely horrifying, since the css still works conditionally, and the permalink can still be edited via the editor (by clicking on the title) everywhere else. Hoping the Gutenberg documentation/options get better soon. If anyone has any suggestions, I'm all ears...</p>\n\n<pre><code>add_action( 'admin_footer', function() {\n$screen = get_current_screen();\nif ( $screen->id == 'WUTEVA' ) { ?>\n<style>\n .editor-post-permalink{display: none !important;}\n</style>\n<script type=\"text/javascript\">\n const { removeEditorPanel } = wp.data.dispatch('core/edit-post');\n removeEditorPanel( 'post-link' );\n</script>\n<?php }\n} );\n</code></pre>\n"
},
{
"answer_id": 329912,
"author": "Ray",
"author_id": 162032,
"author_profile": "https://wordpress.stackexchange.com/users/162032",
"pm_score": 0,
"selected": false,
"text": "<p>You may also prevent user access to the dashboard and allow editing of post type custom fields, excluding the post title and permalink, in the front-end using plugins like Pods, ACF and Toolset. You won't be using Gutenberg in editing, but it will future-proof your application if all you need is editing of custom fields. Only allow dashboard access to the administrator.</p>\n"
}
] | 2019/02/21 | [
"https://wordpress.stackexchange.com/questions/329457",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89/"
] | When using Gutenberg I would like to disable all users except administrator from being able to edit a post's title even though I want to allow them to edit the post, **and** I would like to disable the permalink editor that pops-up just above the post title.
I want to do this for a custom post type where we will disable to the ability to add or delete posts and where we will pre-load all the posts for that post type when launching a site.
*(The use-case is for condo units; once a condo complex is built there is rarely if ever a need to add or remove condo units, so I only want administrators to be able to add or remove them, and only administrators should be able to edit condo unit titles or their URL slugs.)*
I have been able to figure out how to disable editing of the title, in a non-Gutenberg/hacky regular JavaScripty way, but have not been able to get rid of the permalink. Like a zombie, it keeps coming back. *(Ideally I would use a Gutenbergy way to do this and not a hacky JS way.)*
See code that I have below that does disable title editing but not disable permalink editing. I would prefer to get rid of this and use Gutenbergy code instead. I only include it here so I won't get answers suggesting this approach.
```
jQuery(function($){
var title;
function makeTitleReadOnly() {
var textarea = title.find("textarea");
if (textarea.length > 0) {
textarea.attr("readonly",true);
return
}
setTimeout(makeTitleReadOnly,100);
}
function hidePermalink() {
var permalink = title.find(".editor-post-permalink");
if (permalink.length > 0) {
permalink.hide();
return
}
setTimeout(hidePermalink,123);
}
function waitForPostTitle() {
title = $(".editor-post-title");
if (title.length > 0 ) {
makeTitleReadOnly();
hidePermalink();
return;
}
setTimeout(waitForPostTitle,100);
}
waitForPostTitle()
});
```
Ideally I will not have to create a separate plugin for this *(I want to incorporate all code into an existing plugin)* and so ideally I don't want to have to add an `npm`/`webpack` build process meaning no `JSX`, and ideally `create-guten-block` will not be required as part of an to this question. | I used this, inline, on specific pages (using get\_current\_screen()). I'd hoped this would enable me to hide/show the permalink panel under certain conditions. However, removeEditorPanel() removes the permalink panel globally. This isn't completely horrifying, since the css still works conditionally, and the permalink can still be edited via the editor (by clicking on the title) everywhere else. Hoping the Gutenberg documentation/options get better soon. If anyone has any suggestions, I'm all ears...
```
add_action( 'admin_footer', function() {
$screen = get_current_screen();
if ( $screen->id == 'WUTEVA' ) { ?>
<style>
.editor-post-permalink{display: none !important;}
</style>
<script type="text/javascript">
const { removeEditorPanel } = wp.data.dispatch('core/edit-post');
removeEditorPanel( 'post-link' );
</script>
<?php }
} );
``` |
329,506 | <p>I write messages into my db table with jQuery Ajax form post like this:</p>
<p><strong>functions.php</strong></p>
<pre><code>add_action('wp_ajax_send_projectmessage', 'send_projectmessage');
function send_projectmessage() {
global $wpdb;
$wpdb->insert( //insert stuff to db table));
wp_send_json_success();
}
</code></pre>
<p><strong>JS:</strong></p>
<pre><code>$('#form-pm').on('submit',function(e) {
var mydata = {
'action': 'send_projectmessage',
'projectid': projectid,
'message': message
};
var ajaxRequest =
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
data: mydata
});
ajaxRequest.done(function(data) { console.log(data); });
ajaxRequest.fail(function(jqXHR) { alert(jqXHR); });
e.preventDefault();
});
</code></pre>
<p>Everything works fine, data gets inserted into my database table.</p>
<p>Now, this is how I display the messages:</p>
<pre><code><div id="messages">
<?php
$messages = load_projectmessages($projectid);
foreach ($messages as $message) {
//make a <table><tr><td> with $message->themessage
}
?>
</div>
<form id="form-pm>
<!-- input fields and submit here -->
</form>
</code></pre>
<p><code>load_projectmessages</code> is in the same <strong>functions.php</strong>:</p>
<pre><code>function load_projectmessages($projectid) {
global $wpdb;
$sql_displaymessages = $wpdb->prepare("sql stuff", $projectid );
$projectmessages = $wpdb->get_results($sql_displaymessages);
return $projectmessages;
wp_die();
}
</code></pre>
<p>My question is, <strong>where/when</strong> do I call <code>load_projectmessages</code>? Should I modify my whole JS ajax code to also do the displaying of new data?</p>
| [
{
"answer_id": 329508,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>wp_send_json_success</code> to send messages back to the jQuery. The function accepts <code>$data</code> parameter that can basically be anything - plain text string, html, array.</p>\n\n<p>So you could use your messages function inside your ajax insert function and have it send all the messages back to jQuery everytime. Or have the insert respond with only a (success) message related to that particular insert.</p>\n\n<p>You could also add some kind of error handling to your insert function and have it do <code>wp_send_json_error</code> if something goes south during the insert.</p>\n"
},
{
"answer_id": 329511,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p>Modify your code as follows:</p>\n\n<pre><code>add_action('wp_ajax_send_projectmessage', 'send_projectmessage');\nfunction send_projectmessage() {\n global $wpdb;\n $wpdb->insert( //insert stuff to db table));\n\n // Call your function to retrieve your data and send it to browser\n $messages = load_projectmessages($projectid);\n\n wp_send_json_success($messages); \n}\n</code></pre>\n\n<p>Display data through JS by modifying this </p>\n\n<pre><code>ajaxRequest.done(function(data) { console.log(data); });\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>ajaxRequest.done(function(data) { \n // Put markup for retrieved data here\n // for example \n\n var o = \"<table><tr><td>Project ID</td><td>Message</td></tr>\";\n\n for (i=0; i<=data.length; i++){\n o .= \"<tr><td>\"+data.projectid+\"</td><td>\"+data.message\"+</td></tr>\";\n }\n\n o .= \"</table>\";\n\n $(#messages).html(o); \n\n });\n</code></pre>\n\n<p>Also make sure that your function return an array instead of an OBJECT, so modify it as follows:</p>\n\n<pre><code>function load_projectmessages($projectid) {\n global $wpdb;\n $sql_displaymessages = $wpdb->prepare(\"sql stuff\", $projectid );\n\n // Add ARRAY_A to get result in an associative array\n $projectmessages = $wpdb->get_results($sql_displaymessages, ARRAY_A);\n return $projectmessages;\n\n // Not needed\n // wp_die();\n}\n</code></pre>\n\n<p>I hope this will help.</p>\n"
}
] | 2019/02/21 | [
"https://wordpress.stackexchange.com/questions/329506",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64243/"
] | I write messages into my db table with jQuery Ajax form post like this:
**functions.php**
```
add_action('wp_ajax_send_projectmessage', 'send_projectmessage');
function send_projectmessage() {
global $wpdb;
$wpdb->insert( //insert stuff to db table));
wp_send_json_success();
}
```
**JS:**
```
$('#form-pm').on('submit',function(e) {
var mydata = {
'action': 'send_projectmessage',
'projectid': projectid,
'message': message
};
var ajaxRequest =
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
data: mydata
});
ajaxRequest.done(function(data) { console.log(data); });
ajaxRequest.fail(function(jqXHR) { alert(jqXHR); });
e.preventDefault();
});
```
Everything works fine, data gets inserted into my database table.
Now, this is how I display the messages:
```
<div id="messages">
<?php
$messages = load_projectmessages($projectid);
foreach ($messages as $message) {
//make a <table><tr><td> with $message->themessage
}
?>
</div>
<form id="form-pm>
<!-- input fields and submit here -->
</form>
```
`load_projectmessages` is in the same **functions.php**:
```
function load_projectmessages($projectid) {
global $wpdb;
$sql_displaymessages = $wpdb->prepare("sql stuff", $projectid );
$projectmessages = $wpdb->get_results($sql_displaymessages);
return $projectmessages;
wp_die();
}
```
My question is, **where/when** do I call `load_projectmessages`? Should I modify my whole JS ajax code to also do the displaying of new data? | Modify your code as follows:
```
add_action('wp_ajax_send_projectmessage', 'send_projectmessage');
function send_projectmessage() {
global $wpdb;
$wpdb->insert( //insert stuff to db table));
// Call your function to retrieve your data and send it to browser
$messages = load_projectmessages($projectid);
wp_send_json_success($messages);
}
```
Display data through JS by modifying this
```
ajaxRequest.done(function(data) { console.log(data); });
```
to this
```
ajaxRequest.done(function(data) {
// Put markup for retrieved data here
// for example
var o = "<table><tr><td>Project ID</td><td>Message</td></tr>";
for (i=0; i<=data.length; i++){
o .= "<tr><td>"+data.projectid+"</td><td>"+data.message"+</td></tr>";
}
o .= "</table>";
$(#messages).html(o);
});
```
Also make sure that your function return an array instead of an OBJECT, so modify it as follows:
```
function load_projectmessages($projectid) {
global $wpdb;
$sql_displaymessages = $wpdb->prepare("sql stuff", $projectid );
// Add ARRAY_A to get result in an associative array
$projectmessages = $wpdb->get_results($sql_displaymessages, ARRAY_A);
return $projectmessages;
// Not needed
// wp_die();
}
```
I hope this will help. |
329,510 | <p>I am using the following code:</p>
<pre><code>function seconddb() {
global $seconddb;
$seconddb = new wpdb('username','password','g3boat5_G3_Genba','localhost');
}
add_action('init','seconddb');
// add the shortcode [pontoon-table], tell WP which function to call
add_shortcode( 'pontoon-table', 'pontoon_table_shortcode' );
// add the shortcode [pontoon-table], tell WP which function to call
add_shortcode( 'pontoon-table', 'pontoon_table_shortcode' );
// this function generates the shortcode output
function pontoon_table_shortcode( $args ) {
global $seconddb;
// Shortcodes RETURN content, so store in a variable to return
$content = '<table>';
$content .= '</tr><th>Week Beginning</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th><th>Weekly Total</th><th>Previous Week Totals</th></tr>';
$results = $seconddb->get_results( ' SELECT * FROM seconddb_PontoonBoats_LineOne_2Log' );
foreach ( $results AS $row ) {
$content = '<tr>';
// Modify these to match the database structure
$content .= '<td>' . $row->{'Week Beginning'} . '</td>';
$content .= '<td>' . $row->Monday . '</td>';
$content .= '<td>' . $row->Tuesday . '</td>';
$content .= '<td>' . $row->Wednesday . '</td>';
$content .= '<td>' . $row->Thursday . '</td>';
$content .= '<td>' . $row->Friday . '</td>';
$content .= '<td>' . $row->Saturday . '</td>';
$content .= '<td>' . $row->Sunday . '</td>';
$content .= '<td>' . $row->{'Weekly Total'} . '</td>';
$content .= '<td>' . $row->{'Previous Week Totals'} . '</td>';
$content .= '</tr>';
}
$content .= '</table>';
// return the table
return $content;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/wEdNR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wEdNR.png" alt="enter image description here"></a></p>
<p>So that is the correct data being pulled from the database but as you can see it is not being displayed in the table as coded. What is my next step to try and get this to render in a nicely constructed table?</p>
<p>Furthermore...if someone knows, can you explain how I can put a place on this page to to select a date and then the data pulled from the database be from that date? </p>
<p>I am trying to do everything in shortcode. </p>
| [
{
"answer_id": 329512,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>It's not displayed as table, because you don't return correct HTML code. Let's take a look at your code (I've put comments at end of incorrect lines):</p>\n\n<pre><code>$content = '<table>';\n$content .= '</tr><th>Week Beginning</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th><th>Weekly Total</th><th>Previous Week Totals</th></tr>'; // <- here you open TR with </tr>, so it's already incorrect\n$results = $seconddb->get_results( ' SELECT * FROM seconddb_PontoonBoats_LineOne_2Log' );\nforeach ( $results AS $row ) {\n $content = '<tr>'; // <- here you overwrite previous value of $content with string '<tr>'\n // Modify these to match the database structure\n $content .= '<td>' . $row->{'Week Beginning'} . '</td>';\n $content .= '<td>' . $row->Monday . '</td>';\n $content .= '<td>' . $row->Tuesday . '</td>';\n $content .= '<td>' . $row->Wednesday . '</td>';\n $content .= '<td>' . $row->Thursday . '</td>';\n $content .= '<td>' . $row->Friday . '</td>';\n $content .= '<td>' . $row->Saturday . '</td>';\n $content .= '<td>' . $row->Sunday . '</td>';\n $content .= '<td>' . $row->{'Weekly Total'} . '</td>';\n $content .= '<td>' . $row->{'Previous Week Totals'} . '</td>';\n $content .= '</tr>';\n}\n$content .= '</table>';\n</code></pre>\n\n<p>So your function returns something like this, if there are no rows (it's incorrect HTML):</p>\n\n<pre><code><table>\n </tr><th>Week Beginning</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th><th>Weekly Total</th><th>Previous Week Totals</th></tr>\n</table>\n</code></pre>\n\n<p>And something like this, if there are any rows found:</p>\n\n<pre><code><tr>\n <td><VALUE FOR: $row->{'Week Beginning'}></td>\n <td><VALUE FOR: $row->Monday></td>\n <td><VALUE FOR: $row->Tuesday></td>\n <td><VALUE FOR: $row->Wednesday></td>\n <td><VALUE FOR: $row->Thursday></td>\n <td><VALUE FOR: $row->Friday></td>\n <td><VALUE FOR: $row->Saturday></td>\n <td><VALUE FOR: $row->Sunday></td>\n <td><VALUE FOR: $row->{'Weekly Total'}></td>\n <td><VALUE FOR: $row->{'Previous Week Totals'}></td>\n </tr>\n</table>\n</code></pre>\n\n<p>And here's the fixed version of that function:</p>\n\n<pre><code>function pontoon_table_shortcode( $args ) {\n\n global $seconddb;\n // Shortcodes RETURN content, so store in a variable to return\n $content = '<table>';\n $content .= '<tr><th>Week Beginning</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th><th>Weekly Total</th><th>Previous Week Totals</th></tr>';\n $results = $seconddb->get_results( ' SELECT * FROM seconddb_PontoonBoats_LineOne_2Log' );\n foreach ( $results AS $row ) {\n $content .= '<tr>';\n // Modify these to match the database structure\n $content .= '<td>' . $row->{'Week Beginning'} . '</td>';\n $content .= '<td>' . $row->Monday . '</td>';\n $content .= '<td>' . $row->Tuesday . '</td>';\n $content .= '<td>' . $row->Wednesday . '</td>';\n $content .= '<td>' . $row->Thursday . '</td>';\n $content .= '<td>' . $row->Friday . '</td>';\n $content .= '<td>' . $row->Saturday . '</td>';\n $content .= '<td>' . $row->Sunday . '</td>';\n $content .= '<td>' . $row->{'Weekly Total'} . '</td>';\n $content .= '<td>' . $row->{'Previous Week Totals'} . '</td>';\n $content .= '</tr>';\n }\n $content .= '</table>';\n\n // return the table\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 329513,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 1,
"selected": false,
"text": "<p>There are some mistakes in your code, replace this part</p>\n\n<pre><code> $content .= '</tr><th>Week Beginning</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th><th>Weekly Total</th><th>Previous Week Totals</th></tr>';\n</code></pre>\n\n<p>with this</p>\n\n<pre><code> $content .= '<tr><th>Week Beginning</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th><th>Weekly Total</th><th>Previous Week Totals</th></tr>';\n</code></pre>\n\n<p>and this</p>\n\n<pre><code>foreach ( $results AS $row ) {\n $content = '<tr>';\n....\n....\n}\n</code></pre>\n\n<p>with this</p>\n\n<pre><code>foreach ( $results AS $row ) {\n $content .= '<tr>';\n....\n....\n}\n</code></pre>\n\n<p>and see the result. </p>\n\n<p>To make it a nice looking table, add some style through CSS.</p>\n\n<p>I hope this will help.</p>\n\n<p>UPDATE:\n@Krzysiek Dróżdż answer explains in detail what is wrong with your code.</p>\n"
}
] | 2019/02/21 | [
"https://wordpress.stackexchange.com/questions/329510",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161689/"
] | I am using the following code:
```
function seconddb() {
global $seconddb;
$seconddb = new wpdb('username','password','g3boat5_G3_Genba','localhost');
}
add_action('init','seconddb');
// add the shortcode [pontoon-table], tell WP which function to call
add_shortcode( 'pontoon-table', 'pontoon_table_shortcode' );
// add the shortcode [pontoon-table], tell WP which function to call
add_shortcode( 'pontoon-table', 'pontoon_table_shortcode' );
// this function generates the shortcode output
function pontoon_table_shortcode( $args ) {
global $seconddb;
// Shortcodes RETURN content, so store in a variable to return
$content = '<table>';
$content .= '</tr><th>Week Beginning</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th><th>Weekly Total</th><th>Previous Week Totals</th></tr>';
$results = $seconddb->get_results( ' SELECT * FROM seconddb_PontoonBoats_LineOne_2Log' );
foreach ( $results AS $row ) {
$content = '<tr>';
// Modify these to match the database structure
$content .= '<td>' . $row->{'Week Beginning'} . '</td>';
$content .= '<td>' . $row->Monday . '</td>';
$content .= '<td>' . $row->Tuesday . '</td>';
$content .= '<td>' . $row->Wednesday . '</td>';
$content .= '<td>' . $row->Thursday . '</td>';
$content .= '<td>' . $row->Friday . '</td>';
$content .= '<td>' . $row->Saturday . '</td>';
$content .= '<td>' . $row->Sunday . '</td>';
$content .= '<td>' . $row->{'Weekly Total'} . '</td>';
$content .= '<td>' . $row->{'Previous Week Totals'} . '</td>';
$content .= '</tr>';
}
$content .= '</table>';
// return the table
return $content;
}
```
[](https://i.stack.imgur.com/wEdNR.png)
So that is the correct data being pulled from the database but as you can see it is not being displayed in the table as coded. What is my next step to try and get this to render in a nicely constructed table?
Furthermore...if someone knows, can you explain how I can put a place on this page to to select a date and then the data pulled from the database be from that date?
I am trying to do everything in shortcode. | It's not displayed as table, because you don't return correct HTML code. Let's take a look at your code (I've put comments at end of incorrect lines):
```
$content = '<table>';
$content .= '</tr><th>Week Beginning</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th><th>Weekly Total</th><th>Previous Week Totals</th></tr>'; // <- here you open TR with </tr>, so it's already incorrect
$results = $seconddb->get_results( ' SELECT * FROM seconddb_PontoonBoats_LineOne_2Log' );
foreach ( $results AS $row ) {
$content = '<tr>'; // <- here you overwrite previous value of $content with string '<tr>'
// Modify these to match the database structure
$content .= '<td>' . $row->{'Week Beginning'} . '</td>';
$content .= '<td>' . $row->Monday . '</td>';
$content .= '<td>' . $row->Tuesday . '</td>';
$content .= '<td>' . $row->Wednesday . '</td>';
$content .= '<td>' . $row->Thursday . '</td>';
$content .= '<td>' . $row->Friday . '</td>';
$content .= '<td>' . $row->Saturday . '</td>';
$content .= '<td>' . $row->Sunday . '</td>';
$content .= '<td>' . $row->{'Weekly Total'} . '</td>';
$content .= '<td>' . $row->{'Previous Week Totals'} . '</td>';
$content .= '</tr>';
}
$content .= '</table>';
```
So your function returns something like this, if there are no rows (it's incorrect HTML):
```
<table>
</tr><th>Week Beginning</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th><th>Weekly Total</th><th>Previous Week Totals</th></tr>
</table>
```
And something like this, if there are any rows found:
```
<tr>
<td><VALUE FOR: $row->{'Week Beginning'}></td>
<td><VALUE FOR: $row->Monday></td>
<td><VALUE FOR: $row->Tuesday></td>
<td><VALUE FOR: $row->Wednesday></td>
<td><VALUE FOR: $row->Thursday></td>
<td><VALUE FOR: $row->Friday></td>
<td><VALUE FOR: $row->Saturday></td>
<td><VALUE FOR: $row->Sunday></td>
<td><VALUE FOR: $row->{'Weekly Total'}></td>
<td><VALUE FOR: $row->{'Previous Week Totals'}></td>
</tr>
</table>
```
And here's the fixed version of that function:
```
function pontoon_table_shortcode( $args ) {
global $seconddb;
// Shortcodes RETURN content, so store in a variable to return
$content = '<table>';
$content .= '<tr><th>Week Beginning</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th><th>Weekly Total</th><th>Previous Week Totals</th></tr>';
$results = $seconddb->get_results( ' SELECT * FROM seconddb_PontoonBoats_LineOne_2Log' );
foreach ( $results AS $row ) {
$content .= '<tr>';
// Modify these to match the database structure
$content .= '<td>' . $row->{'Week Beginning'} . '</td>';
$content .= '<td>' . $row->Monday . '</td>';
$content .= '<td>' . $row->Tuesday . '</td>';
$content .= '<td>' . $row->Wednesday . '</td>';
$content .= '<td>' . $row->Thursday . '</td>';
$content .= '<td>' . $row->Friday . '</td>';
$content .= '<td>' . $row->Saturday . '</td>';
$content .= '<td>' . $row->Sunday . '</td>';
$content .= '<td>' . $row->{'Weekly Total'} . '</td>';
$content .= '<td>' . $row->{'Previous Week Totals'} . '</td>';
$content .= '</tr>';
}
$content .= '</table>';
// return the table
return $content;
}
``` |
329,534 | <p>So I have two code snippets, trying to get the child pages of the current page. The current page is "Sample", and the following code lives in page-sample.php.</p>
<p>The first snippet uses get_posts()</p>
<pre><code>$args = array(
'post_parent' => $post->ID,
'post_type' => 'page',
'post_status' => 'any'
);
$children = get_posts( $args );
// $children = get_children( $args ); //this also works,btw
foreach($children as $child){
setup_postdata( $child );
echo "<h1>" . $child->post_title . "</h1>";
}
</code></pre>
<p>This correctly displays the child posts.</p>
<p>The second snippet uses a new WP_Query object</p>
<pre><code>$args = array(
'post_parent' => $post->ID,
'post_type' => 'page',
// 'numberposts' => -1,
'post_status' => 'any'
);
$child_pages_query= new WP_Query(args);
// echo $child_pages_query->post_count; // wrong answer already!
if ($child_pages_query->have_posts()){
while($child_pages_query->have_posts()){
$child_pages_query->the_post();
echo "<h1> " . $post->post_title . " </h1>";
}
}
</code></pre>
<p>This <strong>incorrectly</strong> displays <strong>all posts</strong> . No pages, just posts. </p>
<p>I really can't figure out what I'm doing wrong</p>
<ol>
<li>No plugins are installed</li>
<li>I commented out all parent theme code, including header,footer, till it was a bare html page, even though I couldn't see anything in header.php or footer.php that could be affecting this.</li>
</ol>
<p>Now the funny part is changing the WP_Query args doesn't seem to be making any difference. Always, all posts. WP_Query works on other pages.</p>
<p>Any help would be appreciated. Much thanks in advance!</p>
| [
{
"answer_id": 329538,
"author": "hamdirizal",
"author_id": 133145,
"author_profile": "https://wordpress.stackexchange.com/users/133145",
"pm_score": -1,
"selected": false,
"text": "<p>In your WP_Query code instead of</p>\n\n<pre><code>echo $post->post_title; \n</code></pre>\n\n<p>Try</p>\n\n<pre><code>echo $child_pages_query->post->post_title;\n</code></pre>\n"
},
{
"answer_id": 329539,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>You forgot the <code>$</code> on your <code>WP_Query</code> args array:</p>\n\n<pre><code>$child_pages_query= new WP_Query(args);\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>$child_pages_query= new WP_Query($args);\n</code></pre>\n\n<p>This should show up as a PHP warnings/notice in the error logs, and is preventable with standard debugging and development practices.</p>\n"
},
{
"answer_id": 329542,
"author": "czerspalace",
"author_id": 47406,
"author_profile": "https://wordpress.stackexchange.com/users/47406",
"pm_score": 3,
"selected": true,
"text": "<p>You are missing a <code>$</code> before args in </p>\n\n<pre><code>$child_pages_query= new WP_Query(args); \n</code></pre>\n\n<p>It should be </p>\n\n<pre><code>$child_pages_query= new WP_Query($args);\n</code></pre>\n"
}
] | 2019/02/21 | [
"https://wordpress.stackexchange.com/questions/329534",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161799/"
] | So I have two code snippets, trying to get the child pages of the current page. The current page is "Sample", and the following code lives in page-sample.php.
The first snippet uses get\_posts()
```
$args = array(
'post_parent' => $post->ID,
'post_type' => 'page',
'post_status' => 'any'
);
$children = get_posts( $args );
// $children = get_children( $args ); //this also works,btw
foreach($children as $child){
setup_postdata( $child );
echo "<h1>" . $child->post_title . "</h1>";
}
```
This correctly displays the child posts.
The second snippet uses a new WP\_Query object
```
$args = array(
'post_parent' => $post->ID,
'post_type' => 'page',
// 'numberposts' => -1,
'post_status' => 'any'
);
$child_pages_query= new WP_Query(args);
// echo $child_pages_query->post_count; // wrong answer already!
if ($child_pages_query->have_posts()){
while($child_pages_query->have_posts()){
$child_pages_query->the_post();
echo "<h1> " . $post->post_title . " </h1>";
}
}
```
This **incorrectly** displays **all posts** . No pages, just posts.
I really can't figure out what I'm doing wrong
1. No plugins are installed
2. I commented out all parent theme code, including header,footer, till it was a bare html page, even though I couldn't see anything in header.php or footer.php that could be affecting this.
Now the funny part is changing the WP\_Query args doesn't seem to be making any difference. Always, all posts. WP\_Query works on other pages.
Any help would be appreciated. Much thanks in advance! | You are missing a `$` before args in
```
$child_pages_query= new WP_Query(args);
```
It should be
```
$child_pages_query= new WP_Query($args);
``` |
329,603 | <p>I know how to do it with apache/mod_proxy, but I can't use mod_proxy on our shared host. So no .htaccess solutions.</p>
<p>Currently I have the following code in child theme's page.php</p>
<pre><code>global $post ;
if( needs_replacement( $post ) ) {
$post_name = $post->post_name ;
$from_url = create_url( $post );
$r = wp_remote_get( $from_url);
echo wp_remote_retrieve_body( $r );
exit(0);
}
require_once( get_template_directory() . '/page.php' );
?>
</code></pre>
<p>And it works. I am wondering what is the right way of doing this. $from_url is from the same server.</p>
<p>Example:</p>
<pre><code>$post = https://example.com/docs/hello-world
$from_url = https://example.com/supp/?sec=hello-world
</code></pre>
<p>Making it clear, what I want to develop is a method that can get the <em>rendered page</em> content when I pass a URL. So something like:</p>
<pre><code>function wp_get_url_content( $url ) {
....
}
</code></pre>
<p>The <code>$url</code> will always be a URL from the same server.</p>
| [
{
"answer_id": 329538,
"author": "hamdirizal",
"author_id": 133145,
"author_profile": "https://wordpress.stackexchange.com/users/133145",
"pm_score": -1,
"selected": false,
"text": "<p>In your WP_Query code instead of</p>\n\n<pre><code>echo $post->post_title; \n</code></pre>\n\n<p>Try</p>\n\n<pre><code>echo $child_pages_query->post->post_title;\n</code></pre>\n"
},
{
"answer_id": 329539,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>You forgot the <code>$</code> on your <code>WP_Query</code> args array:</p>\n\n<pre><code>$child_pages_query= new WP_Query(args);\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>$child_pages_query= new WP_Query($args);\n</code></pre>\n\n<p>This should show up as a PHP warnings/notice in the error logs, and is preventable with standard debugging and development practices.</p>\n"
},
{
"answer_id": 329542,
"author": "czerspalace",
"author_id": 47406,
"author_profile": "https://wordpress.stackexchange.com/users/47406",
"pm_score": 3,
"selected": true,
"text": "<p>You are missing a <code>$</code> before args in </p>\n\n<pre><code>$child_pages_query= new WP_Query(args); \n</code></pre>\n\n<p>It should be </p>\n\n<pre><code>$child_pages_query= new WP_Query($args);\n</code></pre>\n"
}
] | 2019/02/22 | [
"https://wordpress.stackexchange.com/questions/329603",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13215/"
] | I know how to do it with apache/mod\_proxy, but I can't use mod\_proxy on our shared host. So no .htaccess solutions.
Currently I have the following code in child theme's page.php
```
global $post ;
if( needs_replacement( $post ) ) {
$post_name = $post->post_name ;
$from_url = create_url( $post );
$r = wp_remote_get( $from_url);
echo wp_remote_retrieve_body( $r );
exit(0);
}
require_once( get_template_directory() . '/page.php' );
?>
```
And it works. I am wondering what is the right way of doing this. $from\_url is from the same server.
Example:
```
$post = https://example.com/docs/hello-world
$from_url = https://example.com/supp/?sec=hello-world
```
Making it clear, what I want to develop is a method that can get the *rendered page* content when I pass a URL. So something like:
```
function wp_get_url_content( $url ) {
....
}
```
The `$url` will always be a URL from the same server. | You are missing a `$` before args in
```
$child_pages_query= new WP_Query(args);
```
It should be
```
$child_pages_query= new WP_Query($args);
``` |
329,629 | <p>I have this:</p>
<p>PHP:</p>
<pre><code>add_action('wp_ajax_count_messages', 'count_messages');
function count_messages($projectid) {
//some code
wp_send_json_success($projectid);
}
</code></pre>
<p>JS:</p>
<pre><code>var countData = {
'action': 'count_messages',
'projectid': '100'
}
var myRequest =
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
data: countData
});
myRequest.done(function(data){ console.log(data); });
</code></pre>
<p>When I check console, I get:</p>
<pre><code>{success: true, data: ""}
</code></pre>
<p>I am not sure what is happening and why I get an empty string?</p>
| [
{
"answer_id": 329630,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 1,
"selected": true,
"text": "<p>The data you send from jQuey to PHP is in the <code>$_POST</code> variable. So you can use <code>$_POST['projectid']</code> inside your PHP function to get the data.</p>\n"
},
{
"answer_id": 329645,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered using a REST API endpoint instead?</p>\n\n<p>e.g. lets register our endpoint:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'rollor/v1', '/count_messages/', array(\n 'methods' => 'GET',\n 'callback' => 'count_messages'\n ) );\n} );\n</code></pre>\n\n<p>Then the implementation:</p>\n\n<pre><code>function count_messages($request) {\n return $request['projectid'];\n}\n</code></pre>\n\n<p>Now you can visit <code>yoursite.com/wp-json/rollor/v1/count_messages?projectid=123</code></p>\n\n<h3>Adding Validation</h3>\n\n<p>We can even extend it to add built in validation, and put the project ID in the URL:</p>\n\n<pre><code> register_rest_route( 'rollor/v1', '/count_messages/(?P<projectid>\\d+)', array(\n 'methods' => 'GET',\n 'callback' => 'count_messages',\n 'args' => array(\n 'projectid' => function($param,$request,$key) {\n return is_numeric($param);\n }\n )\n ) );\n</code></pre>\n\n<p>Now we can visit <code>yoursite.com/wp-json/rollor/v1/count_messages/123</code>. It will even tell us if we got it wrong in plain english.</p>\n\n<p>And finally:</p>\n\n<pre><code>var myRequest =\n$.ajax({\n url: 'https://example.com/wp-json/rollor/v1/count_messages/' + projectid,\n});\nmyRequest.done(function(data){ console.log(data); });\n</code></pre>\n"
}
] | 2019/02/22 | [
"https://wordpress.stackexchange.com/questions/329629",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64243/"
] | I have this:
PHP:
```
add_action('wp_ajax_count_messages', 'count_messages');
function count_messages($projectid) {
//some code
wp_send_json_success($projectid);
}
```
JS:
```
var countData = {
'action': 'count_messages',
'projectid': '100'
}
var myRequest =
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
data: countData
});
myRequest.done(function(data){ console.log(data); });
```
When I check console, I get:
```
{success: true, data: ""}
```
I am not sure what is happening and why I get an empty string? | The data you send from jQuey to PHP is in the `$_POST` variable. So you can use `$_POST['projectid']` inside your PHP function to get the data. |
329,642 | <p>I apologize if this is an easily answered question - I've been looking for a while and can't quite get my head around it.</p>
<p>I would like to modify the first label for the wp-login.php page based on the potential user. My current plan is to use url parameters to differentiate users, have a function that checks for a parameter then returns the appropriate label. </p>
<p>Currently, this function does successfully change the username field label:</p>
<pre><code>add_filter( 'gettext', array($this, 'register_text' ) );
add_filter( 'ngettext', array($this, 'register_text') );
public function register_text( $translating ) {
$translated = str_ireplace( 'Username or Email Address', 'Warranty Registration Number', $translating );
return $translated;
}
</code></pre>
<p>But I am struggling to make this conditional. My last attempt looked like this:</p>
<pre><code>public function register_text( $translating ) {
$para_log = $_GET['param']
$s14 = 's14'
$p32 = 'p32'
if ($para_log == $s14) {
$translated = str_ireplace( 'Username or Email Address', 'Dealer Number', $translating );
return $translated;
} elseif ($para_log == $p32) {
$translated = str_ireplace( 'Username or Email Address', 'Distributor Number', $translating );
return $translated;
} else {
$translated = str_ireplace( 'Username or Email Address', 'Registration Number', $translating );
return $translated;
}
endif;
}
</code></pre>
<p>But this crashes the page. I'm hoping I just suck and it's a syntax error I can't see. </p>
<p>I've also tried variations of this, but no luck here either:</p>
<pre><code> function login_function() {
add_filter( 'gettext', 'username_change', 20, 3 );
function username_change( $translated_text, $text, $domain )
{
if ($text === 'Username')
{
$translated_text = 'customLoginName';
}
return $translated_text;
}
add_action( 'login_head', 'login_function' );
</code></pre>
<p>Any help would be appreciated. Thanks.</p>
| [
{
"answer_id": 329630,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 1,
"selected": true,
"text": "<p>The data you send from jQuey to PHP is in the <code>$_POST</code> variable. So you can use <code>$_POST['projectid']</code> inside your PHP function to get the data.</p>\n"
},
{
"answer_id": 329645,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered using a REST API endpoint instead?</p>\n\n<p>e.g. lets register our endpoint:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'rollor/v1', '/count_messages/', array(\n 'methods' => 'GET',\n 'callback' => 'count_messages'\n ) );\n} );\n</code></pre>\n\n<p>Then the implementation:</p>\n\n<pre><code>function count_messages($request) {\n return $request['projectid'];\n}\n</code></pre>\n\n<p>Now you can visit <code>yoursite.com/wp-json/rollor/v1/count_messages?projectid=123</code></p>\n\n<h3>Adding Validation</h3>\n\n<p>We can even extend it to add built in validation, and put the project ID in the URL:</p>\n\n<pre><code> register_rest_route( 'rollor/v1', '/count_messages/(?P<projectid>\\d+)', array(\n 'methods' => 'GET',\n 'callback' => 'count_messages',\n 'args' => array(\n 'projectid' => function($param,$request,$key) {\n return is_numeric($param);\n }\n )\n ) );\n</code></pre>\n\n<p>Now we can visit <code>yoursite.com/wp-json/rollor/v1/count_messages/123</code>. It will even tell us if we got it wrong in plain english.</p>\n\n<p>And finally:</p>\n\n<pre><code>var myRequest =\n$.ajax({\n url: 'https://example.com/wp-json/rollor/v1/count_messages/' + projectid,\n});\nmyRequest.done(function(data){ console.log(data); });\n</code></pre>\n"
}
] | 2019/02/22 | [
"https://wordpress.stackexchange.com/questions/329642",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161855/"
] | I apologize if this is an easily answered question - I've been looking for a while and can't quite get my head around it.
I would like to modify the first label for the wp-login.php page based on the potential user. My current plan is to use url parameters to differentiate users, have a function that checks for a parameter then returns the appropriate label.
Currently, this function does successfully change the username field label:
```
add_filter( 'gettext', array($this, 'register_text' ) );
add_filter( 'ngettext', array($this, 'register_text') );
public function register_text( $translating ) {
$translated = str_ireplace( 'Username or Email Address', 'Warranty Registration Number', $translating );
return $translated;
}
```
But I am struggling to make this conditional. My last attempt looked like this:
```
public function register_text( $translating ) {
$para_log = $_GET['param']
$s14 = 's14'
$p32 = 'p32'
if ($para_log == $s14) {
$translated = str_ireplace( 'Username or Email Address', 'Dealer Number', $translating );
return $translated;
} elseif ($para_log == $p32) {
$translated = str_ireplace( 'Username or Email Address', 'Distributor Number', $translating );
return $translated;
} else {
$translated = str_ireplace( 'Username or Email Address', 'Registration Number', $translating );
return $translated;
}
endif;
}
```
But this crashes the page. I'm hoping I just suck and it's a syntax error I can't see.
I've also tried variations of this, but no luck here either:
```
function login_function() {
add_filter( 'gettext', 'username_change', 20, 3 );
function username_change( $translated_text, $text, $domain )
{
if ($text === 'Username')
{
$translated_text = 'customLoginName';
}
return $translated_text;
}
add_action( 'login_head', 'login_function' );
```
Any help would be appreciated. Thanks. | The data you send from jQuey to PHP is in the `$_POST` variable. So you can use `$_POST['projectid']` inside your PHP function to get the data. |
329,648 | <p>I want to have 3 Pages with 30 posts each: <strong>Total 90 posts.</strong>
<strong>/page/4/ shouldn't exist</strong>. Should either 404 or redirect to home.</p>
<p>Only /, /page/2/ and /page/3/ should exist.
With 30 posts each, like so:</p>
<ul>
<li>/ <em>posts -> 01-30</em></li>
<li>/page/2/ <em>posts -> 31-60</em></li>
<li>/page/3/ <em>posts -> 61-90</em></li>
</ul>
<p>I've tried numerous suggestions, none limit the query for me. Just the number of posts per page. This looked promising but has no effect (/page/999/ works)</p>
<pre><code>function wpcodex_filter_main_search_post_limits( $limit, $query ) {
if ($query->is_front_page()) {
//this:
return '90';
//or even this:
return 'LIMIT 90';
}
return $limit;
}
add_filter( 'post_limits', 'wpcodex_filter_main_search_post_limits', 10, 2 );
</code></pre>
<p>Some people as a work around suggest counting with PHP and using an if to stop showing the posts. That's a work around i want to limit the SQL query.</p>
| [
{
"answer_id": 329652,
"author": "hamdirizal",
"author_id": 133145,
"author_profile": "https://wordpress.stackexchange.com/users/133145",
"pm_score": 0,
"selected": false,
"text": "<p>Your solution doesn't work because it is limiting the current loop to 90 records. <strong>It doesn't limit the total records.</strong></p>\n\n<p>For your problem, you can just cap the <strong>paged</strong> value before WordPress does its main loop like this. </p>\n\n<pre><code>function override_paged(){\n if(get_query_var('paged')>3){\n\n //Cap the value\n set_query_var( 'paged', 3 ); \n\n //Or redirect\n //wp_safe_redirect('HOME_PAGE_URL');die();\n\n }\n}\nadd_action('pre_get_posts','override_paged');\n</code></pre>\n\n<p>This <strong>will affect</strong> all WordPress query, so please adjust to your requirements.</p>\n"
},
{
"answer_id": 329653,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p>Try using <code>paginate_links( $args )</code>. Here is code adopted from <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links#Example_With_a_Custom_Query\" rel=\"nofollow noreferrer\">codex</a>.</p>\n\n<pre><code>$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;\n\n$args = array(\n 'posts_per_page' => 30,\n 'paged' => $paged,\n);\n\n$the_query = new WP_Query( $args );\n\n// the loop etc goes here.. \n\n$big = 999999999; \n\necho paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var('paged') ),\n 'prev_next' => false,\n 'total' => 3\n) );\n</code></pre>\n\n<p>See detail here on <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links\" rel=\"nofollow noreferrer\">codex</a>.</p>\n"
}
] | 2019/02/22 | [
"https://wordpress.stackexchange.com/questions/329648",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77283/"
] | I want to have 3 Pages with 30 posts each: **Total 90 posts.**
**/page/4/ shouldn't exist**. Should either 404 or redirect to home.
Only /, /page/2/ and /page/3/ should exist.
With 30 posts each, like so:
* / *posts -> 01-30*
* /page/2/ *posts -> 31-60*
* /page/3/ *posts -> 61-90*
I've tried numerous suggestions, none limit the query for me. Just the number of posts per page. This looked promising but has no effect (/page/999/ works)
```
function wpcodex_filter_main_search_post_limits( $limit, $query ) {
if ($query->is_front_page()) {
//this:
return '90';
//or even this:
return 'LIMIT 90';
}
return $limit;
}
add_filter( 'post_limits', 'wpcodex_filter_main_search_post_limits', 10, 2 );
```
Some people as a work around suggest counting with PHP and using an if to stop showing the posts. That's a work around i want to limit the SQL query. | Try using `paginate_links( $args )`. Here is code adopted from [codex](https://codex.wordpress.org/Function_Reference/paginate_links#Example_With_a_Custom_Query).
```
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$args = array(
'posts_per_page' => 30,
'paged' => $paged,
);
$the_query = new WP_Query( $args );
// the loop etc goes here..
$big = 999999999;
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'prev_next' => false,
'total' => 3
) );
```
See detail here on [codex](https://codex.wordpress.org/Function_Reference/paginate_links). |
329,656 | <p>How can I display a short url of the post in the content arrea like</p>
<pre><code>Shortlink - https://www.example.com/abc24g4
</code></pre>
<p>instead of the standard</p>
<pre><code>Shortlink - http://example.com/?p=1234
</code></pre>
<h2><strong>WITHOUT USING ANY PLUGINS or other services like bitly</strong></h2>
| [
{
"answer_id": 329652,
"author": "hamdirizal",
"author_id": 133145,
"author_profile": "https://wordpress.stackexchange.com/users/133145",
"pm_score": 0,
"selected": false,
"text": "<p>Your solution doesn't work because it is limiting the current loop to 90 records. <strong>It doesn't limit the total records.</strong></p>\n\n<p>For your problem, you can just cap the <strong>paged</strong> value before WordPress does its main loop like this. </p>\n\n<pre><code>function override_paged(){\n if(get_query_var('paged')>3){\n\n //Cap the value\n set_query_var( 'paged', 3 ); \n\n //Or redirect\n //wp_safe_redirect('HOME_PAGE_URL');die();\n\n }\n}\nadd_action('pre_get_posts','override_paged');\n</code></pre>\n\n<p>This <strong>will affect</strong> all WordPress query, so please adjust to your requirements.</p>\n"
},
{
"answer_id": 329653,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 2,
"selected": true,
"text": "<p>Try using <code>paginate_links( $args )</code>. Here is code adopted from <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links#Example_With_a_Custom_Query\" rel=\"nofollow noreferrer\">codex</a>.</p>\n\n<pre><code>$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;\n\n$args = array(\n 'posts_per_page' => 30,\n 'paged' => $paged,\n);\n\n$the_query = new WP_Query( $args );\n\n// the loop etc goes here.. \n\n$big = 999999999; \n\necho paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var('paged') ),\n 'prev_next' => false,\n 'total' => 3\n) );\n</code></pre>\n\n<p>See detail here on <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links\" rel=\"nofollow noreferrer\">codex</a>.</p>\n"
}
] | 2019/02/23 | [
"https://wordpress.stackexchange.com/questions/329656",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | How can I display a short url of the post in the content arrea like
```
Shortlink - https://www.example.com/abc24g4
```
instead of the standard
```
Shortlink - http://example.com/?p=1234
```
**WITHOUT USING ANY PLUGINS or other services like bitly**
---------------------------------------------------------- | Try using `paginate_links( $args )`. Here is code adopted from [codex](https://codex.wordpress.org/Function_Reference/paginate_links#Example_With_a_Custom_Query).
```
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$args = array(
'posts_per_page' => 30,
'paged' => $paged,
);
$the_query = new WP_Query( $args );
// the loop etc goes here..
$big = 999999999;
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'prev_next' => false,
'total' => 3
) );
```
See detail here on [codex](https://codex.wordpress.org/Function_Reference/paginate_links). |
329,683 | <p>We use automatic updates on our sites due to having many sites and so manual updates not being feasible in the low hosting costs.</p>
<p>But due to Wordpress or mainly plugin updates having the possibility to break your site, and due to not knowing when Wordpress would actually do the updates which could also occur every day, I would like to programatically update Wordpress and plugins in a functions.php or plugin so I can know the exact date and time it will run, and so we know to check for problems afterwards.</p>
<p>For example, I may choose Monday mornings 3am so our first action that morning is check all sites are working well, fix any issues, and then I know the rest of the week will be problem free :) </p>
<p><strong>Does anyone know how to initiate a Wordpress and plugin update in the functions file or a plugin?</strong> </p>
<p>My idea is to disable all automatic updates generally, but then at a certain day and time to call the update function which would check if updates exist, and if they do, update them. I will add an email function to inform me what has been updated on what site so I can check that site. </p>
<p>If using automatic updates, this approach is far more controlled than if leaving Wordpress do it as and when it likes however many times every day. </p>
<p>Thanks</p>
| [
{
"answer_id": 329689,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 1,
"selected": false,
"text": "<p>There's a question and an answer regarding WP (auto) updates here, <a href=\"https://wordpress.stackexchange.com/questions/183202/how-to-what-triggers-a-wordpress-auto-update\">How To/What triggers a Wordpress auto update?</a></p>\n\n<p>The answer also has a link to a blog post on how to <a href=\"http://blog.birdhouse.org/2013/11/02/force-wordpress-auto-update/\" rel=\"nofollow noreferrer\">force WordPress auto-update</a>. </p>\n\n<p>Code snippet posted on the referenced blog,</p>\n\n<pre><code><?php\n // request-update.php\n require( dirname(__FILE__) . '/wp-load.php' );\n wp_maybe_auto_update();\n?>\n</code></pre>\n\n<p>and</p>\n\n<pre><code>php ./request-update.php\n</code></pre>\n\n<p>Perhaps you can use this and a real (not WP) cron job to update your site(s) at a certain day and time.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Then there's the <a href=\"https://developer.wordpress.org/reference/functions/do_core_upgrade/\" rel=\"nofollow noreferrer\"><code>do_core_upgrade</code></a> function.</p>\n\n<p><strong>Edit 2</strong></p>\n\n<p>Oh, and then there's <a href=\"https://developer.wordpress.org/reference/functions/wp_update_plugins/\" rel=\"nofollow noreferrer\"><code>wp_update_plugins</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_update_themes/\" rel=\"nofollow noreferrer\"><code>wp_update_themes</code></a>, too. These are defined in <a href=\"https://core.trac.wordpress.org/browser/tags/5.1/src/wp-includes/update.php\" rel=\"nofollow noreferrer\">wp-includes/update.php</a> (trac).</p>\n\n<p><strong>Edit 3</strong></p>\n\n<p>Actually, <a href=\"https://developer.wordpress.org/reference/functions/wp_ajax_update_plugin/\" rel=\"nofollow noreferrer\"><code>wp_ajax_update_plugin</code></a> might be better reference point for creating a custom plugin update process. There's also the <a href=\"https://developer.wordpress.org/reference/classes/plugin_upgrader/\" rel=\"nofollow noreferrer\"><code>Plugin_Upgrader</code></a> class. For themes there's <a href=\"https://developer.wordpress.org/reference/functions/wp_ajax_update_theme/\" rel=\"nofollow noreferrer\"><code>wp_ajax_update_theme</code></a> for reference and <a href=\"https://developer.wordpress.org/reference/classes/theme_upgrader/\" rel=\"nofollow noreferrer\"><code>Theme_Upgrader</code></a> class.</p>\n"
},
{
"answer_id": 359831,
"author": "MasuduL",
"author_id": 183637,
"author_profile": "https://wordpress.stackexchange.com/users/183637",
"pm_score": 0,
"selected": false,
"text": "<p>wp-disable-plugin-update.php smart updating knowledge growth WordPress code</p>\n\n<pre><code>/**\n * Prevent update notification for plugin\n * http://www.thecreativedev.com/disable-updates-for-specific-plugin-in-wordpress/\n * Place in theme functions.php or at bottom of wp-config.php\n */\nfunction disable_plugin_updates( $value ) {\n if ( isset($value) && is_object($value) ) {\n if ( isset( $value->response['plugin-folder/plugin.php'] ) ) {\n unset( $value->response['plugin-folder/plugin.php'] );\n }\n }\n return $value;\n}\nadd_filter( 'site_transient_update_plugins', 'disable_plugin_updates' );\n</code></pre>\n"
}
] | 2019/02/23 | [
"https://wordpress.stackexchange.com/questions/329683",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89983/"
] | We use automatic updates on our sites due to having many sites and so manual updates not being feasible in the low hosting costs.
But due to Wordpress or mainly plugin updates having the possibility to break your site, and due to not knowing when Wordpress would actually do the updates which could also occur every day, I would like to programatically update Wordpress and plugins in a functions.php or plugin so I can know the exact date and time it will run, and so we know to check for problems afterwards.
For example, I may choose Monday mornings 3am so our first action that morning is check all sites are working well, fix any issues, and then I know the rest of the week will be problem free :)
**Does anyone know how to initiate a Wordpress and plugin update in the functions file or a plugin?**
My idea is to disable all automatic updates generally, but then at a certain day and time to call the update function which would check if updates exist, and if they do, update them. I will add an email function to inform me what has been updated on what site so I can check that site.
If using automatic updates, this approach is far more controlled than if leaving Wordpress do it as and when it likes however many times every day.
Thanks | There's a question and an answer regarding WP (auto) updates here, [How To/What triggers a Wordpress auto update?](https://wordpress.stackexchange.com/questions/183202/how-to-what-triggers-a-wordpress-auto-update)
The answer also has a link to a blog post on how to [force WordPress auto-update](http://blog.birdhouse.org/2013/11/02/force-wordpress-auto-update/).
Code snippet posted on the referenced blog,
```
<?php
// request-update.php
require( dirname(__FILE__) . '/wp-load.php' );
wp_maybe_auto_update();
?>
```
and
```
php ./request-update.php
```
Perhaps you can use this and a real (not WP) cron job to update your site(s) at a certain day and time.
**Edit**
Then there's the [`do_core_upgrade`](https://developer.wordpress.org/reference/functions/do_core_upgrade/) function.
**Edit 2**
Oh, and then there's [`wp_update_plugins`](https://developer.wordpress.org/reference/functions/wp_update_plugins/) and [`wp_update_themes`](https://developer.wordpress.org/reference/functions/wp_update_themes/), too. These are defined in [wp-includes/update.php](https://core.trac.wordpress.org/browser/tags/5.1/src/wp-includes/update.php) (trac).
**Edit 3**
Actually, [`wp_ajax_update_plugin`](https://developer.wordpress.org/reference/functions/wp_ajax_update_plugin/) might be better reference point for creating a custom plugin update process. There's also the [`Plugin_Upgrader`](https://developer.wordpress.org/reference/classes/plugin_upgrader/) class. For themes there's [`wp_ajax_update_theme`](https://developer.wordpress.org/reference/functions/wp_ajax_update_theme/) for reference and [`Theme_Upgrader`](https://developer.wordpress.org/reference/classes/theme_upgrader/) class. |
329,696 | <p>I was looking for a solution to get the image url starting from the uploaded media id.</p>
<p>I'm using a custom field to specify which images to show on a post page. Then I retrieve the images ids with the REST api, and I need to create a gallery of images, based on the retrieved ids.</p>
<p>Does anybody know how to retrieve the image url, based on the image id(using an AJAX call from a .js file)?<br>
Something like the WP php version of wp-get-attachment-image.</p>
| [
{
"answer_id": 329698,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>You can use REST API to <a href=\"https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item\" rel=\"nofollow noreferrer\">retrieve media item</a>. Just send GET request to this address (change example.com to your site):</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/media/<id>\n</code></pre>\n\n<p>If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:</p>\n\n<pre><code>{\n \"id\": 546,\n \"date\": \"2019-01-23T11:22:15\",\n \"date_gmt\": \"2019-01-23T10:22:15\",\n \"guid\": {\n \"rendered\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n },\n \"modified\": \"2019-01-23T11:22:15\",\n \"modified_gmt\": \"2019-01-23T10:22:15\",\n \"slug\": \"my-icon\",\n \"status\": \"inherit\",\n \"type\": \"attachment\",\n \"link\": \"https://example.com/my-icon/\",\n \"title\": {\n \"rendered\": \"my-icon\"\n },\n \"author\": 1,\n \"comment_status\": \"open\",\n \"ping_status\": \"closed\",\n \"template\": \"\",\n \"meta\": [],\n \"description\": {\n \"rendered\": \"<p class=\\\"attachment\\\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\\\"300\\\" height=\\\"300\\\" src=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png\\\" class=\\\"attachment-medium size-medium\\\" alt=\\\"\\\" srcset=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\\\" sizes=\\\"(max-width: 300px) 100vw, 300px\\\" /></a></p>\\n\"\n },\n \"caption\": {\n \"rendered\": \"\"\n },\n \"alt_text\": \"\",\n \"media_type\": \"image\",\n \"mime_type\": \"image/png\",\n \"media_details\": {\n \"width\": 300,\n \"height\": 300,\n \"file\": \"2019/01/my-icon.png\",\n \"sizes\": {\n \"thumbnail\": {\n \"file\": \"my-icon-150x150.png\",\n \"width\": \"150\",\n \"height\": \"150\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png\"\n },\n \"portfolio-thumbnail\": {\n \"file\": \"my-icon-300x240.png\",\n \"width\": \"300\",\n \"height\": \"240\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png\"\n },\n \"full\": {\n \"file\": \"my-icon.png\",\n \"width\": 300,\n \"height\": 300,\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n }\n },\n \"image_meta\": {\n \"aperture\": \"0\",\n \"credit\": \"\",\n \"camera\": \"\",\n \"caption\": \"\",\n \"created_timestamp\": \"0\",\n \"copyright\": \"\",\n \"focal_length\": \"0\",\n \"iso\": \"0\",\n \"shutter_speed\": \"0\",\n \"title\": \"\",\n \"orientation\": \"0\"\n }\n },\n \"post\": null,\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\",\n \"_links\": {\n \"self\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media/546\"\n }\n ],\n \"collection\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media\"\n }\n ],\n \"about\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/types/attachment\"\n }\n ],\n \"author\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/users/1\"\n }\n ],\n \"replies\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/comments?post=546\"\n }\n ]\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329701,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>You can create your own AJAX action to handle this:</p>\n\n<pre><code>add_action( 'wp_ajax_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n\nfunction smyles_get_attachment_src_details() {\n\n check_ajax_referer( 'smyles_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n $user_id = get_current_user_id();\n\n if ( empty( $user_id ) ) {\n wp_send_json_error( array( 'not_logged_in' => 'User is not logged in' ) );\n return;\n }\n\n $attach_id = absint( $_POST['attachment_id'] );\n $size = array_key_exists( 'size', $_POST ) ? sanitize_text_field( $_POST['size'] ) : 'thumbnail';\n\n if( $source = wp_get_attachment_image_src( $attach_id, $size ) ){\n wp_send_json_success( $source );\n } else {\n wp_send_json_error();\n }\n}\n</code></pre>\n\n<p>If you don't care if user is logged in you can remove that code, but you should still keep the nonce handling (ALWAYS think security first!) as this prevents allowing external calls (not from your site) to your endpoints</p>\n\n<p>The return value will be JSON with - url, width, height, is_intermediate</p>\n"
}
] | 2019/02/23 | [
"https://wordpress.stackexchange.com/questions/329696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48664/"
] | I was looking for a solution to get the image url starting from the uploaded media id.
I'm using a custom field to specify which images to show on a post page. Then I retrieve the images ids with the REST api, and I need to create a gallery of images, based on the retrieved ids.
Does anybody know how to retrieve the image url, based on the image id(using an AJAX call from a .js file)?
Something like the WP php version of wp-get-attachment-image. | You can use REST API to [retrieve media item](https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item). Just send GET request to this address (change example.com to your site):
```
http://example.com/wp-json/wp/v2/media/<id>
```
If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:
```
{
"id": 546,
"date": "2019-01-23T11:22:15",
"date_gmt": "2019-01-23T10:22:15",
"guid": {
"rendered": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
},
"modified": "2019-01-23T11:22:15",
"modified_gmt": "2019-01-23T10:22:15",
"slug": "my-icon",
"status": "inherit",
"type": "attachment",
"link": "https://example.com/my-icon/",
"title": {
"rendered": "my-icon"
},
"author": 1,
"comment_status": "open",
"ping_status": "closed",
"template": "",
"meta": [],
"description": {
"rendered": "<p class=\"attachment\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\"300\" height=\"300\" src=\"https://example.com/wp-content/uploads/2019/01/my-icon.png\" class=\"attachment-medium size-medium\" alt=\"\" srcset=\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\" sizes=\"(max-width: 300px) 100vw, 300px\" /></a></p>\n"
},
"caption": {
"rendered": ""
},
"alt_text": "",
"media_type": "image",
"mime_type": "image/png",
"media_details": {
"width": 300,
"height": 300,
"file": "2019/01/my-icon.png",
"sizes": {
"thumbnail": {
"file": "my-icon-150x150.png",
"width": "150",
"height": "150",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png"
},
"portfolio-thumbnail": {
"file": "my-icon-300x240.png",
"width": "300",
"height": "240",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png"
},
"full": {
"file": "my-icon.png",
"width": 300,
"height": 300,
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
}
},
"image_meta": {
"aperture": "0",
"credit": "",
"camera": "",
"caption": "",
"created_timestamp": "0",
"copyright": "",
"focal_length": "0",
"iso": "0",
"shutter_speed": "0",
"title": "",
"orientation": "0"
}
},
"post": null,
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png",
"_links": {
"self": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media/546"
}
],
"collection": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media"
}
],
"about": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/types/attachment"
}
],
"author": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/users/1"
}
],
"replies": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/comments?post=546"
}
]
}
}
``` |
329,702 | <p>How can I be displayed in an article written by a writer in a text format only to the same author.</p>
| [
{
"answer_id": 329698,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>You can use REST API to <a href=\"https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item\" rel=\"nofollow noreferrer\">retrieve media item</a>. Just send GET request to this address (change example.com to your site):</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/media/<id>\n</code></pre>\n\n<p>If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:</p>\n\n<pre><code>{\n \"id\": 546,\n \"date\": \"2019-01-23T11:22:15\",\n \"date_gmt\": \"2019-01-23T10:22:15\",\n \"guid\": {\n \"rendered\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n },\n \"modified\": \"2019-01-23T11:22:15\",\n \"modified_gmt\": \"2019-01-23T10:22:15\",\n \"slug\": \"my-icon\",\n \"status\": \"inherit\",\n \"type\": \"attachment\",\n \"link\": \"https://example.com/my-icon/\",\n \"title\": {\n \"rendered\": \"my-icon\"\n },\n \"author\": 1,\n \"comment_status\": \"open\",\n \"ping_status\": \"closed\",\n \"template\": \"\",\n \"meta\": [],\n \"description\": {\n \"rendered\": \"<p class=\\\"attachment\\\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\\\"300\\\" height=\\\"300\\\" src=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png\\\" class=\\\"attachment-medium size-medium\\\" alt=\\\"\\\" srcset=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\\\" sizes=\\\"(max-width: 300px) 100vw, 300px\\\" /></a></p>\\n\"\n },\n \"caption\": {\n \"rendered\": \"\"\n },\n \"alt_text\": \"\",\n \"media_type\": \"image\",\n \"mime_type\": \"image/png\",\n \"media_details\": {\n \"width\": 300,\n \"height\": 300,\n \"file\": \"2019/01/my-icon.png\",\n \"sizes\": {\n \"thumbnail\": {\n \"file\": \"my-icon-150x150.png\",\n \"width\": \"150\",\n \"height\": \"150\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png\"\n },\n \"portfolio-thumbnail\": {\n \"file\": \"my-icon-300x240.png\",\n \"width\": \"300\",\n \"height\": \"240\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png\"\n },\n \"full\": {\n \"file\": \"my-icon.png\",\n \"width\": 300,\n \"height\": 300,\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n }\n },\n \"image_meta\": {\n \"aperture\": \"0\",\n \"credit\": \"\",\n \"camera\": \"\",\n \"caption\": \"\",\n \"created_timestamp\": \"0\",\n \"copyright\": \"\",\n \"focal_length\": \"0\",\n \"iso\": \"0\",\n \"shutter_speed\": \"0\",\n \"title\": \"\",\n \"orientation\": \"0\"\n }\n },\n \"post\": null,\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\",\n \"_links\": {\n \"self\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media/546\"\n }\n ],\n \"collection\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media\"\n }\n ],\n \"about\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/types/attachment\"\n }\n ],\n \"author\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/users/1\"\n }\n ],\n \"replies\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/comments?post=546\"\n }\n ]\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329701,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>You can create your own AJAX action to handle this:</p>\n\n<pre><code>add_action( 'wp_ajax_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n\nfunction smyles_get_attachment_src_details() {\n\n check_ajax_referer( 'smyles_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n $user_id = get_current_user_id();\n\n if ( empty( $user_id ) ) {\n wp_send_json_error( array( 'not_logged_in' => 'User is not logged in' ) );\n return;\n }\n\n $attach_id = absint( $_POST['attachment_id'] );\n $size = array_key_exists( 'size', $_POST ) ? sanitize_text_field( $_POST['size'] ) : 'thumbnail';\n\n if( $source = wp_get_attachment_image_src( $attach_id, $size ) ){\n wp_send_json_success( $source );\n } else {\n wp_send_json_error();\n }\n}\n</code></pre>\n\n<p>If you don't care if user is logged in you can remove that code, but you should still keep the nonce handling (ALWAYS think security first!) as this prevents allowing external calls (not from your site) to your endpoints</p>\n\n<p>The return value will be JSON with - url, width, height, is_intermediate</p>\n"
}
] | 2019/02/23 | [
"https://wordpress.stackexchange.com/questions/329702",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161894/"
] | How can I be displayed in an article written by a writer in a text format only to the same author. | You can use REST API to [retrieve media item](https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item). Just send GET request to this address (change example.com to your site):
```
http://example.com/wp-json/wp/v2/media/<id>
```
If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:
```
{
"id": 546,
"date": "2019-01-23T11:22:15",
"date_gmt": "2019-01-23T10:22:15",
"guid": {
"rendered": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
},
"modified": "2019-01-23T11:22:15",
"modified_gmt": "2019-01-23T10:22:15",
"slug": "my-icon",
"status": "inherit",
"type": "attachment",
"link": "https://example.com/my-icon/",
"title": {
"rendered": "my-icon"
},
"author": 1,
"comment_status": "open",
"ping_status": "closed",
"template": "",
"meta": [],
"description": {
"rendered": "<p class=\"attachment\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\"300\" height=\"300\" src=\"https://example.com/wp-content/uploads/2019/01/my-icon.png\" class=\"attachment-medium size-medium\" alt=\"\" srcset=\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\" sizes=\"(max-width: 300px) 100vw, 300px\" /></a></p>\n"
},
"caption": {
"rendered": ""
},
"alt_text": "",
"media_type": "image",
"mime_type": "image/png",
"media_details": {
"width": 300,
"height": 300,
"file": "2019/01/my-icon.png",
"sizes": {
"thumbnail": {
"file": "my-icon-150x150.png",
"width": "150",
"height": "150",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png"
},
"portfolio-thumbnail": {
"file": "my-icon-300x240.png",
"width": "300",
"height": "240",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png"
},
"full": {
"file": "my-icon.png",
"width": 300,
"height": 300,
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
}
},
"image_meta": {
"aperture": "0",
"credit": "",
"camera": "",
"caption": "",
"created_timestamp": "0",
"copyright": "",
"focal_length": "0",
"iso": "0",
"shutter_speed": "0",
"title": "",
"orientation": "0"
}
},
"post": null,
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png",
"_links": {
"self": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media/546"
}
],
"collection": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media"
}
],
"about": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/types/attachment"
}
],
"author": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/users/1"
}
],
"replies": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/comments?post=546"
}
]
}
}
``` |
329,715 | <p>I created a page template to serve information dynamically.</p>
<p>For url like</p>
<p>example.com/the-hamptons => index.php?page_id=92&filter=the-hamptons</p>
<p>For url like</p>
<p>example.com/page-that-exists <- show page</p>
<p>Basically, if the url points to a page that exists, show the page. If the page does not exist, pass everything after the / to the page template in variable 'filter'.</p>
<p>I added the following to functions.php in my child theme.</p>
<pre><code>function add_query_vars($aVars) {
$aVars[] = "filter";
return $aVars;
}
// hook add_query_vars function into query_vars
add_filter('query_vars', 'add_query_vars');
</code></pre>
<p>and</p>
<pre><code>function add_rewrite_rules($aRules) {
$aNewRules = array('/([^/]+)/?$' => 'index.php?page_id=92&filter=matches[1]');
$aRules = $aNewRules + $aRules;
return $aRules;
}
// hook add_rewrite_rules function into rewrite_rules_array
add_filter('rewrite_rules_array', 'add_rewrite_rules');
</code></pre>
<p>I get a page not found when I type a url that does not exist.</p>
<p>If type a url that exists, it shows the correct page in that url.</p>
<p>Thank you for the help.</p>
| [
{
"answer_id": 329698,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>You can use REST API to <a href=\"https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item\" rel=\"nofollow noreferrer\">retrieve media item</a>. Just send GET request to this address (change example.com to your site):</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/media/<id>\n</code></pre>\n\n<p>If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:</p>\n\n<pre><code>{\n \"id\": 546,\n \"date\": \"2019-01-23T11:22:15\",\n \"date_gmt\": \"2019-01-23T10:22:15\",\n \"guid\": {\n \"rendered\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n },\n \"modified\": \"2019-01-23T11:22:15\",\n \"modified_gmt\": \"2019-01-23T10:22:15\",\n \"slug\": \"my-icon\",\n \"status\": \"inherit\",\n \"type\": \"attachment\",\n \"link\": \"https://example.com/my-icon/\",\n \"title\": {\n \"rendered\": \"my-icon\"\n },\n \"author\": 1,\n \"comment_status\": \"open\",\n \"ping_status\": \"closed\",\n \"template\": \"\",\n \"meta\": [],\n \"description\": {\n \"rendered\": \"<p class=\\\"attachment\\\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\\\"300\\\" height=\\\"300\\\" src=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png\\\" class=\\\"attachment-medium size-medium\\\" alt=\\\"\\\" srcset=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\\\" sizes=\\\"(max-width: 300px) 100vw, 300px\\\" /></a></p>\\n\"\n },\n \"caption\": {\n \"rendered\": \"\"\n },\n \"alt_text\": \"\",\n \"media_type\": \"image\",\n \"mime_type\": \"image/png\",\n \"media_details\": {\n \"width\": 300,\n \"height\": 300,\n \"file\": \"2019/01/my-icon.png\",\n \"sizes\": {\n \"thumbnail\": {\n \"file\": \"my-icon-150x150.png\",\n \"width\": \"150\",\n \"height\": \"150\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png\"\n },\n \"portfolio-thumbnail\": {\n \"file\": \"my-icon-300x240.png\",\n \"width\": \"300\",\n \"height\": \"240\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png\"\n },\n \"full\": {\n \"file\": \"my-icon.png\",\n \"width\": 300,\n \"height\": 300,\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n }\n },\n \"image_meta\": {\n \"aperture\": \"0\",\n \"credit\": \"\",\n \"camera\": \"\",\n \"caption\": \"\",\n \"created_timestamp\": \"0\",\n \"copyright\": \"\",\n \"focal_length\": \"0\",\n \"iso\": \"0\",\n \"shutter_speed\": \"0\",\n \"title\": \"\",\n \"orientation\": \"0\"\n }\n },\n \"post\": null,\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\",\n \"_links\": {\n \"self\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media/546\"\n }\n ],\n \"collection\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media\"\n }\n ],\n \"about\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/types/attachment\"\n }\n ],\n \"author\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/users/1\"\n }\n ],\n \"replies\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/comments?post=546\"\n }\n ]\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329701,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>You can create your own AJAX action to handle this:</p>\n\n<pre><code>add_action( 'wp_ajax_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n\nfunction smyles_get_attachment_src_details() {\n\n check_ajax_referer( 'smyles_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n $user_id = get_current_user_id();\n\n if ( empty( $user_id ) ) {\n wp_send_json_error( array( 'not_logged_in' => 'User is not logged in' ) );\n return;\n }\n\n $attach_id = absint( $_POST['attachment_id'] );\n $size = array_key_exists( 'size', $_POST ) ? sanitize_text_field( $_POST['size'] ) : 'thumbnail';\n\n if( $source = wp_get_attachment_image_src( $attach_id, $size ) ){\n wp_send_json_success( $source );\n } else {\n wp_send_json_error();\n }\n}\n</code></pre>\n\n<p>If you don't care if user is logged in you can remove that code, but you should still keep the nonce handling (ALWAYS think security first!) as this prevents allowing external calls (not from your site) to your endpoints</p>\n\n<p>The return value will be JSON with - url, width, height, is_intermediate</p>\n"
}
] | 2019/02/24 | [
"https://wordpress.stackexchange.com/questions/329715",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26514/"
] | I created a page template to serve information dynamically.
For url like
example.com/the-hamptons => index.php?page\_id=92&filter=the-hamptons
For url like
example.com/page-that-exists <- show page
Basically, if the url points to a page that exists, show the page. If the page does not exist, pass everything after the / to the page template in variable 'filter'.
I added the following to functions.php in my child theme.
```
function add_query_vars($aVars) {
$aVars[] = "filter";
return $aVars;
}
// hook add_query_vars function into query_vars
add_filter('query_vars', 'add_query_vars');
```
and
```
function add_rewrite_rules($aRules) {
$aNewRules = array('/([^/]+)/?$' => 'index.php?page_id=92&filter=matches[1]');
$aRules = $aNewRules + $aRules;
return $aRules;
}
// hook add_rewrite_rules function into rewrite_rules_array
add_filter('rewrite_rules_array', 'add_rewrite_rules');
```
I get a page not found when I type a url that does not exist.
If type a url that exists, it shows the correct page in that url.
Thank you for the help. | You can use REST API to [retrieve media item](https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item). Just send GET request to this address (change example.com to your site):
```
http://example.com/wp-json/wp/v2/media/<id>
```
If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:
```
{
"id": 546,
"date": "2019-01-23T11:22:15",
"date_gmt": "2019-01-23T10:22:15",
"guid": {
"rendered": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
},
"modified": "2019-01-23T11:22:15",
"modified_gmt": "2019-01-23T10:22:15",
"slug": "my-icon",
"status": "inherit",
"type": "attachment",
"link": "https://example.com/my-icon/",
"title": {
"rendered": "my-icon"
},
"author": 1,
"comment_status": "open",
"ping_status": "closed",
"template": "",
"meta": [],
"description": {
"rendered": "<p class=\"attachment\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\"300\" height=\"300\" src=\"https://example.com/wp-content/uploads/2019/01/my-icon.png\" class=\"attachment-medium size-medium\" alt=\"\" srcset=\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\" sizes=\"(max-width: 300px) 100vw, 300px\" /></a></p>\n"
},
"caption": {
"rendered": ""
},
"alt_text": "",
"media_type": "image",
"mime_type": "image/png",
"media_details": {
"width": 300,
"height": 300,
"file": "2019/01/my-icon.png",
"sizes": {
"thumbnail": {
"file": "my-icon-150x150.png",
"width": "150",
"height": "150",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png"
},
"portfolio-thumbnail": {
"file": "my-icon-300x240.png",
"width": "300",
"height": "240",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png"
},
"full": {
"file": "my-icon.png",
"width": 300,
"height": 300,
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
}
},
"image_meta": {
"aperture": "0",
"credit": "",
"camera": "",
"caption": "",
"created_timestamp": "0",
"copyright": "",
"focal_length": "0",
"iso": "0",
"shutter_speed": "0",
"title": "",
"orientation": "0"
}
},
"post": null,
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png",
"_links": {
"self": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media/546"
}
],
"collection": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media"
}
],
"about": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/types/attachment"
}
],
"author": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/users/1"
}
],
"replies": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/comments?post=546"
}
]
}
}
``` |
329,739 | <p>I want to create a background image effect that will change the image when the user scroll. I'm facing a problem with the images urls, how i can fix this? How I can link an image url in jquery from a wordpress page?</p>
<p>Here is the code. The url is not correct and I can't figure how to link it correctly from the js script.</p>
<pre><code>$(window).scroll(function(e){
e.preventDefault();
var scrollPos = $(window).scrollTop();
if(scrollPos >= 100){
$('#portfolio-cover').css({'backgroundImage':'url("assets/img/top-page2.jpg")'});
}
else if(scrollPos >= 120){
$('#portfolio-cover').css({'backgroundImage':'url("assets/img/top-page3.jpg")'});
}
else if(scrollPos >= 150){
$('#portfolio-cover').css({'backgroundImage':'url("assets/img/top-page4.jpg")'});
}
else{
$('#portfolio-cover').css({'backgroundImage':'url("assets/img/top-page1.jpg")'});
}
});
</code></pre>
| [
{
"answer_id": 329698,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>You can use REST API to <a href=\"https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item\" rel=\"nofollow noreferrer\">retrieve media item</a>. Just send GET request to this address (change example.com to your site):</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/media/<id>\n</code></pre>\n\n<p>If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:</p>\n\n<pre><code>{\n \"id\": 546,\n \"date\": \"2019-01-23T11:22:15\",\n \"date_gmt\": \"2019-01-23T10:22:15\",\n \"guid\": {\n \"rendered\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n },\n \"modified\": \"2019-01-23T11:22:15\",\n \"modified_gmt\": \"2019-01-23T10:22:15\",\n \"slug\": \"my-icon\",\n \"status\": \"inherit\",\n \"type\": \"attachment\",\n \"link\": \"https://example.com/my-icon/\",\n \"title\": {\n \"rendered\": \"my-icon\"\n },\n \"author\": 1,\n \"comment_status\": \"open\",\n \"ping_status\": \"closed\",\n \"template\": \"\",\n \"meta\": [],\n \"description\": {\n \"rendered\": \"<p class=\\\"attachment\\\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\\\"300\\\" height=\\\"300\\\" src=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png\\\" class=\\\"attachment-medium size-medium\\\" alt=\\\"\\\" srcset=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\\\" sizes=\\\"(max-width: 300px) 100vw, 300px\\\" /></a></p>\\n\"\n },\n \"caption\": {\n \"rendered\": \"\"\n },\n \"alt_text\": \"\",\n \"media_type\": \"image\",\n \"mime_type\": \"image/png\",\n \"media_details\": {\n \"width\": 300,\n \"height\": 300,\n \"file\": \"2019/01/my-icon.png\",\n \"sizes\": {\n \"thumbnail\": {\n \"file\": \"my-icon-150x150.png\",\n \"width\": \"150\",\n \"height\": \"150\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png\"\n },\n \"portfolio-thumbnail\": {\n \"file\": \"my-icon-300x240.png\",\n \"width\": \"300\",\n \"height\": \"240\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png\"\n },\n \"full\": {\n \"file\": \"my-icon.png\",\n \"width\": 300,\n \"height\": 300,\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n }\n },\n \"image_meta\": {\n \"aperture\": \"0\",\n \"credit\": \"\",\n \"camera\": \"\",\n \"caption\": \"\",\n \"created_timestamp\": \"0\",\n \"copyright\": \"\",\n \"focal_length\": \"0\",\n \"iso\": \"0\",\n \"shutter_speed\": \"0\",\n \"title\": \"\",\n \"orientation\": \"0\"\n }\n },\n \"post\": null,\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\",\n \"_links\": {\n \"self\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media/546\"\n }\n ],\n \"collection\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media\"\n }\n ],\n \"about\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/types/attachment\"\n }\n ],\n \"author\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/users/1\"\n }\n ],\n \"replies\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/comments?post=546\"\n }\n ]\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329701,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>You can create your own AJAX action to handle this:</p>\n\n<pre><code>add_action( 'wp_ajax_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n\nfunction smyles_get_attachment_src_details() {\n\n check_ajax_referer( 'smyles_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n $user_id = get_current_user_id();\n\n if ( empty( $user_id ) ) {\n wp_send_json_error( array( 'not_logged_in' => 'User is not logged in' ) );\n return;\n }\n\n $attach_id = absint( $_POST['attachment_id'] );\n $size = array_key_exists( 'size', $_POST ) ? sanitize_text_field( $_POST['size'] ) : 'thumbnail';\n\n if( $source = wp_get_attachment_image_src( $attach_id, $size ) ){\n wp_send_json_success( $source );\n } else {\n wp_send_json_error();\n }\n}\n</code></pre>\n\n<p>If you don't care if user is logged in you can remove that code, but you should still keep the nonce handling (ALWAYS think security first!) as this prevents allowing external calls (not from your site) to your endpoints</p>\n\n<p>The return value will be JSON with - url, width, height, is_intermediate</p>\n"
}
] | 2019/02/24 | [
"https://wordpress.stackexchange.com/questions/329739",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159508/"
] | I want to create a background image effect that will change the image when the user scroll. I'm facing a problem with the images urls, how i can fix this? How I can link an image url in jquery from a wordpress page?
Here is the code. The url is not correct and I can't figure how to link it correctly from the js script.
```
$(window).scroll(function(e){
e.preventDefault();
var scrollPos = $(window).scrollTop();
if(scrollPos >= 100){
$('#portfolio-cover').css({'backgroundImage':'url("assets/img/top-page2.jpg")'});
}
else if(scrollPos >= 120){
$('#portfolio-cover').css({'backgroundImage':'url("assets/img/top-page3.jpg")'});
}
else if(scrollPos >= 150){
$('#portfolio-cover').css({'backgroundImage':'url("assets/img/top-page4.jpg")'});
}
else{
$('#portfolio-cover').css({'backgroundImage':'url("assets/img/top-page1.jpg")'});
}
});
``` | You can use REST API to [retrieve media item](https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item). Just send GET request to this address (change example.com to your site):
```
http://example.com/wp-json/wp/v2/media/<id>
```
If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:
```
{
"id": 546,
"date": "2019-01-23T11:22:15",
"date_gmt": "2019-01-23T10:22:15",
"guid": {
"rendered": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
},
"modified": "2019-01-23T11:22:15",
"modified_gmt": "2019-01-23T10:22:15",
"slug": "my-icon",
"status": "inherit",
"type": "attachment",
"link": "https://example.com/my-icon/",
"title": {
"rendered": "my-icon"
},
"author": 1,
"comment_status": "open",
"ping_status": "closed",
"template": "",
"meta": [],
"description": {
"rendered": "<p class=\"attachment\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\"300\" height=\"300\" src=\"https://example.com/wp-content/uploads/2019/01/my-icon.png\" class=\"attachment-medium size-medium\" alt=\"\" srcset=\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\" sizes=\"(max-width: 300px) 100vw, 300px\" /></a></p>\n"
},
"caption": {
"rendered": ""
},
"alt_text": "",
"media_type": "image",
"mime_type": "image/png",
"media_details": {
"width": 300,
"height": 300,
"file": "2019/01/my-icon.png",
"sizes": {
"thumbnail": {
"file": "my-icon-150x150.png",
"width": "150",
"height": "150",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png"
},
"portfolio-thumbnail": {
"file": "my-icon-300x240.png",
"width": "300",
"height": "240",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png"
},
"full": {
"file": "my-icon.png",
"width": 300,
"height": 300,
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
}
},
"image_meta": {
"aperture": "0",
"credit": "",
"camera": "",
"caption": "",
"created_timestamp": "0",
"copyright": "",
"focal_length": "0",
"iso": "0",
"shutter_speed": "0",
"title": "",
"orientation": "0"
}
},
"post": null,
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png",
"_links": {
"self": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media/546"
}
],
"collection": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media"
}
],
"about": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/types/attachment"
}
],
"author": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/users/1"
}
],
"replies": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/comments?post=546"
}
]
}
}
``` |
329,746 | <p>Here is the case, my <a href="https://iavinash.com" rel="nofollow noreferrer">oracle fusion</a> website was initially installed without SSL, last year using plugin “Really Simple SSL” plugin and following <a href="https://iavinash.com/free-ssl-make-website-https/" rel="nofollow noreferrer">this article</a> I changed it to HTTPS.</p>
<p>Now my hosting provider is providing free SSL, the problem is, if I install another wordpress in subdirectory <a href="https://iavinash.com/ask" rel="nofollow noreferrer">https://iavinash.com/ask</a> i cannot access wordpress backend. You can see it by navigating to <a href="https://iavinash.com/ask/wp-login.php" rel="nofollow noreferrer">https://iavinash.com/ask/wp-login.php</a></p>
<p>Note : I used Softaculous to install wordpress in subdirectory and selected https:// protocol.</p>
<p>Thanks
Avinash</p>
| [
{
"answer_id": 329698,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>You can use REST API to <a href=\"https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item\" rel=\"nofollow noreferrer\">retrieve media item</a>. Just send GET request to this address (change example.com to your site):</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/media/<id>\n</code></pre>\n\n<p>If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:</p>\n\n<pre><code>{\n \"id\": 546,\n \"date\": \"2019-01-23T11:22:15\",\n \"date_gmt\": \"2019-01-23T10:22:15\",\n \"guid\": {\n \"rendered\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n },\n \"modified\": \"2019-01-23T11:22:15\",\n \"modified_gmt\": \"2019-01-23T10:22:15\",\n \"slug\": \"my-icon\",\n \"status\": \"inherit\",\n \"type\": \"attachment\",\n \"link\": \"https://example.com/my-icon/\",\n \"title\": {\n \"rendered\": \"my-icon\"\n },\n \"author\": 1,\n \"comment_status\": \"open\",\n \"ping_status\": \"closed\",\n \"template\": \"\",\n \"meta\": [],\n \"description\": {\n \"rendered\": \"<p class=\\\"attachment\\\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\\\"300\\\" height=\\\"300\\\" src=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png\\\" class=\\\"attachment-medium size-medium\\\" alt=\\\"\\\" srcset=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\\\" sizes=\\\"(max-width: 300px) 100vw, 300px\\\" /></a></p>\\n\"\n },\n \"caption\": {\n \"rendered\": \"\"\n },\n \"alt_text\": \"\",\n \"media_type\": \"image\",\n \"mime_type\": \"image/png\",\n \"media_details\": {\n \"width\": 300,\n \"height\": 300,\n \"file\": \"2019/01/my-icon.png\",\n \"sizes\": {\n \"thumbnail\": {\n \"file\": \"my-icon-150x150.png\",\n \"width\": \"150\",\n \"height\": \"150\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png\"\n },\n \"portfolio-thumbnail\": {\n \"file\": \"my-icon-300x240.png\",\n \"width\": \"300\",\n \"height\": \"240\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png\"\n },\n \"full\": {\n \"file\": \"my-icon.png\",\n \"width\": 300,\n \"height\": 300,\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n }\n },\n \"image_meta\": {\n \"aperture\": \"0\",\n \"credit\": \"\",\n \"camera\": \"\",\n \"caption\": \"\",\n \"created_timestamp\": \"0\",\n \"copyright\": \"\",\n \"focal_length\": \"0\",\n \"iso\": \"0\",\n \"shutter_speed\": \"0\",\n \"title\": \"\",\n \"orientation\": \"0\"\n }\n },\n \"post\": null,\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\",\n \"_links\": {\n \"self\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media/546\"\n }\n ],\n \"collection\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media\"\n }\n ],\n \"about\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/types/attachment\"\n }\n ],\n \"author\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/users/1\"\n }\n ],\n \"replies\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/comments?post=546\"\n }\n ]\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329701,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>You can create your own AJAX action to handle this:</p>\n\n<pre><code>add_action( 'wp_ajax_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n\nfunction smyles_get_attachment_src_details() {\n\n check_ajax_referer( 'smyles_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n $user_id = get_current_user_id();\n\n if ( empty( $user_id ) ) {\n wp_send_json_error( array( 'not_logged_in' => 'User is not logged in' ) );\n return;\n }\n\n $attach_id = absint( $_POST['attachment_id'] );\n $size = array_key_exists( 'size', $_POST ) ? sanitize_text_field( $_POST['size'] ) : 'thumbnail';\n\n if( $source = wp_get_attachment_image_src( $attach_id, $size ) ){\n wp_send_json_success( $source );\n } else {\n wp_send_json_error();\n }\n}\n</code></pre>\n\n<p>If you don't care if user is logged in you can remove that code, but you should still keep the nonce handling (ALWAYS think security first!) as this prevents allowing external calls (not from your site) to your endpoints</p>\n\n<p>The return value will be JSON with - url, width, height, is_intermediate</p>\n"
}
] | 2019/02/24 | [
"https://wordpress.stackexchange.com/questions/329746",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101334/"
] | Here is the case, my [oracle fusion](https://iavinash.com) website was initially installed without SSL, last year using plugin “Really Simple SSL” plugin and following [this article](https://iavinash.com/free-ssl-make-website-https/) I changed it to HTTPS.
Now my hosting provider is providing free SSL, the problem is, if I install another wordpress in subdirectory <https://iavinash.com/ask> i cannot access wordpress backend. You can see it by navigating to <https://iavinash.com/ask/wp-login.php>
Note : I used Softaculous to install wordpress in subdirectory and selected https:// protocol.
Thanks
Avinash | You can use REST API to [retrieve media item](https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item). Just send GET request to this address (change example.com to your site):
```
http://example.com/wp-json/wp/v2/media/<id>
```
If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:
```
{
"id": 546,
"date": "2019-01-23T11:22:15",
"date_gmt": "2019-01-23T10:22:15",
"guid": {
"rendered": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
},
"modified": "2019-01-23T11:22:15",
"modified_gmt": "2019-01-23T10:22:15",
"slug": "my-icon",
"status": "inherit",
"type": "attachment",
"link": "https://example.com/my-icon/",
"title": {
"rendered": "my-icon"
},
"author": 1,
"comment_status": "open",
"ping_status": "closed",
"template": "",
"meta": [],
"description": {
"rendered": "<p class=\"attachment\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\"300\" height=\"300\" src=\"https://example.com/wp-content/uploads/2019/01/my-icon.png\" class=\"attachment-medium size-medium\" alt=\"\" srcset=\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\" sizes=\"(max-width: 300px) 100vw, 300px\" /></a></p>\n"
},
"caption": {
"rendered": ""
},
"alt_text": "",
"media_type": "image",
"mime_type": "image/png",
"media_details": {
"width": 300,
"height": 300,
"file": "2019/01/my-icon.png",
"sizes": {
"thumbnail": {
"file": "my-icon-150x150.png",
"width": "150",
"height": "150",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png"
},
"portfolio-thumbnail": {
"file": "my-icon-300x240.png",
"width": "300",
"height": "240",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png"
},
"full": {
"file": "my-icon.png",
"width": 300,
"height": 300,
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
}
},
"image_meta": {
"aperture": "0",
"credit": "",
"camera": "",
"caption": "",
"created_timestamp": "0",
"copyright": "",
"focal_length": "0",
"iso": "0",
"shutter_speed": "0",
"title": "",
"orientation": "0"
}
},
"post": null,
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png",
"_links": {
"self": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media/546"
}
],
"collection": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media"
}
],
"about": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/types/attachment"
}
],
"author": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/users/1"
}
],
"replies": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/comments?post=546"
}
]
}
}
``` |
329,754 | <p>I've created a block, and I need to save as post_meta a value from an action on the panel.</p>
<p>Php side:</p>
<pre><code>add_action( 'init', 'yasr_gutenberg_show_in_rest_overall_meta' );
function yasr_gutenberg_show_in_rest_overall_meta() {
register_meta( 'post', 'yasr_overall_rating',
array(
'show_in_rest' => true,
'single' => true,
'type' => 'number',
)
);
}
</code></pre>
<p>Then in js, I do this:</p>
<pre><code>attributes: {
//name of the attribute
overallRating: {
type: 'number',
source: 'meta',
meta: 'yasr_overall_rating'
},
}
edit:
function( props ) {
const { attributes: {overallRating}, setAttributes, isSelected } = props;
/***
Action and ajax action to update metadata
and where I use setAttributes to
update overallRating
***/
}
</code></pre>
<p>Everything seems to work, but when save or update the post, the overallRating get again the initial value, instead of the new one just saved fine with the ajax call.</p>
<p>How can I achieve this?</p>
| [
{
"answer_id": 329698,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>You can use REST API to <a href=\"https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item\" rel=\"nofollow noreferrer\">retrieve media item</a>. Just send GET request to this address (change example.com to your site):</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/media/<id>\n</code></pre>\n\n<p>If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:</p>\n\n<pre><code>{\n \"id\": 546,\n \"date\": \"2019-01-23T11:22:15\",\n \"date_gmt\": \"2019-01-23T10:22:15\",\n \"guid\": {\n \"rendered\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n },\n \"modified\": \"2019-01-23T11:22:15\",\n \"modified_gmt\": \"2019-01-23T10:22:15\",\n \"slug\": \"my-icon\",\n \"status\": \"inherit\",\n \"type\": \"attachment\",\n \"link\": \"https://example.com/my-icon/\",\n \"title\": {\n \"rendered\": \"my-icon\"\n },\n \"author\": 1,\n \"comment_status\": \"open\",\n \"ping_status\": \"closed\",\n \"template\": \"\",\n \"meta\": [],\n \"description\": {\n \"rendered\": \"<p class=\\\"attachment\\\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\\\"300\\\" height=\\\"300\\\" src=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png\\\" class=\\\"attachment-medium size-medium\\\" alt=\\\"\\\" srcset=\\\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\\\" sizes=\\\"(max-width: 300px) 100vw, 300px\\\" /></a></p>\\n\"\n },\n \"caption\": {\n \"rendered\": \"\"\n },\n \"alt_text\": \"\",\n \"media_type\": \"image\",\n \"mime_type\": \"image/png\",\n \"media_details\": {\n \"width\": 300,\n \"height\": 300,\n \"file\": \"2019/01/my-icon.png\",\n \"sizes\": {\n \"thumbnail\": {\n \"file\": \"my-icon-150x150.png\",\n \"width\": \"150\",\n \"height\": \"150\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png\"\n },\n \"portfolio-thumbnail\": {\n \"file\": \"my-icon-300x240.png\",\n \"width\": \"300\",\n \"height\": \"240\",\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png\"\n },\n \"full\": {\n \"file\": \"my-icon.png\",\n \"width\": 300,\n \"height\": 300,\n \"mime_type\": \"image/png\",\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\"\n }\n },\n \"image_meta\": {\n \"aperture\": \"0\",\n \"credit\": \"\",\n \"camera\": \"\",\n \"caption\": \"\",\n \"created_timestamp\": \"0\",\n \"copyright\": \"\",\n \"focal_length\": \"0\",\n \"iso\": \"0\",\n \"shutter_speed\": \"0\",\n \"title\": \"\",\n \"orientation\": \"0\"\n }\n },\n \"post\": null,\n \"source_url\": \"https://example.com/wp-content/uploads/2019/01/my-icon.png\",\n \"_links\": {\n \"self\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media/546\"\n }\n ],\n \"collection\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/media\"\n }\n ],\n \"about\": [\n {\n \"attributes\": [],\n \"href\": \"https://example.com/wp-json/wp/v2/types/attachment\"\n }\n ],\n \"author\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/users/1\"\n }\n ],\n \"replies\": [\n {\n \"attributes\": {\n \"embeddable\": true\n },\n \"href\": \"https://example.com/wp-json/wp/v2/comments?post=546\"\n }\n ]\n }\n}\n</code></pre>\n"
},
{
"answer_id": 329701,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>You can create your own AJAX action to handle this:</p>\n\n<pre><code>add_action( 'wp_ajax_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n\nfunction smyles_get_attachment_src_details() {\n\n check_ajax_referer( 'smyles_get_attachment_src_details', 'smyles_get_attachment_src_details' );\n $user_id = get_current_user_id();\n\n if ( empty( $user_id ) ) {\n wp_send_json_error( array( 'not_logged_in' => 'User is not logged in' ) );\n return;\n }\n\n $attach_id = absint( $_POST['attachment_id'] );\n $size = array_key_exists( 'size', $_POST ) ? sanitize_text_field( $_POST['size'] ) : 'thumbnail';\n\n if( $source = wp_get_attachment_image_src( $attach_id, $size ) ){\n wp_send_json_success( $source );\n } else {\n wp_send_json_error();\n }\n}\n</code></pre>\n\n<p>If you don't care if user is logged in you can remove that code, but you should still keep the nonce handling (ALWAYS think security first!) as this prevents allowing external calls (not from your site) to your endpoints</p>\n\n<p>The return value will be JSON with - url, width, height, is_intermediate</p>\n"
}
] | 2019/02/24 | [
"https://wordpress.stackexchange.com/questions/329754",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48442/"
] | I've created a block, and I need to save as post\_meta a value from an action on the panel.
Php side:
```
add_action( 'init', 'yasr_gutenberg_show_in_rest_overall_meta' );
function yasr_gutenberg_show_in_rest_overall_meta() {
register_meta( 'post', 'yasr_overall_rating',
array(
'show_in_rest' => true,
'single' => true,
'type' => 'number',
)
);
}
```
Then in js, I do this:
```
attributes: {
//name of the attribute
overallRating: {
type: 'number',
source: 'meta',
meta: 'yasr_overall_rating'
},
}
edit:
function( props ) {
const { attributes: {overallRating}, setAttributes, isSelected } = props;
/***
Action and ajax action to update metadata
and where I use setAttributes to
update overallRating
***/
}
```
Everything seems to work, but when save or update the post, the overallRating get again the initial value, instead of the new one just saved fine with the ajax call.
How can I achieve this? | You can use REST API to [retrieve media item](https://developer.wordpress.org/rest-api/reference/media/#retrieve-a-media-item). Just send GET request to this address (change example.com to your site):
```
http://example.com/wp-json/wp/v2/media/<id>
```
If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:
```
{
"id": 546,
"date": "2019-01-23T11:22:15",
"date_gmt": "2019-01-23T10:22:15",
"guid": {
"rendered": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
},
"modified": "2019-01-23T11:22:15",
"modified_gmt": "2019-01-23T10:22:15",
"slug": "my-icon",
"status": "inherit",
"type": "attachment",
"link": "https://example.com/my-icon/",
"title": {
"rendered": "my-icon"
},
"author": 1,
"comment_status": "open",
"ping_status": "closed",
"template": "",
"meta": [],
"description": {
"rendered": "<p class=\"attachment\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\"300\" height=\"300\" src=\"https://example.com/wp-content/uploads/2019/01/my-icon.png\" class=\"attachment-medium size-medium\" alt=\"\" srcset=\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\" sizes=\"(max-width: 300px) 100vw, 300px\" /></a></p>\n"
},
"caption": {
"rendered": ""
},
"alt_text": "",
"media_type": "image",
"mime_type": "image/png",
"media_details": {
"width": 300,
"height": 300,
"file": "2019/01/my-icon.png",
"sizes": {
"thumbnail": {
"file": "my-icon-150x150.png",
"width": "150",
"height": "150",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png"
},
"portfolio-thumbnail": {
"file": "my-icon-300x240.png",
"width": "300",
"height": "240",
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png"
},
"full": {
"file": "my-icon.png",
"width": 300,
"height": 300,
"mime_type": "image/png",
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
}
},
"image_meta": {
"aperture": "0",
"credit": "",
"camera": "",
"caption": "",
"created_timestamp": "0",
"copyright": "",
"focal_length": "0",
"iso": "0",
"shutter_speed": "0",
"title": "",
"orientation": "0"
}
},
"post": null,
"source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png",
"_links": {
"self": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media/546"
}
],
"collection": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/media"
}
],
"about": [
{
"attributes": [],
"href": "https://example.com/wp-json/wp/v2/types/attachment"
}
],
"author": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/users/1"
}
],
"replies": [
{
"attributes": {
"embeddable": true
},
"href": "https://example.com/wp-json/wp/v2/comments?post=546"
}
]
}
}
``` |
329,869 | <p><strong>TLDR; How can I run a shortcode with multiple shortcodes inside of it?</strong></p>
<p>I'm trying to run a shortcode with multiple shortcodes inside of it.</p>
<p>I can successfully run a shortcode with one shortcode inside of it with the following code in the theme:</p>
<pre><code>add_shortcode('outside_shortcode', function($attr, $content = null) {
return
'
<section class="example_section">
<div class="container">
<div class="row">
' . do_shortcode($content) . '
</div>
</div>
</section>
';
});
add_shortcode('inside_shortcode', function($atts, $content = null) {
$atts = shortcode_atts(
array(
'link' => 'https://link.com',
'image' => 'nameofimage',
), $atts);
return
'
<div class="col-6">
<a href="#!">
<div class="example">
<span class="helper"></span>
<img src="/wp-content/themes/mytheme/assets/images' . $atts['image'] . '.png">
</div>
</a>
</div>
';
});
</code></pre>
<p>and the following within the texteditor on Wordpress:</p>
<pre><code>[outside_shortcode]
[inside_shortcode link='https://mysite/section1' image='funimage']
[inside_shortcode link='https://mysite/section2' image='coolimage']
[/outside_shortcode]
</code></pre>
<p>However, I want to add a second div within the outside shortcode and add a second shortcode within that. My idea was something like:</p>
<pre><code>add_shortcode('outside_shortcode', function($attr, $content = null) {
return
'
<section class="first_section">
<div class="container">
<div class="row">
' . do_shortcode($content) . '
</div>
</div>
</section>
<section class="second_section">
<div class="container">
<div class="row">
' . do_shortcode($content) . '
</div>
</div>
</section>
';
});
add_shortcode('first_inside_shortcode', function($atts, $content = null) {
$atts = shortcode_atts(
array(
'link' => 'https://link.com',
'image' => 'nameofimage',
), $atts);
return
'
<div class="col-6 iamfirst">
<a href="#!">
<div class="example">
<span class="helper"></span>
<img src="/wp-content/themes/mytheme/assets/images' . $atts['image'] . '.png">
</div>
</a>
</div>
';
});
add_shortcode('second_inside_shortcode', function($atts, $content = null) {
$atts = shortcode_atts(
array(
'link' => 'https://link.com',
'image' => 'nameofimage',
), $atts);
return
'
<div class="col-6 iamsecond">
<a href="#!">
<div class="example">
<span class="helper"></span>
<img src="/wp-content/themes/mytheme/assets/images' . $atts['image'] . '.png">
</div>
</a>
</div>
';
});
</code></pre>
<p>However, the problem is that the reader doesn't know how to distinguish between $content.</p>
<p>Any idea how to fix this problem?</p>
<p>I have also tried </p>
<pre><code>do_shortcode( ' [first_inside_shortcode] ' )
</code></pre>
<p>but, then I cannot have multiple sections within the code on the WordPress editor</p>
<p>For example, this does not work:</p>
<pre><code>[outside_shortcode]
[inside_shortcode link='https://mysite/section1' image='funimage']
[inside_shortcode link='https://mysite/section2' image='coolimage']
[/outside_shortcode]
</code></pre>
<p>Instead, it only reads the first one.</p>
<p>Thanks!</p>
| [
{
"answer_id": 329828,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>If you know which particular shortcode you want to remove and you want\n to remove it permanently from your database, you can simply do a SQL\n query with the command below:</p>\n</blockquote>\n\n<pre><code>UPDATE wp_post SET post_content = REPLACE(post_content, '[shortcodename]', '' );\n</code></pre>\n\n<p>Replace “shortcodename” with the shortcode you want to remove.</p>\n\n<p><strong><em>Note: This is not a foolproof method because different shortcodes can come with different attributes and value, making it hard to form a catch-all SQL query.</em></strong></p>\n"
},
{
"answer_id": 329830,
"author": "djboris",
"author_id": 152412,
"author_profile": "https://wordpress.stackexchange.com/users/152412",
"pm_score": 2,
"selected": true,
"text": "<p>I love to use this tool, <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">Search and Replace for WordPress Databases</a>. It is basically a PHP script that is written for WordPress usage (but of course can be used with any database). When placed in the WordPress project, it automatically detects and loads the Database using data from <code>wp-config.php</code> file.</p>\n\n<p>It enables you to make database queries based on regex, with a 'dry runs' - you will see a preview of the data that will be changed, but no real changes would be made. Also, it is serialization aware, meaning, if the variable you are replacing is inside a serialized object, it will safely be replaced, without breaking the serialization.</p>\n\n<p>Setup is easy, just drop the folder in the WP root, and navigate the browser to the main PHP file. Remember to remove it afterwards.</p>\n\n<p>I think you will love it as well, but remember to backup and double check before any live runs.</p>\n"
},
{
"answer_id": 329831,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 2,
"selected": false,
"text": "<p>Site can be broken when you will update the content via SQL. I am giving a simple code and it will hide the <strong>[spacer height=”5px”]</strong> at front end.</p>\n\n<p>Open the functions.php file of your current theme and add this code at end of the file.</p>\n\n<pre><code>add_shortcode( 'spacer','wse2019_remove_spacer' );\nfunction wse2019_remove_spacer( $atts ) {\n return '';\n}\n</code></pre>\n\n<p>It will automatically delete(basically it is hiding) the shortcode from your all existing posts/pages.</p>\n"
},
{
"answer_id": 329834,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest workaround I can think of is to define the shortcode and output an empty string.\nAdd this code to functions.php of the current theme or in a custom plugin:</p>\n\n<pre><code>function wpse329827_ignore_spacer( $atts ) {\n return \"\";\n}\nadd_shortcode( 'spacer', 'wpse329827_ignore_spacer' );\n</code></pre>\n\n<p>If you want to completely remove the shortcode, there are some plugins out there that can make search and replace queries for you like <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">this</a> and <a href=\"https://wordpress.org/plugins/cm-on-demand-search-and-replace/\" rel=\"nofollow noreferrer\">this</a>.</p>\n\n<p>If you have shell access to your server you can do the search-replace manually using <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\"><code>wp search-replace</code></a> command with <code>--regex</code> option.</p>\n\n<p>Note that you should make a database backup before you do any replace operation.</p>\n"
},
{
"answer_id": 379258,
"author": "KBU nulleins",
"author_id": 198462,
"author_profile": "https://wordpress.stackexchange.com/users/198462",
"pm_score": 0,
"selected": false,
"text": "<p>With this small code-snippet you can remove <strong>all shortcodes</strong> from the db:</p>\n<ol>\n<li>Create a new file in the wordpress root dir</li>\n<li>Add the code below to the file</li>\n<li>Call the created file once</li>\n</ol>\n<p><strong>IMPORTANT</strong>:<br />\nThis will remove all Shortcodes directly from the db - so make a backup before you execute the file!</p>\n<pre><code><?php\nrequire_once('wp-load.php');\n\nglobal $wpdb;\n$allPosts = $wpdb->get_results("SELECT * FROM `wp_posts`");\nforeach($allPosts as $post){\n $content = RemoveShortcodes('[', ']', $post->post_content);\n $wpdb->update(\n 'wp_posts',array('post_content' => $content),array( 'ID' => $post->ID )\n );\n}\n\nfunction RemoveShortcodes($beginning, $end, $string) {\n $beginningPos = strpos($string, $beginning);\n $endPos = strpos($string, $end);\n if ($beginningPos === false || $endPos === false) {return $string;}\n $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);\n return RemoveShortcodes($beginning, $end, str_replace($textToDelete, '', $string));\n}\n?>\n</code></pre>\n"
}
] | 2019/02/25 | [
"https://wordpress.stackexchange.com/questions/329869",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151661/"
] | **TLDR; How can I run a shortcode with multiple shortcodes inside of it?**
I'm trying to run a shortcode with multiple shortcodes inside of it.
I can successfully run a shortcode with one shortcode inside of it with the following code in the theme:
```
add_shortcode('outside_shortcode', function($attr, $content = null) {
return
'
<section class="example_section">
<div class="container">
<div class="row">
' . do_shortcode($content) . '
</div>
</div>
</section>
';
});
add_shortcode('inside_shortcode', function($atts, $content = null) {
$atts = shortcode_atts(
array(
'link' => 'https://link.com',
'image' => 'nameofimage',
), $atts);
return
'
<div class="col-6">
<a href="#!">
<div class="example">
<span class="helper"></span>
<img src="/wp-content/themes/mytheme/assets/images' . $atts['image'] . '.png">
</div>
</a>
</div>
';
});
```
and the following within the texteditor on Wordpress:
```
[outside_shortcode]
[inside_shortcode link='https://mysite/section1' image='funimage']
[inside_shortcode link='https://mysite/section2' image='coolimage']
[/outside_shortcode]
```
However, I want to add a second div within the outside shortcode and add a second shortcode within that. My idea was something like:
```
add_shortcode('outside_shortcode', function($attr, $content = null) {
return
'
<section class="first_section">
<div class="container">
<div class="row">
' . do_shortcode($content) . '
</div>
</div>
</section>
<section class="second_section">
<div class="container">
<div class="row">
' . do_shortcode($content) . '
</div>
</div>
</section>
';
});
add_shortcode('first_inside_shortcode', function($atts, $content = null) {
$atts = shortcode_atts(
array(
'link' => 'https://link.com',
'image' => 'nameofimage',
), $atts);
return
'
<div class="col-6 iamfirst">
<a href="#!">
<div class="example">
<span class="helper"></span>
<img src="/wp-content/themes/mytheme/assets/images' . $atts['image'] . '.png">
</div>
</a>
</div>
';
});
add_shortcode('second_inside_shortcode', function($atts, $content = null) {
$atts = shortcode_atts(
array(
'link' => 'https://link.com',
'image' => 'nameofimage',
), $atts);
return
'
<div class="col-6 iamsecond">
<a href="#!">
<div class="example">
<span class="helper"></span>
<img src="/wp-content/themes/mytheme/assets/images' . $atts['image'] . '.png">
</div>
</a>
</div>
';
});
```
However, the problem is that the reader doesn't know how to distinguish between $content.
Any idea how to fix this problem?
I have also tried
```
do_shortcode( ' [first_inside_shortcode] ' )
```
but, then I cannot have multiple sections within the code on the WordPress editor
For example, this does not work:
```
[outside_shortcode]
[inside_shortcode link='https://mysite/section1' image='funimage']
[inside_shortcode link='https://mysite/section2' image='coolimage']
[/outside_shortcode]
```
Instead, it only reads the first one.
Thanks! | I love to use this tool, [Search and Replace for WordPress Databases](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/). It is basically a PHP script that is written for WordPress usage (but of course can be used with any database). When placed in the WordPress project, it automatically detects and loads the Database using data from `wp-config.php` file.
It enables you to make database queries based on regex, with a 'dry runs' - you will see a preview of the data that will be changed, but no real changes would be made. Also, it is serialization aware, meaning, if the variable you are replacing is inside a serialized object, it will safely be replaced, without breaking the serialization.
Setup is easy, just drop the folder in the WP root, and navigate the browser to the main PHP file. Remember to remove it afterwards.
I think you will love it as well, but remember to backup and double check before any live runs. |
329,875 | <p>I have twentyseventeen child-theme, and I found this code:</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'child_enqueue_styles',99);
function child_enqueue_styles() {
$parent_style = 'parent-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'seventeen-child',get_stylesheet_directory_uri() . '/style.css', array( $parent_style ));
}
if ( get_stylesheet() !== get_template() ) {
add_filter( 'pre_update_option_theme_mods_' . get_stylesheet(), function ( $value, $old_value ) {
update_option( 'theme_mods_' . get_template(), $value );
return $old_value; // prevent update to child theme mods
}, 10, 2 );
add_filter( 'pre_option_theme_mods_' . get_stylesheet(), function ( $default ) {
return get_option( 'theme_mods_' . get_template(), $default );
} );
}
</code></pre>
<p>..</p>
<p>But there is problem that style.css is loading twice. I tried code from Reference Wordpress, but then my overrides files like footer.php, navigation.php from child-theme are not loading.</p>
<p>Could someone help me with it to avoid loading .css twice and keep full functionality?</p>
| [
{
"answer_id": 329881,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>But there is problem that style.css is loading twice. </p>\n</blockquote>\n\n<p>This function <code>child_enqueue_styles()</code> enqueues two <code>style.css</code> files, one from parent theme and other from child theme.</p>\n\n<pre><code>// This enqueues style.css from parent theme\nwp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n\n// This enqueues style.css from child theme \nwp_enqueue_style( 'seventeen-child',get_stylesheet_directory_uri() . '/style.css', array( $parent_style ));\n</code></pre>\n\n<p>That's why there are two <code>style.css</code> files loaded. The child theme's <code>style.css</code> should only contain your customization and <strong>it should not be a copy</strong> of Parent theme's <code>style.css</code> file. </p>\n\n<p><strong>In case you are happy with parent theme's style</strong> and just want to override some template files, than you can remove this from your code to load only parent theme's style.</p>\n\n<pre><code>wp_enqueue_style( 'seventeen-child',get_stylesheet_directory_uri() . '/style.css', array( $parent_style ));\n</code></pre>\n"
},
{
"answer_id": 329973,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You usually don't need to enqueue a child theme's stylesheet. The parent theme does that. This is a bit confusing, so I'll explain.</p>\n\n<p>In most themes, Twenty Seventeen included, the stylesheet is loaded like this:</p>\n\n<pre><code>wp_enqueue_style( 'twentyseventeen-style', get_stylesheet_uri() );\n</code></pre>\n\n<p>The trick to understanding what's going on here is understanding what <code>get_stylesheet_uri()</code> does. When a regular theme is activated, this function returns the URL to the theme's style.css file. However, when a child theme is activated, the function returns the URL for the <em>child theme's</em> style.css file.</p>\n\n<p>This means that when you create a child theme with a style.css file, that file will automatically be enqueued, but the parent theme's won't. So all you need to do in your child theme is enqueue the parent theme's stylesheet:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 9 );\nfunction child_enqueue_styles() {\n wp_enqueue_style( 'parent-style', get_parent_theme_file_uri( 'style.css' ) );\n}\n</code></pre>\n\n<p>Note that I set the priority to <code>9</code>. This means that the parent theme's stylesheet will get enqueued before the child theme's, which will be enqueued at the default priority of <code>10</code>.</p>\n"
}
] | 2019/02/25 | [
"https://wordpress.stackexchange.com/questions/329875",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140882/"
] | I have twentyseventeen child-theme, and I found this code:
```
add_action( 'wp_enqueue_scripts', 'child_enqueue_styles',99);
function child_enqueue_styles() {
$parent_style = 'parent-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'seventeen-child',get_stylesheet_directory_uri() . '/style.css', array( $parent_style ));
}
if ( get_stylesheet() !== get_template() ) {
add_filter( 'pre_update_option_theme_mods_' . get_stylesheet(), function ( $value, $old_value ) {
update_option( 'theme_mods_' . get_template(), $value );
return $old_value; // prevent update to child theme mods
}, 10, 2 );
add_filter( 'pre_option_theme_mods_' . get_stylesheet(), function ( $default ) {
return get_option( 'theme_mods_' . get_template(), $default );
} );
}
```
..
But there is problem that style.css is loading twice. I tried code from Reference Wordpress, but then my overrides files like footer.php, navigation.php from child-theme are not loading.
Could someone help me with it to avoid loading .css twice and keep full functionality? | You usually don't need to enqueue a child theme's stylesheet. The parent theme does that. This is a bit confusing, so I'll explain.
In most themes, Twenty Seventeen included, the stylesheet is loaded like this:
```
wp_enqueue_style( 'twentyseventeen-style', get_stylesheet_uri() );
```
The trick to understanding what's going on here is understanding what `get_stylesheet_uri()` does. When a regular theme is activated, this function returns the URL to the theme's style.css file. However, when a child theme is activated, the function returns the URL for the *child theme's* style.css file.
This means that when you create a child theme with a style.css file, that file will automatically be enqueued, but the parent theme's won't. So all you need to do in your child theme is enqueue the parent theme's stylesheet:
```
add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 9 );
function child_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_parent_theme_file_uri( 'style.css' ) );
}
```
Note that I set the priority to `9`. This means that the parent theme's stylesheet will get enqueued before the child theme's, which will be enqueued at the default priority of `10`. |
329,886 | <p>So I want to apply a theme and style the lost password page without the use of a plugin. I don't want it to show the default Wordpress lost password page. I managed to style the login form by redirecting the URL to the styled version, but I'm lost as to how I can style the lost password page. </p>
<p>Any ideas?</p>
<p>Thanks! </p>
| [
{
"answer_id": 329881,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>But there is problem that style.css is loading twice. </p>\n</blockquote>\n\n<p>This function <code>child_enqueue_styles()</code> enqueues two <code>style.css</code> files, one from parent theme and other from child theme.</p>\n\n<pre><code>// This enqueues style.css from parent theme\nwp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n\n// This enqueues style.css from child theme \nwp_enqueue_style( 'seventeen-child',get_stylesheet_directory_uri() . '/style.css', array( $parent_style ));\n</code></pre>\n\n<p>That's why there are two <code>style.css</code> files loaded. The child theme's <code>style.css</code> should only contain your customization and <strong>it should not be a copy</strong> of Parent theme's <code>style.css</code> file. </p>\n\n<p><strong>In case you are happy with parent theme's style</strong> and just want to override some template files, than you can remove this from your code to load only parent theme's style.</p>\n\n<pre><code>wp_enqueue_style( 'seventeen-child',get_stylesheet_directory_uri() . '/style.css', array( $parent_style ));\n</code></pre>\n"
},
{
"answer_id": 329973,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You usually don't need to enqueue a child theme's stylesheet. The parent theme does that. This is a bit confusing, so I'll explain.</p>\n\n<p>In most themes, Twenty Seventeen included, the stylesheet is loaded like this:</p>\n\n<pre><code>wp_enqueue_style( 'twentyseventeen-style', get_stylesheet_uri() );\n</code></pre>\n\n<p>The trick to understanding what's going on here is understanding what <code>get_stylesheet_uri()</code> does. When a regular theme is activated, this function returns the URL to the theme's style.css file. However, when a child theme is activated, the function returns the URL for the <em>child theme's</em> style.css file.</p>\n\n<p>This means that when you create a child theme with a style.css file, that file will automatically be enqueued, but the parent theme's won't. So all you need to do in your child theme is enqueue the parent theme's stylesheet:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 9 );\nfunction child_enqueue_styles() {\n wp_enqueue_style( 'parent-style', get_parent_theme_file_uri( 'style.css' ) );\n}\n</code></pre>\n\n<p>Note that I set the priority to <code>9</code>. This means that the parent theme's stylesheet will get enqueued before the child theme's, which will be enqueued at the default priority of <code>10</code>.</p>\n"
}
] | 2019/02/25 | [
"https://wordpress.stackexchange.com/questions/329886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158774/"
] | So I want to apply a theme and style the lost password page without the use of a plugin. I don't want it to show the default Wordpress lost password page. I managed to style the login form by redirecting the URL to the styled version, but I'm lost as to how I can style the lost password page.
Any ideas?
Thanks! | You usually don't need to enqueue a child theme's stylesheet. The parent theme does that. This is a bit confusing, so I'll explain.
In most themes, Twenty Seventeen included, the stylesheet is loaded like this:
```
wp_enqueue_style( 'twentyseventeen-style', get_stylesheet_uri() );
```
The trick to understanding what's going on here is understanding what `get_stylesheet_uri()` does. When a regular theme is activated, this function returns the URL to the theme's style.css file. However, when a child theme is activated, the function returns the URL for the *child theme's* style.css file.
This means that when you create a child theme with a style.css file, that file will automatically be enqueued, but the parent theme's won't. So all you need to do in your child theme is enqueue the parent theme's stylesheet:
```
add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 9 );
function child_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_parent_theme_file_uri( 'style.css' ) );
}
```
Note that I set the priority to `9`. This means that the parent theme's stylesheet will get enqueued before the child theme's, which will be enqueued at the default priority of `10`. |
329,899 | <p>I am writing a simple plugin to accept a user number, show a form with information about the user, then post a payment amount. The user number is obtained from this http file include_once(PLCOA_ADMIN_PATH . 'views/plcoa-payment-start.php'); and loads perfectly. The info form is filled out using the php file include_once(PLCOA_ADMIN_PATH . 'views/plcoa-payment-add.php');
It has only one field - the payment amount in the form. When the Submit Button is pressed it runs this function.</p>
<pre><code>function payment_post(){
if ($_POST['post_action'] == 'Post')
{
//I do my db INSERT here
}
wp_redirect (PLCOA_ADMIN_PATH . 'views/plcoa-payment-start.php');
exit;
</code></pre>
<p>}</p>
<p>I've spent hours trying to figure out what I have wrong and I know it's simple. This is all running in the admin area. If I re_direct to an external site it works just fine. Is there some other way to re-direct, after inserting the record in the db, back to the start form?</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 329902,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>I think you understand <a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/\" rel=\"nofollow noreferrer\"><code>wp_redirect</code></a> incorrectly. </p>\n\n<p>This function redirects you to a different URL. It’s like sending <code>header('Location: ...');</code></p>\n\n<p>On the other hand, it looks like you’re trying to pass local path as its param. So it won’t work - such path is not a valid URL address.</p>\n"
},
{
"answer_id": 329903,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>Please pay attention to @KrzysiekDróżdż answer. </p>\n\n<pre><code>wp_redirect (PLCOA_ADMIN_PATH . 'views/plcoa-payment-start.php');\n</code></pre>\n\n<p>should be either something like</p>\n\n<pre><code>wp_redirect (PLCOA_ADMIN_URL . 'views/plcoa-payment-start.php'); \n// Assuming PLCOA_ADMIN_URL is defined\n</code></pre>\n\n<p>OR </p>\n\n<pre><code>include_once (PLCOA_ADMIN_PATH . 'views/plcoa-payment-start.php'); // Recommended\n</code></pre>\n"
}
] | 2019/02/25 | [
"https://wordpress.stackexchange.com/questions/329899",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/141156/"
] | I am writing a simple plugin to accept a user number, show a form with information about the user, then post a payment amount. The user number is obtained from this http file include\_once(PLCOA\_ADMIN\_PATH . 'views/plcoa-payment-start.php'); and loads perfectly. The info form is filled out using the php file include\_once(PLCOA\_ADMIN\_PATH . 'views/plcoa-payment-add.php');
It has only one field - the payment amount in the form. When the Submit Button is pressed it runs this function.
```
function payment_post(){
if ($_POST['post_action'] == 'Post')
{
//I do my db INSERT here
}
wp_redirect (PLCOA_ADMIN_PATH . 'views/plcoa-payment-start.php');
exit;
```
}
I've spent hours trying to figure out what I have wrong and I know it's simple. This is all running in the admin area. If I re\_direct to an external site it works just fine. Is there some other way to re-direct, after inserting the record in the db, back to the start form?
Thanks in advance! | I think you understand [`wp_redirect`](https://developer.wordpress.org/reference/functions/wp_redirect/) incorrectly.
This function redirects you to a different URL. It’s like sending `header('Location: ...');`
On the other hand, it looks like you’re trying to pass local path as its param. So it won’t work - such path is not a valid URL address. |
329,904 | <p>I'm trying to display a list of pages on an archive page.
The query I've written is meant to only fetch pages but for some reason it is also displaying one post (from the archive page this is on) amongst the pages.</p>
<p>Can anyone suggest what the issue is?</p>
<p>Thanks in advance. </p>
<pre><code> <?php $page_args = array(
'post_type' => 'page'
); ?>
<?php $page_query = new WP_Query($page_args); ?>
<div class="links_slider">
<a class="slide" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('links'); ?>
<span><?php the_title(); ?></span>
</a>
<?php while($page_query->have_posts()):$page_query->the_post(); ?>
<a class="slide" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('links'); ?>
<span><?php the_title(); ?></span>
</a>
<?php endwhile; ?>
</div>
</code></pre>
| [
{
"answer_id": 329906,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>Apparently this part of code before while loop is introducing undesired result.</p>\n\n<pre><code> <a class=\"slide\" href=\"<?php the_permalink(); ?>\">\n <?php the_post_thumbnail('links'); ?>\n <span><?php the_title(); ?></span>\n </a>\n</code></pre>\n\n<p>So the revised code should be something: </p>\n\n<pre><code><?php $page_args = array(\n 'post_type' => 'page'\n ); ?>\n\n <?php $page_query = new WP_Query($page_args); ?>\n\n <div class=\"links_slider\">\n <?php while( $page_query->have_posts() ): $page_query->the_post(); ?>\n\n <a class=\"slide\" href=\"<?php the_permalink(); ?>\">\n <?php the_post_thumbnail('links'); ?>\n <span><?php the_title(); ?></span>\n </a>\n\n <?php endwhile; ?>\n\n <?php wp_reset_postdata(); ?>\n\n </div>\n</code></pre>\n"
},
{
"answer_id": 329914,
"author": "user3205234",
"author_id": 46039,
"author_profile": "https://wordpress.stackexchange.com/users/46039",
"pm_score": 1,
"selected": false,
"text": "<p>The issue turned out to be in another part of my code and nothing to do the the above query, which works just fine.</p>\n"
}
] | 2019/02/25 | [
"https://wordpress.stackexchange.com/questions/329904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/46039/"
] | I'm trying to display a list of pages on an archive page.
The query I've written is meant to only fetch pages but for some reason it is also displaying one post (from the archive page this is on) amongst the pages.
Can anyone suggest what the issue is?
Thanks in advance.
```
<?php $page_args = array(
'post_type' => 'page'
); ?>
<?php $page_query = new WP_Query($page_args); ?>
<div class="links_slider">
<a class="slide" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('links'); ?>
<span><?php the_title(); ?></span>
</a>
<?php while($page_query->have_posts()):$page_query->the_post(); ?>
<a class="slide" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('links'); ?>
<span><?php the_title(); ?></span>
</a>
<?php endwhile; ?>
</div>
``` | The issue turned out to be in another part of my code and nothing to do the the above query, which works just fine. |
329,935 | <p>I'm trying to link to a custom css file in a new folder of a small plugin I'm trying to make. I can't seem to get it to work. This is the line I have</p>
<pre><code>echo '<link rel="stylesheet" href="' . esc_url( plugins_url( 'public/css/front-end/uwc-tabs-style.css', __FILE__)) . '" >';
</code></pre>
<p>I've also tried the following but neither works. </p>
<pre><code>echo '<link rel="stylesheet" href="' . plugins_url( 'public/css/front-end/uwc-tabs-style.css', __FILE__) . '" >';
</code></pre>
<p>As an edit. This is for an options result. eg. Select option 1 it returns the above stylesheet on the frontend</p>
| [
{
"answer_id": 329937,
"author": "John Cook",
"author_id": 124439,
"author_profile": "https://wordpress.stackexchange.com/users/124439",
"pm_score": -1,
"selected": false,
"text": "<p>I worked it out. In case anyone else comes here looking for the answer here it is. I just had to add <code>dirname(__FILE__)</code> in place of <code>__FILE__</code></p>\n\n<pre><code>echo '<link rel=\"stylesheet\" href=\"' . esc_url( plugins_url( 'public/css/front-end/uwc-tabs-style.css', dirname(__FILE__))) . '\" >';\n</code></pre>\n"
},
{
"answer_id": 329939,
"author": "brothman01",
"author_id": 104630,
"author_profile": "https://wordpress.stackexchange.com/users/104630",
"pm_score": 0,
"selected": false,
"text": "<p>I would use <code>wp_enqueue_style()</code> for this instead of echoing a <code><link></code>.</p>\n"
}
] | 2019/02/26 | [
"https://wordpress.stackexchange.com/questions/329935",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124439/"
] | I'm trying to link to a custom css file in a new folder of a small plugin I'm trying to make. I can't seem to get it to work. This is the line I have
```
echo '<link rel="stylesheet" href="' . esc_url( plugins_url( 'public/css/front-end/uwc-tabs-style.css', __FILE__)) . '" >';
```
I've also tried the following but neither works.
```
echo '<link rel="stylesheet" href="' . plugins_url( 'public/css/front-end/uwc-tabs-style.css', __FILE__) . '" >';
```
As an edit. This is for an options result. eg. Select option 1 it returns the above stylesheet on the frontend | I would use `wp_enqueue_style()` for this instead of echoing a `<link>`. |
329,938 | <p>I'm trying to load jquery from CDN instead of loading natively with wordpress. In my functions.php I have done it like below, making sure it should only happen on the front-end:</p>
<pre><code>function replace_jquery() {
if (!is_admin()) {
wp_deregister_script('jquery');
wp_register_script('jquery2', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js');
wp_enqueue_script('jquery2');
}
}
add_action('init', 'replace_jquery');
</code></pre>
<p>nonetheless, when I try to log in the admin area, I get a bunch of error starting with: </p>
<pre><code>Notice: wp_deregister_script was called <strong>incorrectly</strong>.
Do not deregister the <code>jquery</code> script in the administration area.
To target the front-end theme, use the <code>wp_enqueue_scripts</code> hook.
Please see <a href="https://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.
(This message was added in version 3.6.0.) in /app/public/wp-includes/functions.php on line 4204
</code></pre>
<p>Sometimes it does not throw this error, and sometimes it does. What am I doing wrong?</p>
| [
{
"answer_id": 329940,
"author": "brothman01",
"author_id": 104630,
"author_profile": "https://wordpress.stackexchange.com/users/104630",
"pm_score": -1,
"selected": false,
"text": "<p>try <code>wp_dequeue_script( 'jquery-ui-core' );</code> instead of <code>wp_deregister_script()</code>. It may theoretically work less efficiently but the other way is not working at all.</p>\n"
},
{
"answer_id": 329949,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>The error message describes your problem quite clearly:</p>\n\n<blockquote>\n <p>Notice: wp_deregister_script was called <strong>incorrectly</strong>. \n Do not deregister the <code>jquery</code> script in the administration area. \n To target the front-end theme, use the <code>wp_enqueue_scripts</code> hook.</p>\n</blockquote>\n\n<p>You're de-registering the script on the <code>init</code> hook:</p>\n\n<pre><code>add_action('init', 'replace_jquery');\n</code></pre>\n\n<p>This hook runs for the back and front end, but the debugger isn't smart enough to know that you're using <code>! is_admin()</code> inside the function. Regardless, you should just do what the error recommends and use the <code>wp_enqueue_scripts</code> hook:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'replace_jquery');\n</code></pre>\n\n<p>The original script will not be enqueued yet on the <code>init</code> hook, so attempting to de-register it on that hook won't work, as it will only get re-registered by the time the <code>wp_enqueue_scripts</code> hook runs.</p>\n\n<p>Also, the way you're going about this is likely to cause problems, for 2 reasons:</p>\n\n<ol>\n<li>You're enqueuing jQuery 3.3.1, but WordPress uses 1.12.4. This means that WordPress itself and the vast majority of plugins are expecting 1.12.4 to be loaded, but 3.3.1 will be loaded. Code written expecting 1.X will not necessarily be compatible with 3.X, which could cause plugins to break.</li>\n<li>You're enqueueing it with a different handle, <code>jquery2</code>. This means that any scripts that declare <code>jquery</code> as a dependency will not load. This will break a great number of plugins.</li>\n</ol>\n"
}
] | 2019/02/26 | [
"https://wordpress.stackexchange.com/questions/329938",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157281/"
] | I'm trying to load jquery from CDN instead of loading natively with wordpress. In my functions.php I have done it like below, making sure it should only happen on the front-end:
```
function replace_jquery() {
if (!is_admin()) {
wp_deregister_script('jquery');
wp_register_script('jquery2', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js');
wp_enqueue_script('jquery2');
}
}
add_action('init', 'replace_jquery');
```
nonetheless, when I try to log in the admin area, I get a bunch of error starting with:
```
Notice: wp_deregister_script was called <strong>incorrectly</strong>.
Do not deregister the <code>jquery</code> script in the administration area.
To target the front-end theme, use the <code>wp_enqueue_scripts</code> hook.
Please see <a href="https://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.
(This message was added in version 3.6.0.) in /app/public/wp-includes/functions.php on line 4204
```
Sometimes it does not throw this error, and sometimes it does. What am I doing wrong? | The error message describes your problem quite clearly:
>
> Notice: wp\_deregister\_script was called **incorrectly**.
> Do not deregister the `jquery` script in the administration area.
> To target the front-end theme, use the `wp_enqueue_scripts` hook.
>
>
>
You're de-registering the script on the `init` hook:
```
add_action('init', 'replace_jquery');
```
This hook runs for the back and front end, but the debugger isn't smart enough to know that you're using `! is_admin()` inside the function. Regardless, you should just do what the error recommends and use the `wp_enqueue_scripts` hook:
```
add_action('wp_enqueue_scripts', 'replace_jquery');
```
The original script will not be enqueued yet on the `init` hook, so attempting to de-register it on that hook won't work, as it will only get re-registered by the time the `wp_enqueue_scripts` hook runs.
Also, the way you're going about this is likely to cause problems, for 2 reasons:
1. You're enqueuing jQuery 3.3.1, but WordPress uses 1.12.4. This means that WordPress itself and the vast majority of plugins are expecting 1.12.4 to be loaded, but 3.3.1 will be loaded. Code written expecting 1.X will not necessarily be compatible with 3.X, which could cause plugins to break.
2. You're enqueueing it with a different handle, `jquery2`. This means that any scripts that declare `jquery` as a dependency will not load. This will break a great number of plugins. |
329,952 | <p>I have a multisite and a new theme that needs to be activated across all subsites. I found an answer by fuxia from 2012 and would like to know (1)
if there have been changes in WordPress since that time that would require an update to this filter, and (2) what other methods exist to accomplish this task, like using the switch_theme function or using MySQL if it is about updating an option.</p>
<p>Reference: <a href="https://wordpress.stackexchange.com/questions/54543/changing-multisite-themes-on-mass">Changing Multisite themes on mass</a></p>
| [
{
"answer_id": 329958,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": true,
"text": "<p>Fuxia was using <code>update_option</code> in her answer and it may work, but I wouldn't recommend that - it isn't the polite way of setting a theme. </p>\n\n<p>So how I would approach that problem?</p>\n\n<p>First of all, you want to perform this action only once and for all sites. So there is no point in using any hooks. Just run the code once and then delete it.</p>\n\n<p>And that code should loop through all sites and set their theme:</p>\n\n<pre><code>function switch_all_multisite_themes() {\n foreach ( get_sites() as $site ) {\n switch_to_blog( $site->blog_id );\n\n switch_theme( 'theme' ); // for example 'twentyten'\n\n restore_current_blog();\n }\n}\nswitch_all_multisite_themes(); // run this function only once\n</code></pre>\n"
},
{
"answer_id": 382320,
"author": "Patrick",
"author_id": 185516,
"author_profile": "https://wordpress.stackexchange.com/users/185516",
"pm_score": 2,
"selected": false,
"text": "<p>If you have SSH access to the server, then I highly recommend using the command line <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">Wordpress command line tool (wp cli)</a>. You can automate a lot of actions with this. Here are the docs on <a href=\"https://developer.wordpress.org/cli/commands/theme/activate/\" rel=\"nofollow noreferrer\">activating a theme</a>.</p>\n<p>Here's the code that I used. Worked through 10-15 sites in about 3 seconds. No need to add/delete code to any files, all done from the command line. Put this in a bash file (e.g. <code>update_theme.sh</code>), and run it with <code>bash update_theme.sh</code>:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>SITES=$(wp site list --field=url)\ntheme="THEME_NAME_HERE"\nfor s in $SITES\ndo \necho "Working on $s..."\nwp theme activate "$theme" --url=$s\ndone\n</code></pre>\n"
}
] | 2019/02/26 | [
"https://wordpress.stackexchange.com/questions/329952",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162050/"
] | I have a multisite and a new theme that needs to be activated across all subsites. I found an answer by fuxia from 2012 and would like to know (1)
if there have been changes in WordPress since that time that would require an update to this filter, and (2) what other methods exist to accomplish this task, like using the switch\_theme function or using MySQL if it is about updating an option.
Reference: [Changing Multisite themes on mass](https://wordpress.stackexchange.com/questions/54543/changing-multisite-themes-on-mass) | Fuxia was using `update_option` in her answer and it may work, but I wouldn't recommend that - it isn't the polite way of setting a theme.
So how I would approach that problem?
First of all, you want to perform this action only once and for all sites. So there is no point in using any hooks. Just run the code once and then delete it.
And that code should loop through all sites and set their theme:
```
function switch_all_multisite_themes() {
foreach ( get_sites() as $site ) {
switch_to_blog( $site->blog_id );
switch_theme( 'theme' ); // for example 'twentyten'
restore_current_blog();
}
}
switch_all_multisite_themes(); // run this function only once
``` |
329,962 | <p>I have tried to add custom <code>li</code> to my wordpress header menu using <code>functions.php</code>. Here is my code in <code>function</code> file.</p>
<pre><code>function register_header_menu() {
register_nav_menu('header-menu',__( 'Header Menu' ));
}
add_action( 'init', 'register_header_menu' );
</code></pre>
<p>add new element to header menu</p>
<pre><code>function add_new_item($items, $args) {
if( $args->theme_location == 'header-menu' ){
$items .= '<li> <a>Show whatever</a></li>';
}
return $items;
}
add_filter('wp_nav_menu_items', 'add_new_item');
</code></pre>
<p>I'm using below code to add menu into <code>header.php</code></p>
<pre><code>wp_nav_menu( array(
'theme_location' => 'header-menu',
'container' => 'ul',
'menu_class' => 'menu',
) ); ?>
</code></pre>
<p>Menu is visible on header, but my new item is not visible in the menu. How can I fix it?</p>
| [
{
"answer_id": 329967,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Default usage of <code>add_filter</code> looks like this:</p>\n\n<pre><code>add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )\n</code></pre>\n\n<p>As you can see, the default priority is 10 and by default only one param is passed.</p>\n\n<p>In your code you need your filter to get 2 params, because <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu_items</code></a> takes 2 params (<code>$items</code> and <code>$args</code>) and you need both of them in your filter. So you have to pass 2 as number of params, when you add your filter:</p>\n\n<pre><code>function add_new_item_to_menu( $items, $args ) {\n if ( 'header-menu' == $args->theme_location ) {\n $items .= '<li><a>Show whatever</a></li>';\n }\n return $items;\n}\nadd_filter( 'wp_nav_menu_items', 'add_new_item_to_menu', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 408024,
"author": "kiberchaka",
"author_id": 224395,
"author_profile": "https://wordpress.stackexchange.com/users/224395",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to Krzysiek Dróżdż's answer:</p>\n<p>If you show menu in Elementor widget, you can't check <code>$args->theme_location</code>\nSo, I check by <code>$args->menu == 'primary-menu'</code></p>\n<p>Also it will be helpful if you show a menu in more then one place, this way, you can show it everywhere where menu with <code>primary-menu</code> is displayed.</p>\n"
}
] | 2019/02/26 | [
"https://wordpress.stackexchange.com/questions/329962",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109465/"
] | I have tried to add custom `li` to my wordpress header menu using `functions.php`. Here is my code in `function` file.
```
function register_header_menu() {
register_nav_menu('header-menu',__( 'Header Menu' ));
}
add_action( 'init', 'register_header_menu' );
```
add new element to header menu
```
function add_new_item($items, $args) {
if( $args->theme_location == 'header-menu' ){
$items .= '<li> <a>Show whatever</a></li>';
}
return $items;
}
add_filter('wp_nav_menu_items', 'add_new_item');
```
I'm using below code to add menu into `header.php`
```
wp_nav_menu( array(
'theme_location' => 'header-menu',
'container' => 'ul',
'menu_class' => 'menu',
) ); ?>
```
Menu is visible on header, but my new item is not visible in the menu. How can I fix it? | Default usage of `add_filter` looks like this:
```
add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
```
As you can see, the default priority is 10 and by default only one param is passed.
In your code you need your filter to get 2 params, because [`wp_nav_menu_items`](https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/) takes 2 params (`$items` and `$args`) and you need both of them in your filter. So you have to pass 2 as number of params, when you add your filter:
```
function add_new_item_to_menu( $items, $args ) {
if ( 'header-menu' == $args->theme_location ) {
$items .= '<li><a>Show whatever</a></li>';
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'add_new_item_to_menu', 10, 2 );
``` |
329,976 | <p>When I visit sitemap.xml of my WordPress website I see this error. Here is the image<a href="https://i.stack.imgur.com/J2X63.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J2X63.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 329967,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Default usage of <code>add_filter</code> looks like this:</p>\n\n<pre><code>add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )\n</code></pre>\n\n<p>As you can see, the default priority is 10 and by default only one param is passed.</p>\n\n<p>In your code you need your filter to get 2 params, because <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu_items</code></a> takes 2 params (<code>$items</code> and <code>$args</code>) and you need both of them in your filter. So you have to pass 2 as number of params, when you add your filter:</p>\n\n<pre><code>function add_new_item_to_menu( $items, $args ) {\n if ( 'header-menu' == $args->theme_location ) {\n $items .= '<li><a>Show whatever</a></li>';\n }\n return $items;\n}\nadd_filter( 'wp_nav_menu_items', 'add_new_item_to_menu', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 408024,
"author": "kiberchaka",
"author_id": 224395,
"author_profile": "https://wordpress.stackexchange.com/users/224395",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to Krzysiek Dróżdż's answer:</p>\n<p>If you show menu in Elementor widget, you can't check <code>$args->theme_location</code>\nSo, I check by <code>$args->menu == 'primary-menu'</code></p>\n<p>Also it will be helpful if you show a menu in more then one place, this way, you can show it everywhere where menu with <code>primary-menu</code> is displayed.</p>\n"
}
] | 2019/02/26 | [
"https://wordpress.stackexchange.com/questions/329976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151277/"
] | When I visit sitemap.xml of my WordPress website I see this error. Here is the image[](https://i.stack.imgur.com/J2X63.png) | Default usage of `add_filter` looks like this:
```
add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
```
As you can see, the default priority is 10 and by default only one param is passed.
In your code you need your filter to get 2 params, because [`wp_nav_menu_items`](https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/) takes 2 params (`$items` and `$args`) and you need both of them in your filter. So you have to pass 2 as number of params, when you add your filter:
```
function add_new_item_to_menu( $items, $args ) {
if ( 'header-menu' == $args->theme_location ) {
$items .= '<li><a>Show whatever</a></li>';
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'add_new_item_to_menu', 10, 2 );
``` |
330,008 | <p>I have run into an issue with nonces becoming invalid, and being unable to refresh to a new nonce. In my example I have a Facebook Connect button, and a Facebook Disconnect button, each with their own nonce.</p>
<p>Once either one of these button is pressed, an AJAX call is made, and the other button is sent through AJAX and displayed on the page instead.</p>
<p>For sake of the example, we're starting with the Facebook Connect button.</p>
<pre><code><button type="button" id="facebook-connect-button" class="facebook-button" data-nonce="<?php echo wp_create_nonce('ns-social-facebook-authentication'); ?>">
<?php _e('Connect to', NS_USER_SYSTEM_TEXTDOMAIN); ?> Facebook
</button>
</code></pre>
<p>After this button is pressed, an AJAX call is made, which verifies the data-nonce property like so:</p>
<pre><code>check_ajax_referer( 'ns-social-facebook-authentication', '_nonce' );
</code></pre>
<p>No problems here, this works perfectly and my hooked function is working perfectly.</p>
<p>After this function has ran, it returns the Facebook Disconnect button that looks like this, and replaces the original button.</p>
<pre><code><button type="button" id="facebook-disconnect-button" class="facebook-disconnect-button" data-nonce="<?php echo wp_create_nonce('ns-social-facebook-disconnect'); ?>">
<?php _e('Disconnect from Facebook', NS_USER_SYSTEM_TEXTDOMAIN); ?>
</button>
</code></pre>
<p>After pressing this button, everything works fine like before, and this time, the Facebook Connect button is called again though AJAX. Now here's when the issue starts.</p>
<p>This new returned button contains the same nonce, which is now invalid and returns a 403 error, since it's already been used before.</p>
<p><strong>It looks like returning the button through AJAX does not refresh the nonce, even though it's already been used.</strong></p>
<p>I have also tried displaying both buttons on the page, and returning <em>just</em> a new nonce with AJAX every time a button is clicked, but still, it keeps returning the same nonce for each of the buttons respectively.</p>
<p>Why is this happening and how can I fix this issue?</p>
| [
{
"answer_id": 329967,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Default usage of <code>add_filter</code> looks like this:</p>\n\n<pre><code>add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )\n</code></pre>\n\n<p>As you can see, the default priority is 10 and by default only one param is passed.</p>\n\n<p>In your code you need your filter to get 2 params, because <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu_items</code></a> takes 2 params (<code>$items</code> and <code>$args</code>) and you need both of them in your filter. So you have to pass 2 as number of params, when you add your filter:</p>\n\n<pre><code>function add_new_item_to_menu( $items, $args ) {\n if ( 'header-menu' == $args->theme_location ) {\n $items .= '<li><a>Show whatever</a></li>';\n }\n return $items;\n}\nadd_filter( 'wp_nav_menu_items', 'add_new_item_to_menu', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 408024,
"author": "kiberchaka",
"author_id": 224395,
"author_profile": "https://wordpress.stackexchange.com/users/224395",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to Krzysiek Dróżdż's answer:</p>\n<p>If you show menu in Elementor widget, you can't check <code>$args->theme_location</code>\nSo, I check by <code>$args->menu == 'primary-menu'</code></p>\n<p>Also it will be helpful if you show a menu in more then one place, this way, you can show it everywhere where menu with <code>primary-menu</code> is displayed.</p>\n"
}
] | 2019/02/26 | [
"https://wordpress.stackexchange.com/questions/330008",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22588/"
] | I have run into an issue with nonces becoming invalid, and being unable to refresh to a new nonce. In my example I have a Facebook Connect button, and a Facebook Disconnect button, each with their own nonce.
Once either one of these button is pressed, an AJAX call is made, and the other button is sent through AJAX and displayed on the page instead.
For sake of the example, we're starting with the Facebook Connect button.
```
<button type="button" id="facebook-connect-button" class="facebook-button" data-nonce="<?php echo wp_create_nonce('ns-social-facebook-authentication'); ?>">
<?php _e('Connect to', NS_USER_SYSTEM_TEXTDOMAIN); ?> Facebook
</button>
```
After this button is pressed, an AJAX call is made, which verifies the data-nonce property like so:
```
check_ajax_referer( 'ns-social-facebook-authentication', '_nonce' );
```
No problems here, this works perfectly and my hooked function is working perfectly.
After this function has ran, it returns the Facebook Disconnect button that looks like this, and replaces the original button.
```
<button type="button" id="facebook-disconnect-button" class="facebook-disconnect-button" data-nonce="<?php echo wp_create_nonce('ns-social-facebook-disconnect'); ?>">
<?php _e('Disconnect from Facebook', NS_USER_SYSTEM_TEXTDOMAIN); ?>
</button>
```
After pressing this button, everything works fine like before, and this time, the Facebook Connect button is called again though AJAX. Now here's when the issue starts.
This new returned button contains the same nonce, which is now invalid and returns a 403 error, since it's already been used before.
**It looks like returning the button through AJAX does not refresh the nonce, even though it's already been used.**
I have also tried displaying both buttons on the page, and returning *just* a new nonce with AJAX every time a button is clicked, but still, it keeps returning the same nonce for each of the buttons respectively.
Why is this happening and how can I fix this issue? | Default usage of `add_filter` looks like this:
```
add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
```
As you can see, the default priority is 10 and by default only one param is passed.
In your code you need your filter to get 2 params, because [`wp_nav_menu_items`](https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/) takes 2 params (`$items` and `$args`) and you need both of them in your filter. So you have to pass 2 as number of params, when you add your filter:
```
function add_new_item_to_menu( $items, $args ) {
if ( 'header-menu' == $args->theme_location ) {
$items .= '<li><a>Show whatever</a></li>';
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'add_new_item_to_menu', 10, 2 );
``` |
330,026 | <p>I have created a page template called <code>concert.php</code> under <code>page-templates</code> directory with the following content: </p>
<pre class="lang-php prettyprint-override"><code><?php
/* Template Name: Concert*/
add_body_classes('page_concert'); /* Custom function that adds arguments to
body class using body_class filter */
get_header();
...
get_footer();
?>
</code></pre>
<p>The template shows up in the page editor as expected, however when loading a page that uses this template the default <code>page.php</code> template is used instead.</p>
<p>I've read in some threads that for a child theme to properly load page templates it is necessery to have a proper <code>index.php</code>, <code>header.php</code> and <code>page.php</code>, which I do have set in my theme folder. Also, some people have pointed out that the existence of a <code>front-page.php</code> leads to home page not loading its set template, however deleting the file from parent theme didn't do much for me.</p>
<p>The use of <code>Template: theme-name</code> inside the theme's <code>style.css</code> has said to be problematic, as well. But without that line of code the child theme becomes a standalone theme.</p>
<p>How can I make my custom page template work in a child theme? Has anyone been through the same situation?</p>
| [
{
"answer_id": 329967,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Default usage of <code>add_filter</code> looks like this:</p>\n\n<pre><code>add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )\n</code></pre>\n\n<p>As you can see, the default priority is 10 and by default only one param is passed.</p>\n\n<p>In your code you need your filter to get 2 params, because <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu_items</code></a> takes 2 params (<code>$items</code> and <code>$args</code>) and you need both of them in your filter. So you have to pass 2 as number of params, when you add your filter:</p>\n\n<pre><code>function add_new_item_to_menu( $items, $args ) {\n if ( 'header-menu' == $args->theme_location ) {\n $items .= '<li><a>Show whatever</a></li>';\n }\n return $items;\n}\nadd_filter( 'wp_nav_menu_items', 'add_new_item_to_menu', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 408024,
"author": "kiberchaka",
"author_id": 224395,
"author_profile": "https://wordpress.stackexchange.com/users/224395",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to Krzysiek Dróżdż's answer:</p>\n<p>If you show menu in Elementor widget, you can't check <code>$args->theme_location</code>\nSo, I check by <code>$args->menu == 'primary-menu'</code></p>\n<p>Also it will be helpful if you show a menu in more then one place, this way, you can show it everywhere where menu with <code>primary-menu</code> is displayed.</p>\n"
}
] | 2019/02/26 | [
"https://wordpress.stackexchange.com/questions/330026",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162086/"
] | I have created a page template called `concert.php` under `page-templates` directory with the following content:
```php
<?php
/* Template Name: Concert*/
add_body_classes('page_concert'); /* Custom function that adds arguments to
body class using body_class filter */
get_header();
...
get_footer();
?>
```
The template shows up in the page editor as expected, however when loading a page that uses this template the default `page.php` template is used instead.
I've read in some threads that for a child theme to properly load page templates it is necessery to have a proper `index.php`, `header.php` and `page.php`, which I do have set in my theme folder. Also, some people have pointed out that the existence of a `front-page.php` leads to home page not loading its set template, however deleting the file from parent theme didn't do much for me.
The use of `Template: theme-name` inside the theme's `style.css` has said to be problematic, as well. But without that line of code the child theme becomes a standalone theme.
How can I make my custom page template work in a child theme? Has anyone been through the same situation? | Default usage of `add_filter` looks like this:
```
add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
```
As you can see, the default priority is 10 and by default only one param is passed.
In your code you need your filter to get 2 params, because [`wp_nav_menu_items`](https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/) takes 2 params (`$items` and `$args`) and you need both of them in your filter. So you have to pass 2 as number of params, when you add your filter:
```
function add_new_item_to_menu( $items, $args ) {
if ( 'header-menu' == $args->theme_location ) {
$items .= '<li><a>Show whatever</a></li>';
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'add_new_item_to_menu', 10, 2 );
``` |
330,053 | <p>I have been following a <a href="http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress" rel="nofollow noreferrer">tutorial</a> on setting up a user taxonomy on Justin Tadlock's site. I got everything working but I wanted to adjust the taxonomy from a single radio selection to a multi checkbox selection.</p>
<pre><code>// If there are any competence terms, loop through them and display checkboxes.
if ( !empty( $terms ) ) {
foreach ( $terms as $term ) { ?>
<input type="checkbox" name="competence-<?php echo esc_attr( $term->slug ); ?>" id="competence-<?php echo esc_attr( $term->slug ); ?>" value="<?php echo esc_attr( $term->slug ); ?>" <?php checked( true, is_object_in_term( $user->ID, 'competence', $term ) ); ?> />
<label for="competence-<?php echo esc_attr( $term->slug ); ?>"><?php echo $term->name; ?></label> <br />
<?php }
}
</code></pre>
<p>I have adjusted the input type and the name value but I could not get the checkbox values to stay checked.</p>
<p>I did some simple testing and hard coded values into the save section</p>
<pre><code>$term = esc_attr( $_POST['competence-photographer'] );
$term = esc_attr( $_POST['competence-server-administrator'] );
</code></pre>
<p>And I was able to retain the values if the were checked or not so I created a foreach loop thinking it would loop through all the taxonomy terms but I must be doing something wrong because I cannot git it to save the values</p>
<pre><code>function save_user_competence_terms( $user_id ) {
$tax = get_taxonomy( 'competence' );
if ( !current_user_can( 'edit_user', $user_id ) && current_user_can( $tax->cap->assign_terms ) )
return false;
$terms = get_terms( 'competence', array( 'hide_empty' => false ) );
if ( !empty( $terms ) ) {
foreach ( $terms as $term ) {
$term = esc_attr( $_POST[$term->slug] );
wp_set_object_terms( $user_id, array( $term ), 'competence', false);
clean_object_term_cache( $user_id, 'competence' );
}
}
}
</code></pre>
<p>I believe the method that I am approaching this with is correct but I'm missing something that is not allowing the foreach to read the terms to check for the checked boxes. Any insight would be appreciated.</p>
| [
{
"answer_id": 330078,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>There are two errors in your code.</p>\n\n<p><strong>First one</strong> is the inconsistency in field names. Here’s your checkbox field:</p>\n\n<pre><code> <input type=\"checkbox\" name=\"competence-<?php echo esc_attr( $term->slug ); ?>\" id=\"competence-<?php echo esc_attr( $term->slug ); ?>\" value=\"<?php echo esc_attr( $term->slug ); ?>\" <?php checked( true, is_object_in_term( $user->ID, 'competence', $term ) ); ?> />\n</code></pre>\n\n<p>And here’s the part you’re checking it:</p>\n\n<p>foreach ( $terms as $term ) {\n $term = esc_attr( $_POST[$term->slug] );</p>\n\n<p>So your field has name <code>competence-<TERM_SLUG></code>, but you’re checking it using only <code><TERM_SLUG></code>.</p>\n\n<p>It should be:</p>\n\n<pre><code>foreach ( $terms as $term ) {\n $term = esc_attr( $_POST[ 'competence-' . $term->slug] );\n</code></pre>\n\n<p><strong>Second problem</strong> is the way you’re setting the terms for object:</p>\n\n<pre><code>wp_set_object_terms( $user_id, array( $term ), 'competence', false);\n</code></pre>\n\n<p>Take a look at <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\">wp_set_object_terms docs</a>. This is the default call for this function:</p>\n\n<pre><code> wp_set_object_terms( $object_id, $terms, $taxonomy, $append );\n</code></pre>\n\n<p>As you can see, the last param is <code>$append</code> and it tell if the term should be appended to the existing ones or should it overwrite existing ones. You pass false as the value for that param, so your foreach loop will overwrite existing terms - so only the last one will be saved.</p>\n\n<p>One way to fix it would be like this:</p>\n\n<pre><code>$terms = array();\nforeach ( $terms as $term ) {\n $term = esc_attr( $_POST[ 'competence-' . $term->slug] );\n $terms[] = $term;\n}\nwp_set_object_terms( $user_id, $terms, 'competence', false);\n</code></pre>\n"
},
{
"answer_id": 330153,
"author": "user3692010",
"author_id": 161266,
"author_profile": "https://wordpress.stackexchange.com/users/161266",
"pm_score": 0,
"selected": false,
"text": "<p>I gather that in your changes you are trying to show me that the content is saved in an array and to be very honest I do not understand what wp_set_object_terms or clean_object_term_cache do. The majority of this code came from another site and I am just adjust for the checkboxes and doing a poor job. Any additional help based on my about question and the changes applied to the response would be appreciated.</p>\n\n<pre><code>function save_user_competence_terms( $user_id ) {\n\n$tax = get_taxonomy( 'competence' );\n\nif ( !current_user_can( 'edit_user', $user_id ) && current_user_can( $tax->cap->assign_terms ) )\n return false;\n\n$terms = get_terms( 'competence', array( 'hide_empty' => false ) );\n\nif ( !empty( $terms ) ) {\n\n $terms = array();\n foreach ( $terms as $term ) {\n $term = esc_attr( $_POST['competence-' . $term->slug] );\n $terms[] = $term;\n }\n\n wp_set_object_terms( $user_id, $terms, 'competence', false);\n //clean_object_term_cache( $user_id, 'competence' );\n\n}\n</code></pre>\n\n<p>}</p>\n"
}
] | 2019/02/26 | [
"https://wordpress.stackexchange.com/questions/330053",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161266/"
] | I have been following a [tutorial](http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress) on setting up a user taxonomy on Justin Tadlock's site. I got everything working but I wanted to adjust the taxonomy from a single radio selection to a multi checkbox selection.
```
// If there are any competence terms, loop through them and display checkboxes.
if ( !empty( $terms ) ) {
foreach ( $terms as $term ) { ?>
<input type="checkbox" name="competence-<?php echo esc_attr( $term->slug ); ?>" id="competence-<?php echo esc_attr( $term->slug ); ?>" value="<?php echo esc_attr( $term->slug ); ?>" <?php checked( true, is_object_in_term( $user->ID, 'competence', $term ) ); ?> />
<label for="competence-<?php echo esc_attr( $term->slug ); ?>"><?php echo $term->name; ?></label> <br />
<?php }
}
```
I have adjusted the input type and the name value but I could not get the checkbox values to stay checked.
I did some simple testing and hard coded values into the save section
```
$term = esc_attr( $_POST['competence-photographer'] );
$term = esc_attr( $_POST['competence-server-administrator'] );
```
And I was able to retain the values if the were checked or not so I created a foreach loop thinking it would loop through all the taxonomy terms but I must be doing something wrong because I cannot git it to save the values
```
function save_user_competence_terms( $user_id ) {
$tax = get_taxonomy( 'competence' );
if ( !current_user_can( 'edit_user', $user_id ) && current_user_can( $tax->cap->assign_terms ) )
return false;
$terms = get_terms( 'competence', array( 'hide_empty' => false ) );
if ( !empty( $terms ) ) {
foreach ( $terms as $term ) {
$term = esc_attr( $_POST[$term->slug] );
wp_set_object_terms( $user_id, array( $term ), 'competence', false);
clean_object_term_cache( $user_id, 'competence' );
}
}
}
```
I believe the method that I am approaching this with is correct but I'm missing something that is not allowing the foreach to read the terms to check for the checked boxes. Any insight would be appreciated. | There are two errors in your code.
**First one** is the inconsistency in field names. Here’s your checkbox field:
```
<input type="checkbox" name="competence-<?php echo esc_attr( $term->slug ); ?>" id="competence-<?php echo esc_attr( $term->slug ); ?>" value="<?php echo esc_attr( $term->slug ); ?>" <?php checked( true, is_object_in_term( $user->ID, 'competence', $term ) ); ?> />
```
And here’s the part you’re checking it:
foreach ( $terms as $term ) {
$term = esc\_attr( $\_POST[$term->slug] );
So your field has name `competence-<TERM_SLUG>`, but you’re checking it using only `<TERM_SLUG>`.
It should be:
```
foreach ( $terms as $term ) {
$term = esc_attr( $_POST[ 'competence-' . $term->slug] );
```
**Second problem** is the way you’re setting the terms for object:
```
wp_set_object_terms( $user_id, array( $term ), 'competence', false);
```
Take a look at [wp\_set\_object\_terms docs](https://codex.wordpress.org/Function_Reference/wp_set_object_terms). This is the default call for this function:
```
wp_set_object_terms( $object_id, $terms, $taxonomy, $append );
```
As you can see, the last param is `$append` and it tell if the term should be appended to the existing ones or should it overwrite existing ones. You pass false as the value for that param, so your foreach loop will overwrite existing terms - so only the last one will be saved.
One way to fix it would be like this:
```
$terms = array();
foreach ( $terms as $term ) {
$term = esc_attr( $_POST[ 'competence-' . $term->slug] );
$terms[] = $term;
}
wp_set_object_terms( $user_id, $terms, 'competence', false);
``` |
330,088 | <p>If I click on a selection in the autocompleter of WordPress in codeMirror, the whole field is closed. To prevent this I want to add preventDefault to the click event.</p>
<pre><code>var cm = wp.codeEditor.initialize( options.field, editorSettings );
var editor = cm.codemirror;
jQuery('body').hover(function(e){
if(jQuery('ul.CodeMirror-hints')){
jQuery('ul.CodeMirror-hints').mousedown(function(eH){
eH.preventDefault();
});
}
});
var editorSettings = {
mode: 'css',
lineNumbers: true,
indentUnit: 2,
tabSize: 2,
autoRefresh:true,
autocorrect: true,
autocapitalize: true,
matchBrackets: true,
autoCloseBrackets: true,
lineWrapping: true,
lint: true,
gutters: [ 'CodeMirror-lint-markers' ]
}
</code></pre>
<p>Since ul.CodeMirror-hints is now stored in the body element and is only inserted when codeMirror hints makes a suggestion, I have to make an event on body.</p>
<pre><code>body => <ul class="CodeMirror-hints"...</ul>
</code></pre>
<p>Is there a better solution to add preventFefault() to the event click on ul.CodeMirror-hints?</p>
| [
{
"answer_id": 330078,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>There are two errors in your code.</p>\n\n<p><strong>First one</strong> is the inconsistency in field names. Here’s your checkbox field:</p>\n\n<pre><code> <input type=\"checkbox\" name=\"competence-<?php echo esc_attr( $term->slug ); ?>\" id=\"competence-<?php echo esc_attr( $term->slug ); ?>\" value=\"<?php echo esc_attr( $term->slug ); ?>\" <?php checked( true, is_object_in_term( $user->ID, 'competence', $term ) ); ?> />\n</code></pre>\n\n<p>And here’s the part you’re checking it:</p>\n\n<p>foreach ( $terms as $term ) {\n $term = esc_attr( $_POST[$term->slug] );</p>\n\n<p>So your field has name <code>competence-<TERM_SLUG></code>, but you’re checking it using only <code><TERM_SLUG></code>.</p>\n\n<p>It should be:</p>\n\n<pre><code>foreach ( $terms as $term ) {\n $term = esc_attr( $_POST[ 'competence-' . $term->slug] );\n</code></pre>\n\n<p><strong>Second problem</strong> is the way you’re setting the terms for object:</p>\n\n<pre><code>wp_set_object_terms( $user_id, array( $term ), 'competence', false);\n</code></pre>\n\n<p>Take a look at <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\">wp_set_object_terms docs</a>. This is the default call for this function:</p>\n\n<pre><code> wp_set_object_terms( $object_id, $terms, $taxonomy, $append );\n</code></pre>\n\n<p>As you can see, the last param is <code>$append</code> and it tell if the term should be appended to the existing ones or should it overwrite existing ones. You pass false as the value for that param, so your foreach loop will overwrite existing terms - so only the last one will be saved.</p>\n\n<p>One way to fix it would be like this:</p>\n\n<pre><code>$terms = array();\nforeach ( $terms as $term ) {\n $term = esc_attr( $_POST[ 'competence-' . $term->slug] );\n $terms[] = $term;\n}\nwp_set_object_terms( $user_id, $terms, 'competence', false);\n</code></pre>\n"
},
{
"answer_id": 330153,
"author": "user3692010",
"author_id": 161266,
"author_profile": "https://wordpress.stackexchange.com/users/161266",
"pm_score": 0,
"selected": false,
"text": "<p>I gather that in your changes you are trying to show me that the content is saved in an array and to be very honest I do not understand what wp_set_object_terms or clean_object_term_cache do. The majority of this code came from another site and I am just adjust for the checkboxes and doing a poor job. Any additional help based on my about question and the changes applied to the response would be appreciated.</p>\n\n<pre><code>function save_user_competence_terms( $user_id ) {\n\n$tax = get_taxonomy( 'competence' );\n\nif ( !current_user_can( 'edit_user', $user_id ) && current_user_can( $tax->cap->assign_terms ) )\n return false;\n\n$terms = get_terms( 'competence', array( 'hide_empty' => false ) );\n\nif ( !empty( $terms ) ) {\n\n $terms = array();\n foreach ( $terms as $term ) {\n $term = esc_attr( $_POST['competence-' . $term->slug] );\n $terms[] = $term;\n }\n\n wp_set_object_terms( $user_id, $terms, 'competence', false);\n //clean_object_term_cache( $user_id, 'competence' );\n\n}\n</code></pre>\n\n<p>}</p>\n"
}
] | 2019/02/27 | [
"https://wordpress.stackexchange.com/questions/330088",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133541/"
] | If I click on a selection in the autocompleter of WordPress in codeMirror, the whole field is closed. To prevent this I want to add preventDefault to the click event.
```
var cm = wp.codeEditor.initialize( options.field, editorSettings );
var editor = cm.codemirror;
jQuery('body').hover(function(e){
if(jQuery('ul.CodeMirror-hints')){
jQuery('ul.CodeMirror-hints').mousedown(function(eH){
eH.preventDefault();
});
}
});
var editorSettings = {
mode: 'css',
lineNumbers: true,
indentUnit: 2,
tabSize: 2,
autoRefresh:true,
autocorrect: true,
autocapitalize: true,
matchBrackets: true,
autoCloseBrackets: true,
lineWrapping: true,
lint: true,
gutters: [ 'CodeMirror-lint-markers' ]
}
```
Since ul.CodeMirror-hints is now stored in the body element and is only inserted when codeMirror hints makes a suggestion, I have to make an event on body.
```
body => <ul class="CodeMirror-hints"...</ul>
```
Is there a better solution to add preventFefault() to the event click on ul.CodeMirror-hints? | There are two errors in your code.
**First one** is the inconsistency in field names. Here’s your checkbox field:
```
<input type="checkbox" name="competence-<?php echo esc_attr( $term->slug ); ?>" id="competence-<?php echo esc_attr( $term->slug ); ?>" value="<?php echo esc_attr( $term->slug ); ?>" <?php checked( true, is_object_in_term( $user->ID, 'competence', $term ) ); ?> />
```
And here’s the part you’re checking it:
foreach ( $terms as $term ) {
$term = esc\_attr( $\_POST[$term->slug] );
So your field has name `competence-<TERM_SLUG>`, but you’re checking it using only `<TERM_SLUG>`.
It should be:
```
foreach ( $terms as $term ) {
$term = esc_attr( $_POST[ 'competence-' . $term->slug] );
```
**Second problem** is the way you’re setting the terms for object:
```
wp_set_object_terms( $user_id, array( $term ), 'competence', false);
```
Take a look at [wp\_set\_object\_terms docs](https://codex.wordpress.org/Function_Reference/wp_set_object_terms). This is the default call for this function:
```
wp_set_object_terms( $object_id, $terms, $taxonomy, $append );
```
As you can see, the last param is `$append` and it tell if the term should be appended to the existing ones or should it overwrite existing ones. You pass false as the value for that param, so your foreach loop will overwrite existing terms - so only the last one will be saved.
One way to fix it would be like this:
```
$terms = array();
foreach ( $terms as $term ) {
$term = esc_attr( $_POST[ 'competence-' . $term->slug] );
$terms[] = $term;
}
wp_set_object_terms( $user_id, $terms, 'competence', false);
``` |
330,091 | <p>I have this code for show count of posts by category.</p>
<p>If I visit category sports, show in header 34 articles. If I visit Nutrition Category show in header 12 articles.</p>
<p>But this code is wrong, anyone know why?</p>
<pre><code>add_shortcode('catcount', 'wp_get_cat_postcount');
function wp_get_cat_postcount($id) {
$cat= get_the_category();
echo '<span class="catcount">'. $cat[0]->count .' ARTÍCULOS</span>';
}
</code></pre>
| [
{
"answer_id": 330078,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>There are two errors in your code.</p>\n\n<p><strong>First one</strong> is the inconsistency in field names. Here’s your checkbox field:</p>\n\n<pre><code> <input type=\"checkbox\" name=\"competence-<?php echo esc_attr( $term->slug ); ?>\" id=\"competence-<?php echo esc_attr( $term->slug ); ?>\" value=\"<?php echo esc_attr( $term->slug ); ?>\" <?php checked( true, is_object_in_term( $user->ID, 'competence', $term ) ); ?> />\n</code></pre>\n\n<p>And here’s the part you’re checking it:</p>\n\n<p>foreach ( $terms as $term ) {\n $term = esc_attr( $_POST[$term->slug] );</p>\n\n<p>So your field has name <code>competence-<TERM_SLUG></code>, but you’re checking it using only <code><TERM_SLUG></code>.</p>\n\n<p>It should be:</p>\n\n<pre><code>foreach ( $terms as $term ) {\n $term = esc_attr( $_POST[ 'competence-' . $term->slug] );\n</code></pre>\n\n<p><strong>Second problem</strong> is the way you’re setting the terms for object:</p>\n\n<pre><code>wp_set_object_terms( $user_id, array( $term ), 'competence', false);\n</code></pre>\n\n<p>Take a look at <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\">wp_set_object_terms docs</a>. This is the default call for this function:</p>\n\n<pre><code> wp_set_object_terms( $object_id, $terms, $taxonomy, $append );\n</code></pre>\n\n<p>As you can see, the last param is <code>$append</code> and it tell if the term should be appended to the existing ones or should it overwrite existing ones. You pass false as the value for that param, so your foreach loop will overwrite existing terms - so only the last one will be saved.</p>\n\n<p>One way to fix it would be like this:</p>\n\n<pre><code>$terms = array();\nforeach ( $terms as $term ) {\n $term = esc_attr( $_POST[ 'competence-' . $term->slug] );\n $terms[] = $term;\n}\nwp_set_object_terms( $user_id, $terms, 'competence', false);\n</code></pre>\n"
},
{
"answer_id": 330153,
"author": "user3692010",
"author_id": 161266,
"author_profile": "https://wordpress.stackexchange.com/users/161266",
"pm_score": 0,
"selected": false,
"text": "<p>I gather that in your changes you are trying to show me that the content is saved in an array and to be very honest I do not understand what wp_set_object_terms or clean_object_term_cache do. The majority of this code came from another site and I am just adjust for the checkboxes and doing a poor job. Any additional help based on my about question and the changes applied to the response would be appreciated.</p>\n\n<pre><code>function save_user_competence_terms( $user_id ) {\n\n$tax = get_taxonomy( 'competence' );\n\nif ( !current_user_can( 'edit_user', $user_id ) && current_user_can( $tax->cap->assign_terms ) )\n return false;\n\n$terms = get_terms( 'competence', array( 'hide_empty' => false ) );\n\nif ( !empty( $terms ) ) {\n\n $terms = array();\n foreach ( $terms as $term ) {\n $term = esc_attr( $_POST['competence-' . $term->slug] );\n $terms[] = $term;\n }\n\n wp_set_object_terms( $user_id, $terms, 'competence', false);\n //clean_object_term_cache( $user_id, 'competence' );\n\n}\n</code></pre>\n\n<p>}</p>\n"
}
] | 2019/02/27 | [
"https://wordpress.stackexchange.com/questions/330091",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142081/"
] | I have this code for show count of posts by category.
If I visit category sports, show in header 34 articles. If I visit Nutrition Category show in header 12 articles.
But this code is wrong, anyone know why?
```
add_shortcode('catcount', 'wp_get_cat_postcount');
function wp_get_cat_postcount($id) {
$cat= get_the_category();
echo '<span class="catcount">'. $cat[0]->count .' ARTÍCULOS</span>';
}
``` | There are two errors in your code.
**First one** is the inconsistency in field names. Here’s your checkbox field:
```
<input type="checkbox" name="competence-<?php echo esc_attr( $term->slug ); ?>" id="competence-<?php echo esc_attr( $term->slug ); ?>" value="<?php echo esc_attr( $term->slug ); ?>" <?php checked( true, is_object_in_term( $user->ID, 'competence', $term ) ); ?> />
```
And here’s the part you’re checking it:
foreach ( $terms as $term ) {
$term = esc\_attr( $\_POST[$term->slug] );
So your field has name `competence-<TERM_SLUG>`, but you’re checking it using only `<TERM_SLUG>`.
It should be:
```
foreach ( $terms as $term ) {
$term = esc_attr( $_POST[ 'competence-' . $term->slug] );
```
**Second problem** is the way you’re setting the terms for object:
```
wp_set_object_terms( $user_id, array( $term ), 'competence', false);
```
Take a look at [wp\_set\_object\_terms docs](https://codex.wordpress.org/Function_Reference/wp_set_object_terms). This is the default call for this function:
```
wp_set_object_terms( $object_id, $terms, $taxonomy, $append );
```
As you can see, the last param is `$append` and it tell if the term should be appended to the existing ones or should it overwrite existing ones. You pass false as the value for that param, so your foreach loop will overwrite existing terms - so only the last one will be saved.
One way to fix it would be like this:
```
$terms = array();
foreach ( $terms as $term ) {
$term = esc_attr( $_POST[ 'competence-' . $term->slug] );
$terms[] = $term;
}
wp_set_object_terms( $user_id, $terms, 'competence', false);
``` |
330,104 | <p>I am learning Wordpress Development.</p>
<p>I am noticing whenever I encountered a problem I usually check the web for similar issue(s) for the solution.</p>
<p>Anyway, what I want to ask is, I've noticed, most of the time a solution of using ID is being used. I am thinking that isn't a general solution if that theme will be used by other people and on their Wordpress machine/environment, those IDs will change.</p>
<p>So my question is, why are people accepting ID as a final solution. I think that isn't the best dynamic solution since it will change. Whether it's Page ID, Post ID, every pre-made function that uses ID. </p>
<p>And, is there any better dynamic solution?</p>
<p>Or I am missing something here that ID won't change?</p>
<p>Thanks for the responses in advance. I would love to hear your thought(s) on this as it's been probably 2months this thing is bugging my mind.</p>
| [
{
"answer_id": 330108,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>Anyway, what I want to ask is, I've noticed, most of the time a solution of using ID is being used. I am thinking that isn't a general solution if that theme will be used by other people and on their Wordpress machine/environment, those IDs will change.</p>\n</blockquote>\n\n<p>ID's of various objects remains unchanged within a wordpress install. So it does not matter were a theme is used. </p>\n\n<blockquote>\n <p>Or I am missing something here that ID won't change? </p>\n</blockquote>\n\n<p>ID does not change because <strong>it is unique identifier for an object</strong> (post, page, taxonomy, term, user, menu, site etc) in database.</p>\n"
},
{
"answer_id": 330109,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You're absolutely correct that hard-coding specific IDs is a bad idea. IDs are very much subject to change, and normal activity through the UI can cause problems with any code expecting a specific ID, which makes them fragile.</p>\n\n<p>However, when you see solutions involving a specific ID, you need to keep in mind that the scope of many of these solutions, <em>especially</em> on this site, is limited to only the specific problem that the user is asking about.</p>\n\n<p>As a very simple example, a user might ask \"How do I print the title of a specific page?\", and the solution proposed will be something like:</p>\n\n<pre><code>echo get_the_title( 12 );\n</code></pre>\n\n<p>Where <code>12</code> is the ID of a specific page. </p>\n\n<p>Hard-coding the ID <code>12</code> is indeed a bad idea, however all this solution is intended to tell the user is that you can output a page title — <em>given its ID</em> — using the function <code>get_the_title()</code>. Where that ID comes from is a separate issue to the question that was asked.</p>\n\n<p>So, when implementing that solution, the user is probably going to need to come up with a way to allow that ID to be dynamic. Exactly how they do that is a separate issue to the problem the solution was regarding, and will depend on context. If they needed help with that on this site, then that would require a separate question (if it hasn't already been asked, which it almost certainly has).</p>\n\n<p>The user might want to get the ID from the current post, or maybe it will be a value saved in the database through the Customiser or Settings API, or possibly passed through the URL in the query string. There's lots of options, but the point is that how to <em>get</em> dynamic IDs is a separate problem to how to do something <em>with</em> an ID, and most solutions expect that if you need an ID to be dynamic, that you'd just combine the solution with any of those solutions for making an ID dynamic.</p>\n\n<p>That's another thing to keep in mind: The point of sites like this is to help your learn how to develop with WordPress. It's not to just do free work and give you code to put into your site or project. Any given answer is likely focused on specific questions being asked, and won't be a fully-formed drop-in solution. The question asker is going to need to use some development skills to properly integrate the solution into their project.</p>\n"
}
] | 2019/02/27 | [
"https://wordpress.stackexchange.com/questions/330104",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161005/"
] | I am learning Wordpress Development.
I am noticing whenever I encountered a problem I usually check the web for similar issue(s) for the solution.
Anyway, what I want to ask is, I've noticed, most of the time a solution of using ID is being used. I am thinking that isn't a general solution if that theme will be used by other people and on their Wordpress machine/environment, those IDs will change.
So my question is, why are people accepting ID as a final solution. I think that isn't the best dynamic solution since it will change. Whether it's Page ID, Post ID, every pre-made function that uses ID.
And, is there any better dynamic solution?
Or I am missing something here that ID won't change?
Thanks for the responses in advance. I would love to hear your thought(s) on this as it's been probably 2months this thing is bugging my mind. | You're absolutely correct that hard-coding specific IDs is a bad idea. IDs are very much subject to change, and normal activity through the UI can cause problems with any code expecting a specific ID, which makes them fragile.
However, when you see solutions involving a specific ID, you need to keep in mind that the scope of many of these solutions, *especially* on this site, is limited to only the specific problem that the user is asking about.
As a very simple example, a user might ask "How do I print the title of a specific page?", and the solution proposed will be something like:
```
echo get_the_title( 12 );
```
Where `12` is the ID of a specific page.
Hard-coding the ID `12` is indeed a bad idea, however all this solution is intended to tell the user is that you can output a page title — *given its ID* — using the function `get_the_title()`. Where that ID comes from is a separate issue to the question that was asked.
So, when implementing that solution, the user is probably going to need to come up with a way to allow that ID to be dynamic. Exactly how they do that is a separate issue to the problem the solution was regarding, and will depend on context. If they needed help with that on this site, then that would require a separate question (if it hasn't already been asked, which it almost certainly has).
The user might want to get the ID from the current post, or maybe it will be a value saved in the database through the Customiser or Settings API, or possibly passed through the URL in the query string. There's lots of options, but the point is that how to *get* dynamic IDs is a separate problem to how to do something *with* an ID, and most solutions expect that if you need an ID to be dynamic, that you'd just combine the solution with any of those solutions for making an ID dynamic.
That's another thing to keep in mind: The point of sites like this is to help your learn how to develop with WordPress. It's not to just do free work and give you code to put into your site or project. Any given answer is likely focused on specific questions being asked, and won't be a fully-formed drop-in solution. The question asker is going to need to use some development skills to properly integrate the solution into their project. |
330,118 | <p>I am using this function which is supposed to prevent wordpress from automatically logging me out. However, I am still being logged out every so often.</p>
<pre><code>function my_logged_in( $expirein ) {
return 31556926; // 1 year in seconds
}
add_filter( 'auth_cookie_expiration', 'my_logged_in' );
</code></pre>
<p>Is there another solution to this?</p>
| [
{
"answer_id": 330119,
"author": "Xavier C.",
"author_id": 81047,
"author_profile": "https://wordpress.stackexchange.com/users/81047",
"pm_score": 0,
"selected": false,
"text": "<p>Did you take a look at your session.gc_maxlifetime in your php settings?\nAlso, some operating systems like Debian or Ubuntu have a crontab that flushes sessions. <a href=\"https://stackoverflow.com/questions/3865303/debian-based-systems-session-killed-at-30-minutes-in-special-cron-how-to-overri\">More info here</a></p>\n"
},
{
"answer_id": 330120,
"author": "Gufran Hasan",
"author_id": 137328,
"author_profile": "https://wordpress.stackexchange.com/users/137328",
"pm_score": 2,
"selected": true,
"text": "<p>As we know by default WordPress keeps logged in for <code>48 Hours</code>. If we check \"Remember me\" while login then it will keep login for 14 Days.</p>\n\n<p>If you want to set the logout timeout you can use this code as:</p>\n\n<pre><code>function wpset_change_cookie_logout( $expiration, $user_id, $remember ) {\n if( $remember && user_can( $user_id, 'manage_options' ) ){\n $expiration = 31556926;\n }\n return $expiration;\n}\nadd_filter( 'auth_cookie_expiration','wpset_change_cookie_logout', 10, 3 );\n</code></pre>\n"
}
] | 2019/02/27 | [
"https://wordpress.stackexchange.com/questions/330118",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] | I am using this function which is supposed to prevent wordpress from automatically logging me out. However, I am still being logged out every so often.
```
function my_logged_in( $expirein ) {
return 31556926; // 1 year in seconds
}
add_filter( 'auth_cookie_expiration', 'my_logged_in' );
```
Is there another solution to this? | As we know by default WordPress keeps logged in for `48 Hours`. If we check "Remember me" while login then it will keep login for 14 Days.
If you want to set the logout timeout you can use this code as:
```
function wpset_change_cookie_logout( $expiration, $user_id, $remember ) {
if( $remember && user_can( $user_id, 'manage_options' ) ){
$expiration = 31556926;
}
return $expiration;
}
add_filter( 'auth_cookie_expiration','wpset_change_cookie_logout', 10, 3 );
``` |
330,135 | <p>I'm having issues to change the subject of the email sent out when password is changed.
I have managed to change the message by doing this:</p>
<pre><code>// Change Email to HTML function
function set_email_html_content_type() {
return 'text/html';
}
// Replace the default password change email
add_filter('password_change_email', 'change_password_mail_message', 10, 3);
function change_password_mail_message( $change_mail, $user, $userdata ) {
// Call Change Email to HTML function
add_filter( 'wp_mail_content_type', 'set_email_html_content_type' );
$message = "<p>Test HTML email</p>";
$change_mail[ 'message' ] = $message;
return $change_mail;
// Remove filter HTML content type
remove_filter( 'wp_mail_content_type', 'set_email_html_content_type' );
}
</code></pre>
<p>But how do I change the subject which is default as <code>[Sitename] Notice of Password Change</code></p>
<p>Thank you!</p>
| [
{
"answer_id": 330140,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>The <code>$change_mail</code> variable that you're filtering has a <code>subject</code> value that you can modify the same way you modified the message:</p>\n\n<pre><code>// Replace the default password change email\nadd_filter('password_change_email', 'change_password_mail_message', 10, 3);\nfunction change_password_mail_message( $change_mail, $user, $userdata ) {\n // Call Change Email to HTML function\n add_filter( 'wp_mail_content_type', 'set_email_html_content_type' );\n $message = \"<p>Test HTML email</p>\";\n\n $change_mail[ 'message' ] = $message;\n $change_mail[ 'subject' ] = 'My new email subject';\n\n return $change_mail;\n}\n</code></pre>\n\n<p>(I removed your call to <code>remove_filter()</code> because it wouldn't do anything. Nothing after <code>return</code> will run.)</p>\n"
},
{
"answer_id": 330142,
"author": "filipecsweb",
"author_id": 84657,
"author_profile": "https://wordpress.stackexchange.com/users/84657",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>/**\n * Hooked into `password_change_email` filter hook.\n *\n * @param array $pass_change_email {\n * Used to build wp_mail().\n *\n * @type string $to The intended recipients. Add emails in a comma separated string.\n * @type string $subject The subject of the email.\n * @type string $message The content of the email.\n * The following strings have a special meaning and will get replaced dynamically:\n * - ###USERNAME### The current user's username.\n * - ###ADMIN_EMAIL### The admin email in case this was unexpected.\n * - ###EMAIL### The user's email address.\n * - ###SITENAME### The name of the site.\n * - ###SITEURL### The URL to the site.\n * @type string $headers Headers. Add headers in a newline (\\r\\n) separated string.\n * }\n *\n * @param array $user The original user array.\n * @param array $userdata The updated user array.\n *\n * @return array $pass_change_email\n */\nfunction change_password_mail_message( $pass_change_email, $user, $userdata ) {\n $subject = \"Your new subject\";\n $message = \"<p>Test HTML email</p>\";\n $headers[] = 'Content-Type: text/html';\n\n $pass_change_email['subject'] = $subject;\n $pass_change_email['message'] = $message;\n $pass_change_email['headers'] = $headers;\n\n return $pass_change_email;\n}\n\n/**\n * Filters the contents of the email sent when the user's password is changed.\n *\n * @see change_password_mail_message()\n */\nadd_filter( 'password_change_email', 'change_password_mail_message', 10, 3 );\n</code></pre>\n"
}
] | 2019/02/27 | [
"https://wordpress.stackexchange.com/questions/330135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143279/"
] | I'm having issues to change the subject of the email sent out when password is changed.
I have managed to change the message by doing this:
```
// Change Email to HTML function
function set_email_html_content_type() {
return 'text/html';
}
// Replace the default password change email
add_filter('password_change_email', 'change_password_mail_message', 10, 3);
function change_password_mail_message( $change_mail, $user, $userdata ) {
// Call Change Email to HTML function
add_filter( 'wp_mail_content_type', 'set_email_html_content_type' );
$message = "<p>Test HTML email</p>";
$change_mail[ 'message' ] = $message;
return $change_mail;
// Remove filter HTML content type
remove_filter( 'wp_mail_content_type', 'set_email_html_content_type' );
}
```
But how do I change the subject which is default as `[Sitename] Notice of Password Change`
Thank you! | The `$change_mail` variable that you're filtering has a `subject` value that you can modify the same way you modified the message:
```
// Replace the default password change email
add_filter('password_change_email', 'change_password_mail_message', 10, 3);
function change_password_mail_message( $change_mail, $user, $userdata ) {
// Call Change Email to HTML function
add_filter( 'wp_mail_content_type', 'set_email_html_content_type' );
$message = "<p>Test HTML email</p>";
$change_mail[ 'message' ] = $message;
$change_mail[ 'subject' ] = 'My new email subject';
return $change_mail;
}
```
(I removed your call to `remove_filter()` because it wouldn't do anything. Nothing after `return` will run.) |
330,156 | <p>I want to display only 3 categories (Ex: horses, dogs, birds), names only and comma separated, in my Post, since one of them, two or all tree are marked in the post.</p>
<pre><code> <span><?php
if ( 'in_category('horses') ) {
echo "horses";
} ?></span><span><?php
if ( in_category('dogs') ) {
echo "dogs";
} ?></span><span><?php
if ( in_category('birds') ) {
echo "birds";
}
?></span>
</code></pre>
| [
{
"answer_id": 330165,
"author": "Fabrizio Mele",
"author_id": 40463,
"author_profile": "https://wordpress.stackexchange.com/users/40463",
"pm_score": 3,
"selected": true,
"text": "<p>It should be enough using a single <code><span></code> for all categories and add some logic.:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><span><?php\n$categories = ['horses','dogs','birds'];\n$string = \"\";\n\nforeach ($categories as $category){ //iterate over the categories to check\n if(has_category($category))\n $string .= $category.\", \"; //if in_category add to the output\n}\n\n$string = trim($string); //remove extra space from end\n$string = rtrim($string, ','); //remove extra comma from end\necho $string; //result example: <span>horses, dogs</span>\n?></span>\n</code></pre>\n"
},
{
"answer_id": 330166,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure, if I understand it correctly, because it doesn't sound like very common problem, but...</p>\n\n<p>If you want to check only for the existence of given three categories and output them separated with commas, then this is the code you can use (based on yours, but I've fixed the empty spans problem):</p>\n\n<pre><code><?php $cats_printed = 0; ?>\n<?php if ( in_category('horses') ) : $cats_printed++; ?><span>horses</span><?php endif; ?>\n<?php if ( in_category('dogs') ) : if ( $cats_printed++ ) echo ', '; ?><span>dogs</span><?php endif; ?>\n<?php if ( in_category('birds') ) : if ( $cats_printed++ ) echo ', '; ?><span>birds</span><?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 330171,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>get_the_terms( int|WP_Post $post, string $taxonomy )</code> . See Codex detail <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<pre><code>// put IDs of your selected three categories e.g. 15, 18, 20 here in this array\n$my_cats = array(15, 18, 20);\n\n$my_terms = get_the_terms( get_the_id(), 'category' );\n\nif ( ! empty( $my_terms ) ) {\n if ( ! is_wp_error( $my_terms ) ) {\n\n foreach( $my_terms as $term ) {\n\n if(in_array($term->term_id, $my_cats){\n // Display them as you want\n echo '<span>' . esc_html( $term->name ) . '</span>' ; \n\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 330827,
"author": "shea",
"author_id": 19726,
"author_profile": "https://wordpress.stackexchange.com/users/19726",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a simplified version of Fabrizo's code:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><span><?php\n $categories = [ 'horses', 'dogs', 'birds' ];\n echo implode( ', ', array_filter( $categories, 'has_category' ) );\n?></span>\n</code></pre>\n"
}
] | 2019/02/27 | [
"https://wordpress.stackexchange.com/questions/330156",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162089/"
] | I want to display only 3 categories (Ex: horses, dogs, birds), names only and comma separated, in my Post, since one of them, two or all tree are marked in the post.
```
<span><?php
if ( 'in_category('horses') ) {
echo "horses";
} ?></span><span><?php
if ( in_category('dogs') ) {
echo "dogs";
} ?></span><span><?php
if ( in_category('birds') ) {
echo "birds";
}
?></span>
``` | It should be enough using a single `<span>` for all categories and add some logic.:
```php
<span><?php
$categories = ['horses','dogs','birds'];
$string = "";
foreach ($categories as $category){ //iterate over the categories to check
if(has_category($category))
$string .= $category.", "; //if in_category add to the output
}
$string = trim($string); //remove extra space from end
$string = rtrim($string, ','); //remove extra comma from end
echo $string; //result example: <span>horses, dogs</span>
?></span>
``` |
330,173 | <p>I have a user that is receiving notification emails to their personal email address and we would like to have it be changed to more of public one that is used by the company. I have tried to change the Email Address field in the UI under Settings->General and when I do, the notifications are still being sent to the same email address with the Email Address field showing the new email address. </p>
<p>Do you have any ideas of how we can get this changed?</p>
| [
{
"answer_id": 330165,
"author": "Fabrizio Mele",
"author_id": 40463,
"author_profile": "https://wordpress.stackexchange.com/users/40463",
"pm_score": 3,
"selected": true,
"text": "<p>It should be enough using a single <code><span></code> for all categories and add some logic.:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><span><?php\n$categories = ['horses','dogs','birds'];\n$string = \"\";\n\nforeach ($categories as $category){ //iterate over the categories to check\n if(has_category($category))\n $string .= $category.\", \"; //if in_category add to the output\n}\n\n$string = trim($string); //remove extra space from end\n$string = rtrim($string, ','); //remove extra comma from end\necho $string; //result example: <span>horses, dogs</span>\n?></span>\n</code></pre>\n"
},
{
"answer_id": 330166,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure, if I understand it correctly, because it doesn't sound like very common problem, but...</p>\n\n<p>If you want to check only for the existence of given three categories and output them separated with commas, then this is the code you can use (based on yours, but I've fixed the empty spans problem):</p>\n\n<pre><code><?php $cats_printed = 0; ?>\n<?php if ( in_category('horses') ) : $cats_printed++; ?><span>horses</span><?php endif; ?>\n<?php if ( in_category('dogs') ) : if ( $cats_printed++ ) echo ', '; ?><span>dogs</span><?php endif; ?>\n<?php if ( in_category('birds') ) : if ( $cats_printed++ ) echo ', '; ?><span>birds</span><?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 330171,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>get_the_terms( int|WP_Post $post, string $taxonomy )</code> . See Codex detail <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<pre><code>// put IDs of your selected three categories e.g. 15, 18, 20 here in this array\n$my_cats = array(15, 18, 20);\n\n$my_terms = get_the_terms( get_the_id(), 'category' );\n\nif ( ! empty( $my_terms ) ) {\n if ( ! is_wp_error( $my_terms ) ) {\n\n foreach( $my_terms as $term ) {\n\n if(in_array($term->term_id, $my_cats){\n // Display them as you want\n echo '<span>' . esc_html( $term->name ) . '</span>' ; \n\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 330827,
"author": "shea",
"author_id": 19726,
"author_profile": "https://wordpress.stackexchange.com/users/19726",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a simplified version of Fabrizo's code:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><span><?php\n $categories = [ 'horses', 'dogs', 'birds' ];\n echo implode( ', ', array_filter( $categories, 'has_category' ) );\n?></span>\n</code></pre>\n"
}
] | 2019/02/27 | [
"https://wordpress.stackexchange.com/questions/330173",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162182/"
] | I have a user that is receiving notification emails to their personal email address and we would like to have it be changed to more of public one that is used by the company. I have tried to change the Email Address field in the UI under Settings->General and when I do, the notifications are still being sent to the same email address with the Email Address field showing the new email address.
Do you have any ideas of how we can get this changed? | It should be enough using a single `<span>` for all categories and add some logic.:
```php
<span><?php
$categories = ['horses','dogs','birds'];
$string = "";
foreach ($categories as $category){ //iterate over the categories to check
if(has_category($category))
$string .= $category.", "; //if in_category add to the output
}
$string = trim($string); //remove extra space from end
$string = rtrim($string, ','); //remove extra comma from end
echo $string; //result example: <span>horses, dogs</span>
?></span>
``` |
330,174 | <p>For some reason, some of the thumbnails of my media library are randomly becoming missing.</p>
<p>I've found out <code>_wp_attachment_metadata</code> isn't present in the database for those images with missing thumbnails. The files, however, are present on disk - both the original file and the "cropped" sizes.</p>
<hr>
<h2><strong><em>The purpose of this question is not to find out why this happens</em></strong>, I wrote a <a href="https://wordpress.stackexchange.com/q/330267/22510">different question</a> for that.</h2>
<p><strong>Again, in this context all I want is to fix the symptoms, while I haven't found out the cause yet.</strong></p>
<hr>
<p>My goal here is rebuilding the missing thumbnails.</p>
<p>What I've already tried:</p>
<ul>
<li><a href="https://wordpress.stackexchange.com/a/78542/22510">This WP SE answer</a>.</li>
<li>The <a href="https://wordpress.org/plugins/regenerate-thumbnails/" rel="nofollow noreferrer">Regenerate Thumbnails</a> plugin:
<ul>
<li>If I open the attachment details panel for that specific image and press the "Regenerate thumbnails" button, I get the following message: "ERROR: Unable to load the metadata for this attachment."</li>
<li>Running "Regenerate Thumbnails For All 4028 Attachments" works, but it takes a long time (1 hour for 4.000 pictures), even with the "Skip regenerating existing correctly sized thumbnails" option turned on.</li>
</ul></li>
<li>The <a href="https://wordpress.org/plugins/fix-my-posts/" rel="nofollow noreferrer">Fix My Posts</a> plugin: displays a meter which goes from 0% to 100% in a few seconds, but no difference.</li>
<li>The <a href="https://wordpress.org/plugins/wow-media-library-fix/" rel="nofollow noreferrer">Fix Media Library</a> plugin: even when selecting "Regenerate attachments metadata and thumbnails", it takes about 1 second per image. It also errors out on very large images, so for me it processes about 100 images and then stops.</li>
</ul>
<p>I've also come across the following snippet that is supposed to fix the missing metadata, but it isn't working as intended (see details after code)</p>
<pre><code>/**
* fix broken image metadata so that thumbs can be regenerated
*/
function fixImageMeta() {
global $wpdb;
$sql = "
select ID from {$wpdb->posts}
where post_type = 'attachment'
and post_mime_type like 'image/%'
";
$images = $wpdb->get_col($sql);
foreach ($images as $id) {
$meta = wp_get_attachment_metadata($id);
if (!$meta) {
$file = get_attached_file($id);
if (!empty($file)) {
$info = getimagesize($file);
$meta = array (
'width' => $info[0],
'height' => $info[1],
'hwstring_small' => "height='{$info[1]}' width='{$info[0]}'",
'file' => basename($file),
'sizes' => array(), // thumbnails etc.
'image_meta' => array(), // EXIF data
);
update_post_meta($id, '_wp_attachment_metadata', $meta);
}
}
}
}
</code></pre>
<p>(<a href="https://snippets.webaware.com.au/snippets/repair-wordpress-image-meta/" rel="nofollow noreferrer">source</a>)</p>
<p>The above code fixes the missing thumbnails on the media library, but with some inconsistencies:</p>
<p>Unserialized <code>_wp_attachment_metadata</code> for a previously correct image:</p>
<pre><code>Array
(
[width] => 700
[height] => 430
[file] => 2019/02/filename.png
[sizes] => Array
(
[thumbnail] => Array
(
[file] => filename-150x150.png
[width] => 150
[height] => 150
[mime-type] => image/png
)
[medium] => Array
(
[file] => filename-300x184.png
[width] => 300
[height] => 184
[mime-type] => image/png
)
)
[image_meta] => Array
(
[aperture] => 0
[credit] =>
[camera] =>
[caption] =>
[created_timestamp] => 0
[copyright] =>
[focal_length] => 0
[iso] => 0
[shutter_speed] => 0
[title] =>
[orientation] => 0
[keywords] => Array
(
)
)
)
</code></pre>
<p>Unserialized <code>_wp_attachment_metadata</code> for a "fixed" image:</p>
<pre><code>Array
(
[width] => 700
[height] => 430
[hwstring_small] => height='430' width='700'
[file] => filename.png
[sizes] => Array
(
)
[image_meta] => Array
(
)
)
</code></pre>
| [
{
"answer_id": 330175,
"author": "That Brazilian Guy",
"author_id": 22510,
"author_profile": "https://wordpress.stackexchange.com/users/22510",
"pm_score": 4,
"selected": true,
"text": "<p>Running the <a href=\"https://developer.wordpress.org/cli/commands/media/regenerate/\" rel=\"noreferrer\"><code>wp media regenerate</code> command</a> from WP-CLI with the <code>--only-missing</code> argument is quite fast (takes about 30 seconds for 4000 images) and rebuilds <code>_wp_attachment_metadata</code> correctly:</p>\n\n<p><code>wp media regenerate --only-missing</code></p>\n"
},
{
"answer_id": 330868,
"author": "WowPress.host",
"author_id": 135591,
"author_profile": "https://wordpress.stackexchange.com/users/135591",
"pm_score": -1,
"selected": false,
"text": "<p>The real problem with your website is \"thumbnails of my media library are randomly becoming missing\" and that's what you should try to fix at the first place.\nAnd you gave a hint right in your message why it happens: \"It also errors out on very large images\". It happens because webserver goes out of RAM when it tries to build thumbnails for your images. Potentially other images are converted on it's edge so they fail randomly.</p>\n\n<p>You need to upgrade your hosting plan or use/upload smaller images.</p>\n"
},
{
"answer_id": 384439,
"author": "err",
"author_id": 110247,
"author_profile": "https://wordpress.stackexchange.com/users/110247",
"pm_score": 1,
"selected": false,
"text": "<p>There are some non-working links above, so if somebody still struggling with this in 2021 (specially after moving WP), I found a working solution here:</p>\n<p><a href=\"https://barebones.dev/articles/rebuild-meta-data-for-media-items-that-are-missing-it/\" rel=\"nofollow noreferrer\">https://barebones.dev/articles/rebuild-meta-data-for-media-items-that-are-missing-it/</a></p>\n<p>Saving for the future the origin source, but I had to remove the meta query to work well. (took quite long time for a few hundred attachments, so consider to build in a counter and do some from-to limiter inside the foreach, as limiting the posts_per_page won't work well, only if you order by rand, and run lots of times, but it's not a good idea :))</p>\n<pre><code>require_once('wp-load.php');\nif ( ! function_exists( 'wp_crop_image' ) ) {\n include( ABSPATH . 'wp-admin/includes/image.php' );\n}\n\n$attachments = get_posts(\n[\n 'post_type' => 'attachment',\n 'posts_per_page' => -1,\n 'fields' => 'ids',\n 'meta_query' => [\n [\n 'key' => '_wp_attachment_metadata',\n 'compare' => 'NOT EXISTS'\n ]\n ]\n]\n);\n\nforeach($attachments as $attachment_id)\n{\n\n $url = get_attached_file($attachment_id);\n\n if (strpos($url, '.svg') !== false) continue;\n\n $attach_data = wp_generate_attachment_metadata($attachment_id, $url);\n wp_update_attachment_metadata( $attachment_id, $attach_data );\n\n}\n</code></pre>\n"
}
] | 2019/02/27 | [
"https://wordpress.stackexchange.com/questions/330174",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22510/"
] | For some reason, some of the thumbnails of my media library are randomly becoming missing.
I've found out `_wp_attachment_metadata` isn't present in the database for those images with missing thumbnails. The files, however, are present on disk - both the original file and the "cropped" sizes.
---
***The purpose of this question is not to find out why this happens***, I wrote a [different question](https://wordpress.stackexchange.com/q/330267/22510) for that.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
**Again, in this context all I want is to fix the symptoms, while I haven't found out the cause yet.**
---
My goal here is rebuilding the missing thumbnails.
What I've already tried:
* [This WP SE answer](https://wordpress.stackexchange.com/a/78542/22510).
* The [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) plugin:
+ If I open the attachment details panel for that specific image and press the "Regenerate thumbnails" button, I get the following message: "ERROR: Unable to load the metadata for this attachment."
+ Running "Regenerate Thumbnails For All 4028 Attachments" works, but it takes a long time (1 hour for 4.000 pictures), even with the "Skip regenerating existing correctly sized thumbnails" option turned on.
* The [Fix My Posts](https://wordpress.org/plugins/fix-my-posts/) plugin: displays a meter which goes from 0% to 100% in a few seconds, but no difference.
* The [Fix Media Library](https://wordpress.org/plugins/wow-media-library-fix/) plugin: even when selecting "Regenerate attachments metadata and thumbnails", it takes about 1 second per image. It also errors out on very large images, so for me it processes about 100 images and then stops.
I've also come across the following snippet that is supposed to fix the missing metadata, but it isn't working as intended (see details after code)
```
/**
* fix broken image metadata so that thumbs can be regenerated
*/
function fixImageMeta() {
global $wpdb;
$sql = "
select ID from {$wpdb->posts}
where post_type = 'attachment'
and post_mime_type like 'image/%'
";
$images = $wpdb->get_col($sql);
foreach ($images as $id) {
$meta = wp_get_attachment_metadata($id);
if (!$meta) {
$file = get_attached_file($id);
if (!empty($file)) {
$info = getimagesize($file);
$meta = array (
'width' => $info[0],
'height' => $info[1],
'hwstring_small' => "height='{$info[1]}' width='{$info[0]}'",
'file' => basename($file),
'sizes' => array(), // thumbnails etc.
'image_meta' => array(), // EXIF data
);
update_post_meta($id, '_wp_attachment_metadata', $meta);
}
}
}
}
```
([source](https://snippets.webaware.com.au/snippets/repair-wordpress-image-meta/))
The above code fixes the missing thumbnails on the media library, but with some inconsistencies:
Unserialized `_wp_attachment_metadata` for a previously correct image:
```
Array
(
[width] => 700
[height] => 430
[file] => 2019/02/filename.png
[sizes] => Array
(
[thumbnail] => Array
(
[file] => filename-150x150.png
[width] => 150
[height] => 150
[mime-type] => image/png
)
[medium] => Array
(
[file] => filename-300x184.png
[width] => 300
[height] => 184
[mime-type] => image/png
)
)
[image_meta] => Array
(
[aperture] => 0
[credit] =>
[camera] =>
[caption] =>
[created_timestamp] => 0
[copyright] =>
[focal_length] => 0
[iso] => 0
[shutter_speed] => 0
[title] =>
[orientation] => 0
[keywords] => Array
(
)
)
)
```
Unserialized `_wp_attachment_metadata` for a "fixed" image:
```
Array
(
[width] => 700
[height] => 430
[hwstring_small] => height='430' width='700'
[file] => filename.png
[sizes] => Array
(
)
[image_meta] => Array
(
)
)
``` | Running the [`wp media regenerate` command](https://developer.wordpress.org/cli/commands/media/regenerate/) from WP-CLI with the `--only-missing` argument is quite fast (takes about 30 seconds for 4000 images) and rebuilds `_wp_attachment_metadata` correctly:
`wp media regenerate --only-missing` |
330,248 | <p>I am not using WPML or Polylang, but multisite to create multiple languages. The code below is used to make a language switcher, but I want a second menu with the full language name for a different menu (i.e. EN should be English, FR - Français, DE - Deutsch). Wordpress has the native names stored (because when selecting a language you get a list with the native language name), but how can I access this to use? </p>
<pre><code>$languages = get_available_languages();
foreach ($languages as $item) {
$iso = substr($item, 0, 2);
echo '<li>'. $iso .'</li>';
}
</code></pre>
| [
{
"answer_id": 330231,
"author": "Rob",
"author_id": 94286,
"author_profile": "https://wordpress.stackexchange.com/users/94286",
"pm_score": 0,
"selected": false,
"text": "<p>That's perfectly normal, it's a security feature.</p>\n\n<p>My advice is that you do it via FTP and add the code to your footer file (usually footer.php) before the closing tag.</p>\n\n<p>Ideally, you want to be using a child-theme.</p>\n"
},
{
"answer_id": 330235,
"author": "Diana Moura",
"author_id": 160266,
"author_profile": "https://wordpress.stackexchange.com/users/160266",
"pm_score": 1,
"selected": false,
"text": "<p>You can use this Plugin and it will automatically insert the code for you on every page.</p>\n\n<p>Just download the plugin and add your code to the header box that the pugin provides.\nSuper easy to use and super lightweight. </p>\n\n<p>Plugin: Insert Headers and Footers</p>\n\n<p><a href=\"https://pt.wordpress.org/plugins/insert-headers-and-footers/\" rel=\"nofollow noreferrer\">https://pt.wordpress.org/plugins/insert-headers-and-footers/</a></p>\n"
},
{
"answer_id": 330280,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>You should be using the <code>wp_head</code> filter to add things to the or footer area. Similar to this:</p>\n\n<pre><code>add_action('wp_head', 'my_analytics');\nfunction my_analytics() {\n?>\n<!-- put your analytics script code here -->\n<?php \nreturn;\n}\n</code></pre>\n\n<p>This code is placed in your Child Theme's functions.php . (You <strong>always</strong> want to use a Child Theme, so any changes you make are not killed by a theme update. You <strong>never</strong> want to modify theme code directly.)</p>\n\n<p>But, be aware that client-side analytics will be blocked by many ad-blockers, so you may not get full 'participation' in your analytics.</p>\n\n<p>Best to implement a server-side analytics process. Many googles on how to do that.</p>\n\n<p>Alternately, there are many plugins that will properly insert your analytics code in your site.</p>\n"
}
] | 2019/02/28 | [
"https://wordpress.stackexchange.com/questions/330248",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87656/"
] | I am not using WPML or Polylang, but multisite to create multiple languages. The code below is used to make a language switcher, but I want a second menu with the full language name for a different menu (i.e. EN should be English, FR - Français, DE - Deutsch). Wordpress has the native names stored (because when selecting a language you get a list with the native language name), but how can I access this to use?
```
$languages = get_available_languages();
foreach ($languages as $item) {
$iso = substr($item, 0, 2);
echo '<li>'. $iso .'</li>';
}
``` | You can use this Plugin and it will automatically insert the code for you on every page.
Just download the plugin and add your code to the header box that the pugin provides.
Super easy to use and super lightweight.
Plugin: Insert Headers and Footers
<https://pt.wordpress.org/plugins/insert-headers-and-footers/> |
330,251 | <p>I´d like to automatically load three images inside all posts (via single.php), always in the same div (.acf_imgs-centro1). The idea is that the images are uploaded into uploads folder, with the same name as the post, and then they will be displayed inside the post. I can do it using the code bellow, but there is a problem... I have a static title (.imgs_h2) above the images divs, and I want it (the title) to load only since there are any image loaded. I can, for example, have the post and not yet have the image in the folder, so the title will be invisible. No Image, no title. Right now, the method i´m using seems incompatible with what I want to achiev. Any help is appreciated. </p>
<pre><code><div class="acf_imgs-centro1">
<h2 class="imgs_h2">Compartilhe nas redes sociais</h2>
<div class="img-neutra">
<img alt="Significado de <?php the_title(); ?>" src="http://teste.significadodosnomes.com.br/wp-content/uploads/nomes-unisex/<?php echo $post->post_name; ?>.jpg" onerror="this.style.opacity='0'" >
</div>
<div class="img-fem">
<img alt="Significado de <?php the_title(); ?>" src="http://teste.significadodosnomes.com.br/wp-content/uploads/nomes-femininos/<?php echo $post->post_name; ?>.jpg" onerror="this.style.opacity='0'"></div>
<div class="img-masc">
<img alt="Significado de <?php the_title(); ?>" src="http://teste.significadodosnomes.com.br/wp-content/uploads/nomes-masculinos/<?php echo $post->post_name; ?>.jpg" onerror="this.style.opacity='0'" ></div>
</div>
</code></pre>
<p><a href="https://i.stack.imgur.com/7epQB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7epQB.jpg" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/IqXNu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IqXNu.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 330231,
"author": "Rob",
"author_id": 94286,
"author_profile": "https://wordpress.stackexchange.com/users/94286",
"pm_score": 0,
"selected": false,
"text": "<p>That's perfectly normal, it's a security feature.</p>\n\n<p>My advice is that you do it via FTP and add the code to your footer file (usually footer.php) before the closing tag.</p>\n\n<p>Ideally, you want to be using a child-theme.</p>\n"
},
{
"answer_id": 330235,
"author": "Diana Moura",
"author_id": 160266,
"author_profile": "https://wordpress.stackexchange.com/users/160266",
"pm_score": 1,
"selected": false,
"text": "<p>You can use this Plugin and it will automatically insert the code for you on every page.</p>\n\n<p>Just download the plugin and add your code to the header box that the pugin provides.\nSuper easy to use and super lightweight. </p>\n\n<p>Plugin: Insert Headers and Footers</p>\n\n<p><a href=\"https://pt.wordpress.org/plugins/insert-headers-and-footers/\" rel=\"nofollow noreferrer\">https://pt.wordpress.org/plugins/insert-headers-and-footers/</a></p>\n"
},
{
"answer_id": 330280,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>You should be using the <code>wp_head</code> filter to add things to the or footer area. Similar to this:</p>\n\n<pre><code>add_action('wp_head', 'my_analytics');\nfunction my_analytics() {\n?>\n<!-- put your analytics script code here -->\n<?php \nreturn;\n}\n</code></pre>\n\n<p>This code is placed in your Child Theme's functions.php . (You <strong>always</strong> want to use a Child Theme, so any changes you make are not killed by a theme update. You <strong>never</strong> want to modify theme code directly.)</p>\n\n<p>But, be aware that client-side analytics will be blocked by many ad-blockers, so you may not get full 'participation' in your analytics.</p>\n\n<p>Best to implement a server-side analytics process. Many googles on how to do that.</p>\n\n<p>Alternately, there are many plugins that will properly insert your analytics code in your site.</p>\n"
}
] | 2019/02/28 | [
"https://wordpress.stackexchange.com/questions/330251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162089/"
] | I´d like to automatically load three images inside all posts (via single.php), always in the same div (.acf\_imgs-centro1). The idea is that the images are uploaded into uploads folder, with the same name as the post, and then they will be displayed inside the post. I can do it using the code bellow, but there is a problem... I have a static title (.imgs\_h2) above the images divs, and I want it (the title) to load only since there are any image loaded. I can, for example, have the post and not yet have the image in the folder, so the title will be invisible. No Image, no title. Right now, the method i´m using seems incompatible with what I want to achiev. Any help is appreciated.
```
<div class="acf_imgs-centro1">
<h2 class="imgs_h2">Compartilhe nas redes sociais</h2>
<div class="img-neutra">
<img alt="Significado de <?php the_title(); ?>" src="http://teste.significadodosnomes.com.br/wp-content/uploads/nomes-unisex/<?php echo $post->post_name; ?>.jpg" onerror="this.style.opacity='0'" >
</div>
<div class="img-fem">
<img alt="Significado de <?php the_title(); ?>" src="http://teste.significadodosnomes.com.br/wp-content/uploads/nomes-femininos/<?php echo $post->post_name; ?>.jpg" onerror="this.style.opacity='0'"></div>
<div class="img-masc">
<img alt="Significado de <?php the_title(); ?>" src="http://teste.significadodosnomes.com.br/wp-content/uploads/nomes-masculinos/<?php echo $post->post_name; ?>.jpg" onerror="this.style.opacity='0'" ></div>
</div>
```
[](https://i.stack.imgur.com/7epQB.jpg)
[](https://i.stack.imgur.com/IqXNu.jpg) | You can use this Plugin and it will automatically insert the code for you on every page.
Just download the plugin and add your code to the header box that the pugin provides.
Super easy to use and super lightweight.
Plugin: Insert Headers and Footers
<https://pt.wordpress.org/plugins/insert-headers-and-footers/> |
330,255 | <p>I'm making a website with the Primer theme, and it includes a big bar with the title in huge letters across every page. I prefer the titles be in the body of the post, so I want to delete the title bar altogether.</p>
<p>However, inserts that have been suggested on here like </p>
<pre><code>.page_header {
display: none !important;
}
</code></pre>
<p>don't work at all when I input them into "Additional CSS". What am I doing wrong? Keep in mind, when you answer, that I'm a complete novice.</p>
| [
{
"answer_id": 330231,
"author": "Rob",
"author_id": 94286,
"author_profile": "https://wordpress.stackexchange.com/users/94286",
"pm_score": 0,
"selected": false,
"text": "<p>That's perfectly normal, it's a security feature.</p>\n\n<p>My advice is that you do it via FTP and add the code to your footer file (usually footer.php) before the closing tag.</p>\n\n<p>Ideally, you want to be using a child-theme.</p>\n"
},
{
"answer_id": 330235,
"author": "Diana Moura",
"author_id": 160266,
"author_profile": "https://wordpress.stackexchange.com/users/160266",
"pm_score": 1,
"selected": false,
"text": "<p>You can use this Plugin and it will automatically insert the code for you on every page.</p>\n\n<p>Just download the plugin and add your code to the header box that the pugin provides.\nSuper easy to use and super lightweight. </p>\n\n<p>Plugin: Insert Headers and Footers</p>\n\n<p><a href=\"https://pt.wordpress.org/plugins/insert-headers-and-footers/\" rel=\"nofollow noreferrer\">https://pt.wordpress.org/plugins/insert-headers-and-footers/</a></p>\n"
},
{
"answer_id": 330280,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>You should be using the <code>wp_head</code> filter to add things to the or footer area. Similar to this:</p>\n\n<pre><code>add_action('wp_head', 'my_analytics');\nfunction my_analytics() {\n?>\n<!-- put your analytics script code here -->\n<?php \nreturn;\n}\n</code></pre>\n\n<p>This code is placed in your Child Theme's functions.php . (You <strong>always</strong> want to use a Child Theme, so any changes you make are not killed by a theme update. You <strong>never</strong> want to modify theme code directly.)</p>\n\n<p>But, be aware that client-side analytics will be blocked by many ad-blockers, so you may not get full 'participation' in your analytics.</p>\n\n<p>Best to implement a server-side analytics process. Many googles on how to do that.</p>\n\n<p>Alternately, there are many plugins that will properly insert your analytics code in your site.</p>\n"
}
] | 2019/02/28 | [
"https://wordpress.stackexchange.com/questions/330255",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162208/"
] | I'm making a website with the Primer theme, and it includes a big bar with the title in huge letters across every page. I prefer the titles be in the body of the post, so I want to delete the title bar altogether.
However, inserts that have been suggested on here like
```
.page_header {
display: none !important;
}
```
don't work at all when I input them into "Additional CSS". What am I doing wrong? Keep in mind, when you answer, that I'm a complete novice. | You can use this Plugin and it will automatically insert the code for you on every page.
Just download the plugin and add your code to the header box that the pugin provides.
Super easy to use and super lightweight.
Plugin: Insert Headers and Footers
<https://pt.wordpress.org/plugins/insert-headers-and-footers/> |
330,346 | <p>I have a function which adds a <code>posts_join</code> and a <code>posts_where</code> to searches in <code>WP_Query</code>. It works fine on a normal, php rendered search page. However i'm also using it for a ajax product search and the additional <code>posts_join</code> and a <code>posts_where</code> don't seem to apply.</p>
<p>Here's the join and where:</p>
<pre><code>function search_by_meta_join($join) {
global $wpdb;
if (is_search()) {
$join .= " LEFT JOIN {$wpdb->postmeta} pm_ean ON {$wpdb->posts}.ID = pm_ean.post_id AND (pm_ean.meta_key = 'ean') ";
$join .= " LEFT JOIN {$wpdb->postmeta} pm_code ON {$wpdb->posts}.ID = pm_code.post_id AND (pm_code.meta_key = 'product_code') ";
}
return $join;
}
add_filter('posts_join', 'search_by_meta_join');
function search_by_meta_where($where) {
global $wpdb;
if (is_search()) {
$where = preg_replace(
"/\(\s*{$wpdb->posts}.post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"({$wpdb->posts}.post_title LIKE $1) OR (pm_ean.meta_value LIKE $1) OR (pm_code.meta_value LIKE $1) ", $where
);
}
return $where;
}
add_filter('posts_where', 'search_by_meta_where');
</code></pre>
<p>And here's my ajax function:</p>
<pre><code> $args = array(
'posts_per_page' => 12,
'post_type' => 'product',
// 'offset' => filter_var($_GET['offset'], FILTER_SANITIZE_NUMBER_INT),
// 'post_status' => 'publish',
// 'order' => 'ASC',
// 'orderby' => 'title',
);
// Search query
if (isset($_GET['searchQuery']) && $_GET['searchQuery'] != '') {
$args['s'] = filter_var($_GET['searchQuery'], FILTER_SANITIZE_STRING);
}
// Category filter
// if (isset($_GET['category']) && $_GET['category'] !== 0) {
// $args['tax_query'][] = [
// 'taxonomy' => 'product-category',
// 'field' => 'term_id',
// 'terms' => filter_var($_GET['category'], FILTER_SANITIZE_NUMBER_INT),
// ];
// }
$loop = new WP_Query($args);
$products = array();
</code></pre>
<p>As I say it works on a normal search page like so:</p>
<pre><code>global $query_string;
wp_parse_str($query_string, $search_query);
$search = new WP_Query($search_query);
</code></pre>
<p>Am I missing something for the ajax function to use it?</p>
| [
{
"answer_id": 330348,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": -1,
"selected": false,
"text": "<p>If you use ajax, is_search() return false. You have to define a global variable or a constant for use in your filters.</p>\n"
},
{
"answer_id": 330349,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p><code>is_search()</code> is only true if the <em>main</em> query is for the search results. When you create your own query with <code>new WP_Query</code>, you're not using the main query. Additionally, AJAX requests do not even have a main query, so functions like <code>is_search()</code>, <code>is_archive()</code> etc. do not work.</p>\n\n<p>If you want to check if a specific query is a search, you should use the <code>is_search()</code> method of the query, like this:</p>\n\n<pre><code>$query->is_search();\n</code></pre>\n\n<p>The <code>posts_join</code> and <code>posts_where</code> filters are applied to all queries, but the callbacks to those filters receive the current query object as an argument, and you can use this to check for any search queries so that you can apply your filter:</p>\n\n<pre><code>function search_by_meta_join( $join, $query ) { // <-- Note the additional argument.\n global $wpdb;\n\n if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.\n }\n\n return $join;\n}\nadd_filter('posts_join', 'search_by_meta_join', 10, 2 ); // <-- Note the '2' which indicates we're accepting 2 arguments.\n\nfunction search_by_meta_where( $where, $query ) { // <-- Note the additional argument.\n global $wpdb;\n\n if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.\n\n }\n\n return $where;\n}\nadd_filter( 'posts_where', 'search_by_meta_where', 10, 2 );// <-- Note the '2' which indicates we're accepting 2 arguments.\n</code></pre>\n\n<p>The same principle applies whenever you're filtering <code>pre_get_posts</code> as well. You should always use the query object that's passed to the filter to check these things, otherwise your changes will apply to <em>all</em> queries on the search page, including menus, widgets, and secondary queries, not just the specific search query.</p>\n"
}
] | 2019/03/01 | [
"https://wordpress.stackexchange.com/questions/330346",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146026/"
] | I have a function which adds a `posts_join` and a `posts_where` to searches in `WP_Query`. It works fine on a normal, php rendered search page. However i'm also using it for a ajax product search and the additional `posts_join` and a `posts_where` don't seem to apply.
Here's the join and where:
```
function search_by_meta_join($join) {
global $wpdb;
if (is_search()) {
$join .= " LEFT JOIN {$wpdb->postmeta} pm_ean ON {$wpdb->posts}.ID = pm_ean.post_id AND (pm_ean.meta_key = 'ean') ";
$join .= " LEFT JOIN {$wpdb->postmeta} pm_code ON {$wpdb->posts}.ID = pm_code.post_id AND (pm_code.meta_key = 'product_code') ";
}
return $join;
}
add_filter('posts_join', 'search_by_meta_join');
function search_by_meta_where($where) {
global $wpdb;
if (is_search()) {
$where = preg_replace(
"/\(\s*{$wpdb->posts}.post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"({$wpdb->posts}.post_title LIKE $1) OR (pm_ean.meta_value LIKE $1) OR (pm_code.meta_value LIKE $1) ", $where
);
}
return $where;
}
add_filter('posts_where', 'search_by_meta_where');
```
And here's my ajax function:
```
$args = array(
'posts_per_page' => 12,
'post_type' => 'product',
// 'offset' => filter_var($_GET['offset'], FILTER_SANITIZE_NUMBER_INT),
// 'post_status' => 'publish',
// 'order' => 'ASC',
// 'orderby' => 'title',
);
// Search query
if (isset($_GET['searchQuery']) && $_GET['searchQuery'] != '') {
$args['s'] = filter_var($_GET['searchQuery'], FILTER_SANITIZE_STRING);
}
// Category filter
// if (isset($_GET['category']) && $_GET['category'] !== 0) {
// $args['tax_query'][] = [
// 'taxonomy' => 'product-category',
// 'field' => 'term_id',
// 'terms' => filter_var($_GET['category'], FILTER_SANITIZE_NUMBER_INT),
// ];
// }
$loop = new WP_Query($args);
$products = array();
```
As I say it works on a normal search page like so:
```
global $query_string;
wp_parse_str($query_string, $search_query);
$search = new WP_Query($search_query);
```
Am I missing something for the ajax function to use it? | `is_search()` is only true if the *main* query is for the search results. When you create your own query with `new WP_Query`, you're not using the main query. Additionally, AJAX requests do not even have a main query, so functions like `is_search()`, `is_archive()` etc. do not work.
If you want to check if a specific query is a search, you should use the `is_search()` method of the query, like this:
```
$query->is_search();
```
The `posts_join` and `posts_where` filters are applied to all queries, but the callbacks to those filters receive the current query object as an argument, and you can use this to check for any search queries so that you can apply your filter:
```
function search_by_meta_join( $join, $query ) { // <-- Note the additional argument.
global $wpdb;
if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.
}
return $join;
}
add_filter('posts_join', 'search_by_meta_join', 10, 2 ); // <-- Note the '2' which indicates we're accepting 2 arguments.
function search_by_meta_where( $where, $query ) { // <-- Note the additional argument.
global $wpdb;
if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.
}
return $where;
}
add_filter( 'posts_where', 'search_by_meta_where', 10, 2 );// <-- Note the '2' which indicates we're accepting 2 arguments.
```
The same principle applies whenever you're filtering `pre_get_posts` as well. You should always use the query object that's passed to the filter to check these things, otherwise your changes will apply to *all* queries on the search page, including menus, widgets, and secondary queries, not just the specific search query. |
330,356 | <p>I'm trying to understand how datas are being handled when saving to the database in the <strong><em>wpdb</em></strong> class. I have searched for where HTML string datas are handled and found a method in the <code>$this->query()</code> method in the wpdb class where the query string is being stripped and thought it could be there. It's on <a href="https://core.trac.wordpress.org/browser/tags/5.0.3/src/wp-includes/wp-db.php#L1798" rel="nofollow noreferrer">line 1798</a>. The <code>$query</code> string variable is stripped:</p>
<pre><code>$stripped_query = $this->strip_invalid_text_from_query( $query );
</code></pre>
<p>But then I don't understand. I <strong>just can't</strong> find the stripped variable <code>$stripped_query</code> to be used in a query after that. The method is just returning false if it's not exactly like the original?:</p>
<pre><code>if ( $stripped_query !== $query ) {
$this->insert_id = 0;
return false;
}
</code></pre>
<p>Why? Maybe I have misunderstood what <code>strip_invalid_text_from_query()</code> is doing?</p>
<p>Anyway.. As I said, I just wanna find the method that fixes HTML to a database safe string. So that not for example line-breaks destroys the query or so. Does anyone know where that is?</p>
| [
{
"answer_id": 330348,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": -1,
"selected": false,
"text": "<p>If you use ajax, is_search() return false. You have to define a global variable or a constant for use in your filters.</p>\n"
},
{
"answer_id": 330349,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p><code>is_search()</code> is only true if the <em>main</em> query is for the search results. When you create your own query with <code>new WP_Query</code>, you're not using the main query. Additionally, AJAX requests do not even have a main query, so functions like <code>is_search()</code>, <code>is_archive()</code> etc. do not work.</p>\n\n<p>If you want to check if a specific query is a search, you should use the <code>is_search()</code> method of the query, like this:</p>\n\n<pre><code>$query->is_search();\n</code></pre>\n\n<p>The <code>posts_join</code> and <code>posts_where</code> filters are applied to all queries, but the callbacks to those filters receive the current query object as an argument, and you can use this to check for any search queries so that you can apply your filter:</p>\n\n<pre><code>function search_by_meta_join( $join, $query ) { // <-- Note the additional argument.\n global $wpdb;\n\n if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.\n }\n\n return $join;\n}\nadd_filter('posts_join', 'search_by_meta_join', 10, 2 ); // <-- Note the '2' which indicates we're accepting 2 arguments.\n\nfunction search_by_meta_where( $where, $query ) { // <-- Note the additional argument.\n global $wpdb;\n\n if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.\n\n }\n\n return $where;\n}\nadd_filter( 'posts_where', 'search_by_meta_where', 10, 2 );// <-- Note the '2' which indicates we're accepting 2 arguments.\n</code></pre>\n\n<p>The same principle applies whenever you're filtering <code>pre_get_posts</code> as well. You should always use the query object that's passed to the filter to check these things, otherwise your changes will apply to <em>all</em> queries on the search page, including menus, widgets, and secondary queries, not just the specific search query.</p>\n"
}
] | 2019/03/01 | [
"https://wordpress.stackexchange.com/questions/330356",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3216/"
] | I'm trying to understand how datas are being handled when saving to the database in the ***wpdb*** class. I have searched for where HTML string datas are handled and found a method in the `$this->query()` method in the wpdb class where the query string is being stripped and thought it could be there. It's on [line 1798](https://core.trac.wordpress.org/browser/tags/5.0.3/src/wp-includes/wp-db.php#L1798). The `$query` string variable is stripped:
```
$stripped_query = $this->strip_invalid_text_from_query( $query );
```
But then I don't understand. I **just can't** find the stripped variable `$stripped_query` to be used in a query after that. The method is just returning false if it's not exactly like the original?:
```
if ( $stripped_query !== $query ) {
$this->insert_id = 0;
return false;
}
```
Why? Maybe I have misunderstood what `strip_invalid_text_from_query()` is doing?
Anyway.. As I said, I just wanna find the method that fixes HTML to a database safe string. So that not for example line-breaks destroys the query or so. Does anyone know where that is? | `is_search()` is only true if the *main* query is for the search results. When you create your own query with `new WP_Query`, you're not using the main query. Additionally, AJAX requests do not even have a main query, so functions like `is_search()`, `is_archive()` etc. do not work.
If you want to check if a specific query is a search, you should use the `is_search()` method of the query, like this:
```
$query->is_search();
```
The `posts_join` and `posts_where` filters are applied to all queries, but the callbacks to those filters receive the current query object as an argument, and you can use this to check for any search queries so that you can apply your filter:
```
function search_by_meta_join( $join, $query ) { // <-- Note the additional argument.
global $wpdb;
if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.
}
return $join;
}
add_filter('posts_join', 'search_by_meta_join', 10, 2 ); // <-- Note the '2' which indicates we're accepting 2 arguments.
function search_by_meta_where( $where, $query ) { // <-- Note the additional argument.
global $wpdb;
if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.
}
return $where;
}
add_filter( 'posts_where', 'search_by_meta_where', 10, 2 );// <-- Note the '2' which indicates we're accepting 2 arguments.
```
The same principle applies whenever you're filtering `pre_get_posts` as well. You should always use the query object that's passed to the filter to check these things, otherwise your changes will apply to *all* queries on the search page, including menus, widgets, and secondary queries, not just the specific search query. |
330,362 | <p>I have a custom table in the WP database called wp_products. It has columns titled ID, SKU, Details and Page. I'm trying to search this table via the default search box, so I've replaced my search.php file with the code below. This isn't working and I don't know enough PHP to fix it. Can anyone help me out with this?</p>
<pre><code><?php
/**
* Author:
* Created on:
*
* @package Neve
*/
function search_it() {
if ( is_search() && isset( $_GET['s'] ) ) {
global $wpdb;
$address_table = $wpdb->prefix . "wp_products";
$search = $_GET['s'];
$search = "%{$search}%";
$where = $wpdb->prepare( 'WHERE SKU LIKE %s OR Details LIKE %s OR Page LIKE %s', $search, $search, $search );
$results = $wpdb->get_results( "SELECT * FROM {$address_table} {$where}" );
return $product;
}
return array();
}
$container_class = apply_filters( 'neve_container_class_filter', 'container', 'blog-archive' );
get_header();
$cities = search_it();
if ( ! empty( $cities ) ) {
echo '<h1>Catalogue Search Results:</h1>';
foreach( $cities AS $city ) {
echo "<table width='100%' align='center' border='3px solid grey'>";
echo "<tr>";
echo "<th style='background: #B9C9FE;'>Part Number</th>";
echo "<th style='background: #B9C9FE;'>Description</th>";
echo "<th style='background: #B9C9FE;'>Page</th>";
echo "</tr>";
echo "<tbody>";
for ($i=$start;$i < $end ;++$i ) {
$results = $results[$i];
echo "<tr>";
echo "<td>$city->SKU</td>";
echo "<td>$city->description</td>";
echo "<td>$city->Page</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
}
get_search_form();
?>
<?php
get_footer();
</code></pre>
<p>Here's the updated code:</p>
<pre><code><?php
/*
Template Name: Search Page
*/
function search_it() {
$search = filter_input( INPUT_GET, 's', FILTER_SANITIZE_STRING );
if ( ! is_search() || empty( $search ) ) {
return array();
}
global $wpdb;
$address_table = $wpdb->prefix . 'products';
$search = $wpdb->esc_like( $search );
$search = "%{$search}%";
$query = "SELECT * FROM {$wpdb->prefix}products WHERE SKU LIKE %s OR Details LIKE %s OR Page Like %s";
$query = $wpdb->prepare( $query, $search, $search, $search );
return $wpdb->get_results();
}
get_header();
$cities = search_it();
if ( ! empty( $cities ) ) {
echo '<h1>Catalogue Search Results:</h1>';
echo "<table width='100%' align='center' border='3px solid grey'>";
echo "<tr>";
echo "<th style='background: #B9C9FE;'>Part Number</th>";
echo "<th style='background: #B9C9FE;'>Description</th>";
echo "<th style='background: #B9C9FE;'>Page</th>";
echo "</tr>";
echo "<tbody>";
foreach( $cities AS $city ) {
echo "<tr>";
echo "<td>{$city->SKU}</td>";
echo "<td>{$city->Details}</td>";
echo "<td>{$city->Page}</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
} else {
echo "<h1 class='page-title'>";
printf( __( 'There are no search results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' );
echo ".</h1>";
$query;
}
get_search_form();
get_footer();
</code></pre>
<p>Here's the print_r( $wpdb->prepare( $query, $search, $search, $search ) ); die; output:</p>
<pre><code>SELECT * FROM wp_products WHERE SKU LIKE '{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}GASKET{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}' OR Details LIKE '{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}GASKET{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}' OR Page Like '{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}GASKET{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}'
</code></pre>
<p>The above is the output I get when I run this query:</p>
<pre><code>$query = "SELECT * FROM {$wpdb->prefix}products WHERE SKU LIKE %s OR Details LIKE %s OR Page Like %s";
</code></pre>
| [
{
"answer_id": 330348,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": -1,
"selected": false,
"text": "<p>If you use ajax, is_search() return false. You have to define a global variable or a constant for use in your filters.</p>\n"
},
{
"answer_id": 330349,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p><code>is_search()</code> is only true if the <em>main</em> query is for the search results. When you create your own query with <code>new WP_Query</code>, you're not using the main query. Additionally, AJAX requests do not even have a main query, so functions like <code>is_search()</code>, <code>is_archive()</code> etc. do not work.</p>\n\n<p>If you want to check if a specific query is a search, you should use the <code>is_search()</code> method of the query, like this:</p>\n\n<pre><code>$query->is_search();\n</code></pre>\n\n<p>The <code>posts_join</code> and <code>posts_where</code> filters are applied to all queries, but the callbacks to those filters receive the current query object as an argument, and you can use this to check for any search queries so that you can apply your filter:</p>\n\n<pre><code>function search_by_meta_join( $join, $query ) { // <-- Note the additional argument.\n global $wpdb;\n\n if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.\n }\n\n return $join;\n}\nadd_filter('posts_join', 'search_by_meta_join', 10, 2 ); // <-- Note the '2' which indicates we're accepting 2 arguments.\n\nfunction search_by_meta_where( $where, $query ) { // <-- Note the additional argument.\n global $wpdb;\n\n if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.\n\n }\n\n return $where;\n}\nadd_filter( 'posts_where', 'search_by_meta_where', 10, 2 );// <-- Note the '2' which indicates we're accepting 2 arguments.\n</code></pre>\n\n<p>The same principle applies whenever you're filtering <code>pre_get_posts</code> as well. You should always use the query object that's passed to the filter to check these things, otherwise your changes will apply to <em>all</em> queries on the search page, including menus, widgets, and secondary queries, not just the specific search query.</p>\n"
}
] | 2019/03/01 | [
"https://wordpress.stackexchange.com/questions/330362",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162295/"
] | I have a custom table in the WP database called wp\_products. It has columns titled ID, SKU, Details and Page. I'm trying to search this table via the default search box, so I've replaced my search.php file with the code below. This isn't working and I don't know enough PHP to fix it. Can anyone help me out with this?
```
<?php
/**
* Author:
* Created on:
*
* @package Neve
*/
function search_it() {
if ( is_search() && isset( $_GET['s'] ) ) {
global $wpdb;
$address_table = $wpdb->prefix . "wp_products";
$search = $_GET['s'];
$search = "%{$search}%";
$where = $wpdb->prepare( 'WHERE SKU LIKE %s OR Details LIKE %s OR Page LIKE %s', $search, $search, $search );
$results = $wpdb->get_results( "SELECT * FROM {$address_table} {$where}" );
return $product;
}
return array();
}
$container_class = apply_filters( 'neve_container_class_filter', 'container', 'blog-archive' );
get_header();
$cities = search_it();
if ( ! empty( $cities ) ) {
echo '<h1>Catalogue Search Results:</h1>';
foreach( $cities AS $city ) {
echo "<table width='100%' align='center' border='3px solid grey'>";
echo "<tr>";
echo "<th style='background: #B9C9FE;'>Part Number</th>";
echo "<th style='background: #B9C9FE;'>Description</th>";
echo "<th style='background: #B9C9FE;'>Page</th>";
echo "</tr>";
echo "<tbody>";
for ($i=$start;$i < $end ;++$i ) {
$results = $results[$i];
echo "<tr>";
echo "<td>$city->SKU</td>";
echo "<td>$city->description</td>";
echo "<td>$city->Page</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
}
get_search_form();
?>
<?php
get_footer();
```
Here's the updated code:
```
<?php
/*
Template Name: Search Page
*/
function search_it() {
$search = filter_input( INPUT_GET, 's', FILTER_SANITIZE_STRING );
if ( ! is_search() || empty( $search ) ) {
return array();
}
global $wpdb;
$address_table = $wpdb->prefix . 'products';
$search = $wpdb->esc_like( $search );
$search = "%{$search}%";
$query = "SELECT * FROM {$wpdb->prefix}products WHERE SKU LIKE %s OR Details LIKE %s OR Page Like %s";
$query = $wpdb->prepare( $query, $search, $search, $search );
return $wpdb->get_results();
}
get_header();
$cities = search_it();
if ( ! empty( $cities ) ) {
echo '<h1>Catalogue Search Results:</h1>';
echo "<table width='100%' align='center' border='3px solid grey'>";
echo "<tr>";
echo "<th style='background: #B9C9FE;'>Part Number</th>";
echo "<th style='background: #B9C9FE;'>Description</th>";
echo "<th style='background: #B9C9FE;'>Page</th>";
echo "</tr>";
echo "<tbody>";
foreach( $cities AS $city ) {
echo "<tr>";
echo "<td>{$city->SKU}</td>";
echo "<td>{$city->Details}</td>";
echo "<td>{$city->Page}</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
} else {
echo "<h1 class='page-title'>";
printf( __( 'There are no search results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' );
echo ".</h1>";
$query;
}
get_search_form();
get_footer();
```
Here's the print\_r( $wpdb->prepare( $query, $search, $search, $search ) ); die; output:
```
SELECT * FROM wp_products WHERE SKU LIKE '{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}GASKET{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}' OR Details LIKE '{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}GASKET{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}' OR Page Like '{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}GASKET{feeb191b44038789f6b0c639a9f2fe6ff48090427c92513c8582b33a4cbf1c42}'
```
The above is the output I get when I run this query:
```
$query = "SELECT * FROM {$wpdb->prefix}products WHERE SKU LIKE %s OR Details LIKE %s OR Page Like %s";
``` | `is_search()` is only true if the *main* query is for the search results. When you create your own query with `new WP_Query`, you're not using the main query. Additionally, AJAX requests do not even have a main query, so functions like `is_search()`, `is_archive()` etc. do not work.
If you want to check if a specific query is a search, you should use the `is_search()` method of the query, like this:
```
$query->is_search();
```
The `posts_join` and `posts_where` filters are applied to all queries, but the callbacks to those filters receive the current query object as an argument, and you can use this to check for any search queries so that you can apply your filter:
```
function search_by_meta_join( $join, $query ) { // <-- Note the additional argument.
global $wpdb;
if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.
}
return $join;
}
add_filter('posts_join', 'search_by_meta_join', 10, 2 ); // <-- Note the '2' which indicates we're accepting 2 arguments.
function search_by_meta_where( $where, $query ) { // <-- Note the additional argument.
global $wpdb;
if ( $query->is_search() ) { // <-- Note that we are checking the current query, not the main query.
}
return $where;
}
add_filter( 'posts_where', 'search_by_meta_where', 10, 2 );// <-- Note the '2' which indicates we're accepting 2 arguments.
```
The same principle applies whenever you're filtering `pre_get_posts` as well. You should always use the query object that's passed to the filter to check these things, otherwise your changes will apply to *all* queries on the search page, including menus, widgets, and secondary queries, not just the specific search query. |
330,367 | <p>I am new in wordpress , started plugin development in wordpress a week ago . I have to add the new custom field in default <em>add user form</em> , is it possible . Then i if write wp_get_current_user() , is it possible to get the data which is added in the new custom field ?
Any body please help .
Thank you in advance . </p>
| [
{
"answer_id": 330378,
"author": "Roman Bitca",
"author_id": 150500,
"author_profile": "https://wordpress.stackexchange.com/users/150500",
"pm_score": 3,
"selected": true,
"text": "<p>It is possible. For that we will use 4 hooks (actions): show_user_profile, edit_user_profile, personal_options_update, edit_user_profile_update.</p>\n\n<p>Here is the example how to add extra field to user in WordPress.</p>\n\n<p>Adding user info fields function</p>\n\n<pre><code>add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );\nadd_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );\n\nfunction extra_user_profile_fields( $user ) { ?>\n <h3><?php _e(\"Extra profile information\", \"blank\"); ?></h3>\n\n <table class=\"form-table\">\n <tr>\n <th><label for=\"user_img_path_image\"><?php _e(\"Image path\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_img_path_image\" id=\"user_img_path_image\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"Path to country image.\"); ?></span>\n </td>\n </tr>\n <tr>\n <th><label for=\"user_country_field\"><?php _e(\"Country field\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_country_field\" id=\"user_country_field\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"\"); ?></span>\n </td>\n </tr>\n\n </table>\n<?php }\n\n</code></pre>\n\n<p>Here is the extra code for save and edit function</p>\n\n<pre><code>add_action( 'personal_options_update', 'save_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );\n\nfunction save_extra_user_profile_fields( $user_id ) {\n if ( !current_user_can( 'edit_user', $user_id ) ) { \n return false; \n }\n update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );\n update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );\n\n}\n// end - Add user info fields\n</code></pre>\n\n<p>Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.</p>\n\n<p>For extracting your date in frontend use this code:</p>\n\n<pre><code>$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );\n</code></pre>\n"
},
{
"answer_id": 330379,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>This is very possible. In WordPress, there is a concept of <a href=\"https://developer.wordpress.org/plugins/hooks/filters/\" rel=\"nofollow noreferrer\">Filters</a> and <a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"nofollow noreferrer\">Actions</a>, collectively known as \"hooks\". Hooks allow you to \"hook into\" WordPress to change values (filters) or to execute your own functions (actions).</p>\n\n<p>For the WordPress user page, you should look into the following hooks:</p>\n\n<ul>\n<li><code>show_user_profile</code> - Fires for the current user after the \"About Yourself\" section</li>\n<li><code>edit_user_profile</code> - Fires when editing <strong>another</strong> user's profile after the \"About the User\" section</li>\n</ul>\n\n<p>These two actions fire when viewing the page. Here, you can add your own code to display new fields, e.g.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user ) {\n $my_field_value = $user->my_field_key; // 'my_field_key' is the user meta field key in wp_usermeta\n // You can also use\n $my_field_value = get_user_meta( $user->ID, 'my_field_key', true );\n?>\n<input type=\"text\" name=\"my_field_key\" value=\"<?php echo esc_attr( $my_field_value ); ?>\"/>\n<?php\n});\n</code></pre>\n\n<p>Then, you can use the following actions to update the user:\n- <code>personal_options_update</code> - Fires when you update your own profile page.\n- <code>edit_user_profile_update</code> - Fires when you update another user's profile.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user_id ) {\n // You should escape and verify the input.\n $my_value = filter_input( INPUT_GET, 'my_field_key', FITLER_SANITIZE_STRING );\n\n if ( ! $my_value ) {\n delete_user_meta( $user_id, 'my_field_key' );\n return;\n }\n\n update_user_meta( $user_id, 'my_field_key', $my_value );\n} );\n</code></pre>\n\n<p>This could use some better HTML to fit the page, and should be modified for your usage, but hopefully this gives you an idea of where to go. Take a look at <code>/wp-admin/user-edit.php</code> for more details.</p>\n"
}
] | 2019/03/01 | [
"https://wordpress.stackexchange.com/questions/330367",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161732/"
] | I am new in wordpress , started plugin development in wordpress a week ago . I have to add the new custom field in default *add user form* , is it possible . Then i if write wp\_get\_current\_user() , is it possible to get the data which is added in the new custom field ?
Any body please help .
Thank you in advance . | It is possible. For that we will use 4 hooks (actions): show\_user\_profile, edit\_user\_profile, personal\_options\_update, edit\_user\_profile\_update.
Here is the example how to add extra field to user in WordPress.
Adding user info fields function
```
add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );
add_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );
function extra_user_profile_fields( $user ) { ?>
<h3><?php _e("Extra profile information", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="user_img_path_image"><?php _e("Image path"); ?></label></th>
<td>
<input type="text" name="user_img_path_image" id="user_img_path_image" value="<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Path to country image."); ?></span>
</td>
</tr>
<tr>
<th><label for="user_country_field"><?php _e("Country field"); ?></label></th>
<td>
<input type="text" name="user_country_field" id="user_country_field" value="<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e(""); ?></span>
</td>
</tr>
</table>
<?php }
```
Here is the extra code for save and edit function
```
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );
update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );
}
// end - Add user info fields
```
Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.
For extracting your date in frontend use this code:
```
$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );
``` |
330,369 | <p>I use this function to add prices to my WooCommerce variation dropdown menu. I am trying to wrap the price with a span tag but it's displaying the tags as text.</p>
<pre><code>add_filter( 'woocommerce_variation_option_name','display_price_in_variation_option_name');
function display_price_in_variation_option_name( $term ) {
global $product;
if ( empty( $term ) ) {
return $term;
}
if ( empty( $product->get_id() ) ) {
return $term;
}
$variation_id = $product->get_children();
foreach ( $variation_id as $id ) {
$_product = new WC_Product_Variation( $id );
$variation_data = $_product->get_variation_attributes();
foreach ( $variation_data as $key => $data ) {
$display_price = '';
switch ($id) {
case 1:
$display_price = $_product->get_price() / 12;
break;
case 2:
$display_price = $_product->get_price();
break;
case 3:
$display_price = $_product->get_price() / 6;
break;
default:
}
if ( $data == $term ) {
$html = $term;
$html .= '<span>' . $display_price . '</span>';
return $html;
}
}
}
return $term;
}
</code></pre>
| [
{
"answer_id": 330378,
"author": "Roman Bitca",
"author_id": 150500,
"author_profile": "https://wordpress.stackexchange.com/users/150500",
"pm_score": 3,
"selected": true,
"text": "<p>It is possible. For that we will use 4 hooks (actions): show_user_profile, edit_user_profile, personal_options_update, edit_user_profile_update.</p>\n\n<p>Here is the example how to add extra field to user in WordPress.</p>\n\n<p>Adding user info fields function</p>\n\n<pre><code>add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );\nadd_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );\n\nfunction extra_user_profile_fields( $user ) { ?>\n <h3><?php _e(\"Extra profile information\", \"blank\"); ?></h3>\n\n <table class=\"form-table\">\n <tr>\n <th><label for=\"user_img_path_image\"><?php _e(\"Image path\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_img_path_image\" id=\"user_img_path_image\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"Path to country image.\"); ?></span>\n </td>\n </tr>\n <tr>\n <th><label for=\"user_country_field\"><?php _e(\"Country field\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_country_field\" id=\"user_country_field\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"\"); ?></span>\n </td>\n </tr>\n\n </table>\n<?php }\n\n</code></pre>\n\n<p>Here is the extra code for save and edit function</p>\n\n<pre><code>add_action( 'personal_options_update', 'save_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );\n\nfunction save_extra_user_profile_fields( $user_id ) {\n if ( !current_user_can( 'edit_user', $user_id ) ) { \n return false; \n }\n update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );\n update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );\n\n}\n// end - Add user info fields\n</code></pre>\n\n<p>Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.</p>\n\n<p>For extracting your date in frontend use this code:</p>\n\n<pre><code>$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );\n</code></pre>\n"
},
{
"answer_id": 330379,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>This is very possible. In WordPress, there is a concept of <a href=\"https://developer.wordpress.org/plugins/hooks/filters/\" rel=\"nofollow noreferrer\">Filters</a> and <a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"nofollow noreferrer\">Actions</a>, collectively known as \"hooks\". Hooks allow you to \"hook into\" WordPress to change values (filters) or to execute your own functions (actions).</p>\n\n<p>For the WordPress user page, you should look into the following hooks:</p>\n\n<ul>\n<li><code>show_user_profile</code> - Fires for the current user after the \"About Yourself\" section</li>\n<li><code>edit_user_profile</code> - Fires when editing <strong>another</strong> user's profile after the \"About the User\" section</li>\n</ul>\n\n<p>These two actions fire when viewing the page. Here, you can add your own code to display new fields, e.g.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user ) {\n $my_field_value = $user->my_field_key; // 'my_field_key' is the user meta field key in wp_usermeta\n // You can also use\n $my_field_value = get_user_meta( $user->ID, 'my_field_key', true );\n?>\n<input type=\"text\" name=\"my_field_key\" value=\"<?php echo esc_attr( $my_field_value ); ?>\"/>\n<?php\n});\n</code></pre>\n\n<p>Then, you can use the following actions to update the user:\n- <code>personal_options_update</code> - Fires when you update your own profile page.\n- <code>edit_user_profile_update</code> - Fires when you update another user's profile.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user_id ) {\n // You should escape and verify the input.\n $my_value = filter_input( INPUT_GET, 'my_field_key', FITLER_SANITIZE_STRING );\n\n if ( ! $my_value ) {\n delete_user_meta( $user_id, 'my_field_key' );\n return;\n }\n\n update_user_meta( $user_id, 'my_field_key', $my_value );\n} );\n</code></pre>\n\n<p>This could use some better HTML to fit the page, and should be modified for your usage, but hopefully this gives you an idea of where to go. Take a look at <code>/wp-admin/user-edit.php</code> for more details.</p>\n"
}
] | 2019/03/01 | [
"https://wordpress.stackexchange.com/questions/330369",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134343/"
] | I use this function to add prices to my WooCommerce variation dropdown menu. I am trying to wrap the price with a span tag but it's displaying the tags as text.
```
add_filter( 'woocommerce_variation_option_name','display_price_in_variation_option_name');
function display_price_in_variation_option_name( $term ) {
global $product;
if ( empty( $term ) ) {
return $term;
}
if ( empty( $product->get_id() ) ) {
return $term;
}
$variation_id = $product->get_children();
foreach ( $variation_id as $id ) {
$_product = new WC_Product_Variation( $id );
$variation_data = $_product->get_variation_attributes();
foreach ( $variation_data as $key => $data ) {
$display_price = '';
switch ($id) {
case 1:
$display_price = $_product->get_price() / 12;
break;
case 2:
$display_price = $_product->get_price();
break;
case 3:
$display_price = $_product->get_price() / 6;
break;
default:
}
if ( $data == $term ) {
$html = $term;
$html .= '<span>' . $display_price . '</span>';
return $html;
}
}
}
return $term;
}
``` | It is possible. For that we will use 4 hooks (actions): show\_user\_profile, edit\_user\_profile, personal\_options\_update, edit\_user\_profile\_update.
Here is the example how to add extra field to user in WordPress.
Adding user info fields function
```
add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );
add_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );
function extra_user_profile_fields( $user ) { ?>
<h3><?php _e("Extra profile information", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="user_img_path_image"><?php _e("Image path"); ?></label></th>
<td>
<input type="text" name="user_img_path_image" id="user_img_path_image" value="<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Path to country image."); ?></span>
</td>
</tr>
<tr>
<th><label for="user_country_field"><?php _e("Country field"); ?></label></th>
<td>
<input type="text" name="user_country_field" id="user_country_field" value="<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e(""); ?></span>
</td>
</tr>
</table>
<?php }
```
Here is the extra code for save and edit function
```
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );
update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );
}
// end - Add user info fields
```
Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.
For extracting your date in frontend use this code:
```
$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );
``` |
330,375 | <p>I have a problem - when I click on "Wordpress update", I receive this message:</p>
<blockquote>
<p>Downloading update from <a href="https://downloads.wordpress.org/release/wordpress-5.1-new-bundled.zip" rel="nofollow noreferrer">https://downloads.wordpress.org/release/wordpress-5.1-new-bundled.zip</a>… Unpacking the update… The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.: wp-admin/includes/update-core.php Installation Failed</p>
</blockquote>
<p>I changed permissions: WP-admin and WP-includes to 755 WP-content to 777 All files in WP-admin are 755.</p>
<p>What can be the problem? I am trying to solve it, but I can't do it.</p>
| [
{
"answer_id": 330378,
"author": "Roman Bitca",
"author_id": 150500,
"author_profile": "https://wordpress.stackexchange.com/users/150500",
"pm_score": 3,
"selected": true,
"text": "<p>It is possible. For that we will use 4 hooks (actions): show_user_profile, edit_user_profile, personal_options_update, edit_user_profile_update.</p>\n\n<p>Here is the example how to add extra field to user in WordPress.</p>\n\n<p>Adding user info fields function</p>\n\n<pre><code>add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );\nadd_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );\n\nfunction extra_user_profile_fields( $user ) { ?>\n <h3><?php _e(\"Extra profile information\", \"blank\"); ?></h3>\n\n <table class=\"form-table\">\n <tr>\n <th><label for=\"user_img_path_image\"><?php _e(\"Image path\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_img_path_image\" id=\"user_img_path_image\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"Path to country image.\"); ?></span>\n </td>\n </tr>\n <tr>\n <th><label for=\"user_country_field\"><?php _e(\"Country field\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_country_field\" id=\"user_country_field\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"\"); ?></span>\n </td>\n </tr>\n\n </table>\n<?php }\n\n</code></pre>\n\n<p>Here is the extra code for save and edit function</p>\n\n<pre><code>add_action( 'personal_options_update', 'save_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );\n\nfunction save_extra_user_profile_fields( $user_id ) {\n if ( !current_user_can( 'edit_user', $user_id ) ) { \n return false; \n }\n update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );\n update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );\n\n}\n// end - Add user info fields\n</code></pre>\n\n<p>Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.</p>\n\n<p>For extracting your date in frontend use this code:</p>\n\n<pre><code>$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );\n</code></pre>\n"
},
{
"answer_id": 330379,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>This is very possible. In WordPress, there is a concept of <a href=\"https://developer.wordpress.org/plugins/hooks/filters/\" rel=\"nofollow noreferrer\">Filters</a> and <a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"nofollow noreferrer\">Actions</a>, collectively known as \"hooks\". Hooks allow you to \"hook into\" WordPress to change values (filters) or to execute your own functions (actions).</p>\n\n<p>For the WordPress user page, you should look into the following hooks:</p>\n\n<ul>\n<li><code>show_user_profile</code> - Fires for the current user after the \"About Yourself\" section</li>\n<li><code>edit_user_profile</code> - Fires when editing <strong>another</strong> user's profile after the \"About the User\" section</li>\n</ul>\n\n<p>These two actions fire when viewing the page. Here, you can add your own code to display new fields, e.g.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user ) {\n $my_field_value = $user->my_field_key; // 'my_field_key' is the user meta field key in wp_usermeta\n // You can also use\n $my_field_value = get_user_meta( $user->ID, 'my_field_key', true );\n?>\n<input type=\"text\" name=\"my_field_key\" value=\"<?php echo esc_attr( $my_field_value ); ?>\"/>\n<?php\n});\n</code></pre>\n\n<p>Then, you can use the following actions to update the user:\n- <code>personal_options_update</code> - Fires when you update your own profile page.\n- <code>edit_user_profile_update</code> - Fires when you update another user's profile.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user_id ) {\n // You should escape and verify the input.\n $my_value = filter_input( INPUT_GET, 'my_field_key', FITLER_SANITIZE_STRING );\n\n if ( ! $my_value ) {\n delete_user_meta( $user_id, 'my_field_key' );\n return;\n }\n\n update_user_meta( $user_id, 'my_field_key', $my_value );\n} );\n</code></pre>\n\n<p>This could use some better HTML to fit the page, and should be modified for your usage, but hopefully this gives you an idea of where to go. Take a look at <code>/wp-admin/user-edit.php</code> for more details.</p>\n"
}
] | 2019/03/01 | [
"https://wordpress.stackexchange.com/questions/330375",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134556/"
] | I have a problem - when I click on "Wordpress update", I receive this message:
>
> Downloading update from <https://downloads.wordpress.org/release/wordpress-5.1-new-bundled.zip>… Unpacking the update… The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.: wp-admin/includes/update-core.php Installation Failed
>
>
>
I changed permissions: WP-admin and WP-includes to 755 WP-content to 777 All files in WP-admin are 755.
What can be the problem? I am trying to solve it, but I can't do it. | It is possible. For that we will use 4 hooks (actions): show\_user\_profile, edit\_user\_profile, personal\_options\_update, edit\_user\_profile\_update.
Here is the example how to add extra field to user in WordPress.
Adding user info fields function
```
add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );
add_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );
function extra_user_profile_fields( $user ) { ?>
<h3><?php _e("Extra profile information", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="user_img_path_image"><?php _e("Image path"); ?></label></th>
<td>
<input type="text" name="user_img_path_image" id="user_img_path_image" value="<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Path to country image."); ?></span>
</td>
</tr>
<tr>
<th><label for="user_country_field"><?php _e("Country field"); ?></label></th>
<td>
<input type="text" name="user_country_field" id="user_country_field" value="<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e(""); ?></span>
</td>
</tr>
</table>
<?php }
```
Here is the extra code for save and edit function
```
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );
update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );
}
// end - Add user info fields
```
Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.
For extracting your date in frontend use this code:
```
$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );
``` |
330,377 | <p>I wrote a plugin to hit an API and display results on a page. When I was testing, every time I hit "preview", the plugin would hit the API and retrieve the most recent data. Now that the plugin is live, when I navigate to the live page, no calls are being made to the API.</p>
<p>Through research I believe this is a caching issue, since we want real time data, we would like that every time a user navigates to the page, the plugin fires off to the API and the most recent values are returned. </p>
<p>Here is a snippet of my code: </p>
<pre><code>function get_count(){
//get response from api
$request = wp_remote_get('https://myapi.com/count');
if(is_wp_error($request)){
return false;
}
//get the body from the response
$body= json_decode(wp_remote_retrieve_body($request));
//parse the body and get the count attribute
$statistic=($body->payload->count);
return '<div id="value" class="number">'. $statistic . '</div>';
}
add_shortcode('real_time_count','get_count');
</code></pre>
<p>How can I make this execute every time a user navigates to a page that has this shortcode?</p>
| [
{
"answer_id": 330378,
"author": "Roman Bitca",
"author_id": 150500,
"author_profile": "https://wordpress.stackexchange.com/users/150500",
"pm_score": 3,
"selected": true,
"text": "<p>It is possible. For that we will use 4 hooks (actions): show_user_profile, edit_user_profile, personal_options_update, edit_user_profile_update.</p>\n\n<p>Here is the example how to add extra field to user in WordPress.</p>\n\n<p>Adding user info fields function</p>\n\n<pre><code>add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );\nadd_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );\n\nfunction extra_user_profile_fields( $user ) { ?>\n <h3><?php _e(\"Extra profile information\", \"blank\"); ?></h3>\n\n <table class=\"form-table\">\n <tr>\n <th><label for=\"user_img_path_image\"><?php _e(\"Image path\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_img_path_image\" id=\"user_img_path_image\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"Path to country image.\"); ?></span>\n </td>\n </tr>\n <tr>\n <th><label for=\"user_country_field\"><?php _e(\"Country field\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_country_field\" id=\"user_country_field\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"\"); ?></span>\n </td>\n </tr>\n\n </table>\n<?php }\n\n</code></pre>\n\n<p>Here is the extra code for save and edit function</p>\n\n<pre><code>add_action( 'personal_options_update', 'save_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );\n\nfunction save_extra_user_profile_fields( $user_id ) {\n if ( !current_user_can( 'edit_user', $user_id ) ) { \n return false; \n }\n update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );\n update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );\n\n}\n// end - Add user info fields\n</code></pre>\n\n<p>Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.</p>\n\n<p>For extracting your date in frontend use this code:</p>\n\n<pre><code>$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );\n</code></pre>\n"
},
{
"answer_id": 330379,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>This is very possible. In WordPress, there is a concept of <a href=\"https://developer.wordpress.org/plugins/hooks/filters/\" rel=\"nofollow noreferrer\">Filters</a> and <a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"nofollow noreferrer\">Actions</a>, collectively known as \"hooks\". Hooks allow you to \"hook into\" WordPress to change values (filters) or to execute your own functions (actions).</p>\n\n<p>For the WordPress user page, you should look into the following hooks:</p>\n\n<ul>\n<li><code>show_user_profile</code> - Fires for the current user after the \"About Yourself\" section</li>\n<li><code>edit_user_profile</code> - Fires when editing <strong>another</strong> user's profile after the \"About the User\" section</li>\n</ul>\n\n<p>These two actions fire when viewing the page. Here, you can add your own code to display new fields, e.g.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user ) {\n $my_field_value = $user->my_field_key; // 'my_field_key' is the user meta field key in wp_usermeta\n // You can also use\n $my_field_value = get_user_meta( $user->ID, 'my_field_key', true );\n?>\n<input type=\"text\" name=\"my_field_key\" value=\"<?php echo esc_attr( $my_field_value ); ?>\"/>\n<?php\n});\n</code></pre>\n\n<p>Then, you can use the following actions to update the user:\n- <code>personal_options_update</code> - Fires when you update your own profile page.\n- <code>edit_user_profile_update</code> - Fires when you update another user's profile.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user_id ) {\n // You should escape and verify the input.\n $my_value = filter_input( INPUT_GET, 'my_field_key', FITLER_SANITIZE_STRING );\n\n if ( ! $my_value ) {\n delete_user_meta( $user_id, 'my_field_key' );\n return;\n }\n\n update_user_meta( $user_id, 'my_field_key', $my_value );\n} );\n</code></pre>\n\n<p>This could use some better HTML to fit the page, and should be modified for your usage, but hopefully this gives you an idea of where to go. Take a look at <code>/wp-admin/user-edit.php</code> for more details.</p>\n"
}
] | 2019/03/01 | [
"https://wordpress.stackexchange.com/questions/330377",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162301/"
] | I wrote a plugin to hit an API and display results on a page. When I was testing, every time I hit "preview", the plugin would hit the API and retrieve the most recent data. Now that the plugin is live, when I navigate to the live page, no calls are being made to the API.
Through research I believe this is a caching issue, since we want real time data, we would like that every time a user navigates to the page, the plugin fires off to the API and the most recent values are returned.
Here is a snippet of my code:
```
function get_count(){
//get response from api
$request = wp_remote_get('https://myapi.com/count');
if(is_wp_error($request)){
return false;
}
//get the body from the response
$body= json_decode(wp_remote_retrieve_body($request));
//parse the body and get the count attribute
$statistic=($body->payload->count);
return '<div id="value" class="number">'. $statistic . '</div>';
}
add_shortcode('real_time_count','get_count');
```
How can I make this execute every time a user navigates to a page that has this shortcode? | It is possible. For that we will use 4 hooks (actions): show\_user\_profile, edit\_user\_profile, personal\_options\_update, edit\_user\_profile\_update.
Here is the example how to add extra field to user in WordPress.
Adding user info fields function
```
add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );
add_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );
function extra_user_profile_fields( $user ) { ?>
<h3><?php _e("Extra profile information", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="user_img_path_image"><?php _e("Image path"); ?></label></th>
<td>
<input type="text" name="user_img_path_image" id="user_img_path_image" value="<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Path to country image."); ?></span>
</td>
</tr>
<tr>
<th><label for="user_country_field"><?php _e("Country field"); ?></label></th>
<td>
<input type="text" name="user_country_field" id="user_country_field" value="<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e(""); ?></span>
</td>
</tr>
</table>
<?php }
```
Here is the extra code for save and edit function
```
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );
update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );
}
// end - Add user info fields
```
Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.
For extracting your date in frontend use this code:
```
$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );
``` |
330,387 | <p>Anybody know how to make the "add to cart" visible on product page?
I did an update of content-product.php and after that the add to cart and choose style options are gone.
Please check the link below:</p>
<p><a href="https://twinklebelle.com/product-category/rain-gear/rain-pants/" rel="nofollow noreferrer">https://twinklebelle.com/product-category/rain-gear/rain-pants/</a></p>
| [
{
"answer_id": 330378,
"author": "Roman Bitca",
"author_id": 150500,
"author_profile": "https://wordpress.stackexchange.com/users/150500",
"pm_score": 3,
"selected": true,
"text": "<p>It is possible. For that we will use 4 hooks (actions): show_user_profile, edit_user_profile, personal_options_update, edit_user_profile_update.</p>\n\n<p>Here is the example how to add extra field to user in WordPress.</p>\n\n<p>Adding user info fields function</p>\n\n<pre><code>add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );\nadd_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );\n\nfunction extra_user_profile_fields( $user ) { ?>\n <h3><?php _e(\"Extra profile information\", \"blank\"); ?></h3>\n\n <table class=\"form-table\">\n <tr>\n <th><label for=\"user_img_path_image\"><?php _e(\"Image path\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_img_path_image\" id=\"user_img_path_image\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"Path to country image.\"); ?></span>\n </td>\n </tr>\n <tr>\n <th><label for=\"user_country_field\"><?php _e(\"Country field\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_country_field\" id=\"user_country_field\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"\"); ?></span>\n </td>\n </tr>\n\n </table>\n<?php }\n\n</code></pre>\n\n<p>Here is the extra code for save and edit function</p>\n\n<pre><code>add_action( 'personal_options_update', 'save_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );\n\nfunction save_extra_user_profile_fields( $user_id ) {\n if ( !current_user_can( 'edit_user', $user_id ) ) { \n return false; \n }\n update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );\n update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );\n\n}\n// end - Add user info fields\n</code></pre>\n\n<p>Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.</p>\n\n<p>For extracting your date in frontend use this code:</p>\n\n<pre><code>$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );\n</code></pre>\n"
},
{
"answer_id": 330379,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>This is very possible. In WordPress, there is a concept of <a href=\"https://developer.wordpress.org/plugins/hooks/filters/\" rel=\"nofollow noreferrer\">Filters</a> and <a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"nofollow noreferrer\">Actions</a>, collectively known as \"hooks\". Hooks allow you to \"hook into\" WordPress to change values (filters) or to execute your own functions (actions).</p>\n\n<p>For the WordPress user page, you should look into the following hooks:</p>\n\n<ul>\n<li><code>show_user_profile</code> - Fires for the current user after the \"About Yourself\" section</li>\n<li><code>edit_user_profile</code> - Fires when editing <strong>another</strong> user's profile after the \"About the User\" section</li>\n</ul>\n\n<p>These two actions fire when viewing the page. Here, you can add your own code to display new fields, e.g.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user ) {\n $my_field_value = $user->my_field_key; // 'my_field_key' is the user meta field key in wp_usermeta\n // You can also use\n $my_field_value = get_user_meta( $user->ID, 'my_field_key', true );\n?>\n<input type=\"text\" name=\"my_field_key\" value=\"<?php echo esc_attr( $my_field_value ); ?>\"/>\n<?php\n});\n</code></pre>\n\n<p>Then, you can use the following actions to update the user:\n- <code>personal_options_update</code> - Fires when you update your own profile page.\n- <code>edit_user_profile_update</code> - Fires when you update another user's profile.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user_id ) {\n // You should escape and verify the input.\n $my_value = filter_input( INPUT_GET, 'my_field_key', FITLER_SANITIZE_STRING );\n\n if ( ! $my_value ) {\n delete_user_meta( $user_id, 'my_field_key' );\n return;\n }\n\n update_user_meta( $user_id, 'my_field_key', $my_value );\n} );\n</code></pre>\n\n<p>This could use some better HTML to fit the page, and should be modified for your usage, but hopefully this gives you an idea of where to go. Take a look at <code>/wp-admin/user-edit.php</code> for more details.</p>\n"
}
] | 2019/03/01 | [
"https://wordpress.stackexchange.com/questions/330387",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162304/"
] | Anybody know how to make the "add to cart" visible on product page?
I did an update of content-product.php and after that the add to cart and choose style options are gone.
Please check the link below:
<https://twinklebelle.com/product-category/rain-gear/rain-pants/> | It is possible. For that we will use 4 hooks (actions): show\_user\_profile, edit\_user\_profile, personal\_options\_update, edit\_user\_profile\_update.
Here is the example how to add extra field to user in WordPress.
Adding user info fields function
```
add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );
add_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );
function extra_user_profile_fields( $user ) { ?>
<h3><?php _e("Extra profile information", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="user_img_path_image"><?php _e("Image path"); ?></label></th>
<td>
<input type="text" name="user_img_path_image" id="user_img_path_image" value="<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Path to country image."); ?></span>
</td>
</tr>
<tr>
<th><label for="user_country_field"><?php _e("Country field"); ?></label></th>
<td>
<input type="text" name="user_country_field" id="user_country_field" value="<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e(""); ?></span>
</td>
</tr>
</table>
<?php }
```
Here is the extra code for save and edit function
```
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );
update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );
}
// end - Add user info fields
```
Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.
For extracting your date in frontend use this code:
```
$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );
``` |
330,444 | <p>I have been using WP All Import (to varying degrees of success) to import products to my Woo Commerce site. My server keeps timing out and stopping the import which is causing me difficulty and I have followed the official advise from the plugin without much luck. My imports are broken into ~12 CSV files, the largest with ~100 rows.</p>
<p>Does anyone have any other ways of adding ~400 products to the site with the correct variations? One solution I considered was running my site locally, running all my imports and then replacing my live db with the local one but I would rather avoid that...</p>
| [
{
"answer_id": 330378,
"author": "Roman Bitca",
"author_id": 150500,
"author_profile": "https://wordpress.stackexchange.com/users/150500",
"pm_score": 3,
"selected": true,
"text": "<p>It is possible. For that we will use 4 hooks (actions): show_user_profile, edit_user_profile, personal_options_update, edit_user_profile_update.</p>\n\n<p>Here is the example how to add extra field to user in WordPress.</p>\n\n<p>Adding user info fields function</p>\n\n<pre><code>add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );\nadd_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );\n\nfunction extra_user_profile_fields( $user ) { ?>\n <h3><?php _e(\"Extra profile information\", \"blank\"); ?></h3>\n\n <table class=\"form-table\">\n <tr>\n <th><label for=\"user_img_path_image\"><?php _e(\"Image path\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_img_path_image\" id=\"user_img_path_image\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"Path to country image.\"); ?></span>\n </td>\n </tr>\n <tr>\n <th><label for=\"user_country_field\"><?php _e(\"Country field\"); ?></label></th>\n <td>\n <input type=\"text\" name=\"user_country_field\" id=\"user_country_field\" value=\"<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>\" class=\"regular-text\" /><br />\n <span class=\"description\"><?php _e(\"\"); ?></span>\n </td>\n </tr>\n\n </table>\n<?php }\n\n</code></pre>\n\n<p>Here is the extra code for save and edit function</p>\n\n<pre><code>add_action( 'personal_options_update', 'save_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );\n\nfunction save_extra_user_profile_fields( $user_id ) {\n if ( !current_user_can( 'edit_user', $user_id ) ) { \n return false; \n }\n update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );\n update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );\n\n}\n// end - Add user info fields\n</code></pre>\n\n<p>Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.</p>\n\n<p>For extracting your date in frontend use this code:</p>\n\n<pre><code>$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );\n</code></pre>\n"
},
{
"answer_id": 330379,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": false,
"text": "<p>This is very possible. In WordPress, there is a concept of <a href=\"https://developer.wordpress.org/plugins/hooks/filters/\" rel=\"nofollow noreferrer\">Filters</a> and <a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"nofollow noreferrer\">Actions</a>, collectively known as \"hooks\". Hooks allow you to \"hook into\" WordPress to change values (filters) or to execute your own functions (actions).</p>\n\n<p>For the WordPress user page, you should look into the following hooks:</p>\n\n<ul>\n<li><code>show_user_profile</code> - Fires for the current user after the \"About Yourself\" section</li>\n<li><code>edit_user_profile</code> - Fires when editing <strong>another</strong> user's profile after the \"About the User\" section</li>\n</ul>\n\n<p>These two actions fire when viewing the page. Here, you can add your own code to display new fields, e.g.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user ) {\n $my_field_value = $user->my_field_key; // 'my_field_key' is the user meta field key in wp_usermeta\n // You can also use\n $my_field_value = get_user_meta( $user->ID, 'my_field_key', true );\n?>\n<input type=\"text\" name=\"my_field_key\" value=\"<?php echo esc_attr( $my_field_value ); ?>\"/>\n<?php\n});\n</code></pre>\n\n<p>Then, you can use the following actions to update the user:\n- <code>personal_options_update</code> - Fires when you update your own profile page.\n- <code>edit_user_profile_update</code> - Fires when you update another user's profile.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'personal_options_update', function( $user_id ) {\n // You should escape and verify the input.\n $my_value = filter_input( INPUT_GET, 'my_field_key', FITLER_SANITIZE_STRING );\n\n if ( ! $my_value ) {\n delete_user_meta( $user_id, 'my_field_key' );\n return;\n }\n\n update_user_meta( $user_id, 'my_field_key', $my_value );\n} );\n</code></pre>\n\n<p>This could use some better HTML to fit the page, and should be modified for your usage, but hopefully this gives you an idea of where to go. Take a look at <code>/wp-admin/user-edit.php</code> for more details.</p>\n"
}
] | 2019/03/02 | [
"https://wordpress.stackexchange.com/questions/330444",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148232/"
] | I have been using WP All Import (to varying degrees of success) to import products to my Woo Commerce site. My server keeps timing out and stopping the import which is causing me difficulty and I have followed the official advise from the plugin without much luck. My imports are broken into ~12 CSV files, the largest with ~100 rows.
Does anyone have any other ways of adding ~400 products to the site with the correct variations? One solution I considered was running my site locally, running all my imports and then replacing my live db with the local one but I would rather avoid that... | It is possible. For that we will use 4 hooks (actions): show\_user\_profile, edit\_user\_profile, personal\_options\_update, edit\_user\_profile\_update.
Here is the example how to add extra field to user in WordPress.
Adding user info fields function
```
add_action( 'show_user_profile', 'extra_user_profile_fields', 10, 1 );
add_action( 'edit_user_profile', 'extra_user_profile_fields', 10, 1 );
function extra_user_profile_fields( $user ) { ?>
<h3><?php _e("Extra profile information", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="user_img_path_image"><?php _e("Image path"); ?></label></th>
<td>
<input type="text" name="user_img_path_image" id="user_img_path_image" value="<?php echo esc_attr( get_the_author_meta( 'user_img_path_image', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Path to country image."); ?></span>
</td>
</tr>
<tr>
<th><label for="user_country_field"><?php _e("Country field"); ?></label></th>
<td>
<input type="text" name="user_country_field" id="user_country_field" value="<?php echo esc_attr( get_the_author_meta( 'user_country_field', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e(""); ?></span>
</td>
</tr>
</table>
<?php }
```
Here is the extra code for save and edit function
```
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'user_img_path_image', $_POST['user_img_path_image'] );
update_user_meta( $user_id, 'user_country_field', $_POST['user_country_field'] );
}
// end - Add user info fields
```
Just copy and paste this code in your plugin or function.php and you must see new 2 fields in Wordpress backend user editing/adding page.
For extracting your date in frontend use this code:
```
$user_facebook_id_acc = get_the_author_meta( 'user_facebook_id_acc', $current_user_data->ID );
``` |
330,460 | <p>I've twice had my site's url changed in the database. This is the only piece of data being altered. Whoever is doing this is then redirecting the site to a script at this location:</p>
<pre><code>somelandingpage [dot] com/3gGykjDJ?frm=script
</code></pre>
<p>I've tried preventing XSS and have checked/updated every single plugin and I cannot figure out how this is happening. Any ideas?</p>
| [
{
"answer_id": 330469,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>YOu need to deeply look throughout your site for the 'infection'/malware code. This would include the following steps:</p>\n\n<ul>\n<li>update everything (WP, themes, plugins)</li>\n<li>change credentials on everything (hosting, FTP, admin-level users)</li>\n<li>create a new admin user, log in as it, then delete the user called 'admin' (or demote to 'subscriber')</li>\n<li>look at all folders for files that shouldn't be there. This is somewhat easier if you sort the file list by date, looking for outliers (since you updated everything, the 'good' files should have the same date/timestamp).</li>\n</ul>\n\n<p>I've put together a <a href=\"https://securitydawg.com/recovering-from-a-hacked-wordpress-site/\" rel=\"nofollow noreferrer\">procedure</a> I use to clean up a site. It takes a while, but can be done. There are other similar resources available via your favorite search engine.</p>\n"
},
{
"answer_id": 330531,
"author": "Inventiva Creative Studio",
"author_id": 162418,
"author_profile": "https://wordpress.stackexchange.com/users/162418",
"pm_score": 0,
"selected": false,
"text": "<p>Here is how to fix this:</p>\n\n<ol>\n<li>Log onto your PHPMyAdmin. </li>\n<li>Head to wp_options On line 1 (siteurl) you will notice the 'somelandingpage [dot] com/3gGykjDJ?frm=script' address. Simply edit this line and replace the address with the correct one for your site (Copy the same you see on line 2, generally something like: <a href=\"https://yoursite.com\" rel=\"nofollow noreferrer\">https://yoursite.com</a>)</li>\n<li>This should get rid of the \"redirection\" and you should be able to log onto your Wordpress Admin Dashboard, from there make sure to update to the\nlatest Wordpress version and update all your plugins accordingly.</li>\n</ol>\n\n<p>Hope this helps and saves some of you some time :)</p>\n"
}
] | 2019/03/02 | [
"https://wordpress.stackexchange.com/questions/330460",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162371/"
] | I've twice had my site's url changed in the database. This is the only piece of data being altered. Whoever is doing this is then redirecting the site to a script at this location:
```
somelandingpage [dot] com/3gGykjDJ?frm=script
```
I've tried preventing XSS and have checked/updated every single plugin and I cannot figure out how this is happening. Any ideas? | YOu need to deeply look throughout your site for the 'infection'/malware code. This would include the following steps:
* update everything (WP, themes, plugins)
* change credentials on everything (hosting, FTP, admin-level users)
* create a new admin user, log in as it, then delete the user called 'admin' (or demote to 'subscriber')
* look at all folders for files that shouldn't be there. This is somewhat easier if you sort the file list by date, looking for outliers (since you updated everything, the 'good' files should have the same date/timestamp).
I've put together a [procedure](https://securitydawg.com/recovering-from-a-hacked-wordpress-site/) I use to clean up a site. It takes a while, but can be done. There are other similar resources available via your favorite search engine. |
330,465 | <p>Wordpress has a <a href="https://en.support.wordpress.com/site-icons/" rel="nofollow noreferrer">"Site Icon"</a> feature that serves correctly-sized favicons and so on to browsers. Is there a way to drive this feature programmatically, eg. by uploading media and setting an option with <code>wp cli</code>?</p>
| [
{
"answer_id": 330657,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>The 'official rules' about site icons are here:<a href=\"https://www.w3.org/TR/html5/links.html#link-type-icon\" rel=\"nofollow noreferrer\">https://www.w3.org/TR/html5/links.html#link-type-icon</a> .</p>\n\n<p>They provide this example of site icons for several sizes:</p>\n\n<pre><code><link rel=icon href=favicon.png sizes=\"16x16\" type=\"image/png\">\n <link rel=icon href=windows.ico sizes=\"32x32 48x48\" type=\"image/vnd.microsoft.icon\">\n <link rel=icon href=mac.icns sizes=\"128x128 512x512 8192x8192 32768x32768\">\n <link rel=icon href=iphone.png sizes=\"57x57\" type=\"image/png\">\n <link rel=icon href=gnome.svg sizes=\"any\" type=\"image/svg+xml\">\n</code></pre>\n\n<p>The above link also specifies if the 'link rel=icon ...' is not specified, then the /favicon.ico file (in the site root) will be used.</p>\n\n<p>It further states: </p>\n\n<blockquote>\n <p>\"If multiple icons are provided, the user agent must select the most\n appropriate icon according to the type, media, and sizes attributes.\"</p>\n</blockquote>\n\n<p>(\"User agent\" is the browser rendering the site.)</p>\n\n<p>Also, see one of the answers here <a href=\"https://stackoverflow.com/questions/9943771/adding-a-favicon-to-a-static-html-page\">https://stackoverflow.com/questions/9943771/adding-a-favicon-to-a-static-html-page</a> that references an application to create all of the different icon sizes and the code needed to use them:</p>\n\n<blockquote>\n <p>Actually, to make your favicon work in all browsers, you must have\n more than 10 images in the correct sizes and formats.</p>\n \n <p>I created an App (<a href=\"http://faviconit.com/\" rel=\"nofollow noreferrer\">faviconit.com</a>) so people don´t have to create all\n these images and the correct tags by hand.</p>\n</blockquote>\n\n<p>I have not tried the application referenced. YMMV.</p>\n\n<p>And, this question/answer might also be helpful: <a href=\"https://stackoverflow.com/questions/53464667/best-practice-for-ordering-icon-link-tags-in-html-head\">https://stackoverflow.com/questions/53464667/best-practice-for-ordering-icon-link-tags-in-html-head</a> .</p>\n"
},
{
"answer_id": 364342,
"author": "Koubi",
"author_id": 186320,
"author_profile": "https://wordpress.stackexchange.com/users/186320",
"pm_score": 0,
"selected": false,
"text": "<p>I managed to set the favicon of my wordpress using Wordpress CLI:</p>\n\n<pre><code>FAVICON_TITLE=\"mysite-favicon\"\nFAVICON_PATH=\"~/dev/favicon.png\"\nwp media import ${FAVICON_PATH} --title=${FAVICON_TITLE}\nFAVICON_ID=$(wp post list --post_type=attachment --post_title=${FAVICON_TITLE} --format=ids)\nwp option update site_icon ${FAVICON_ID}\n</code></pre>\n"
},
{
"answer_id": 373440,
"author": "Rentringer",
"author_id": 119120,
"author_profile": "https://wordpress.stackexchange.com/users/119120",
"pm_score": 1,
"selected": false,
"text": "<p>Use wp-cli commands <code>wp media import</code> and <code>wp option update</code>.</p>\n<p><code>wp media import <file></code> : Creates attachments from local files or URLs.</p>\n<p><code>wp option update <key></code> : Updates an option value.</p>\n<p><strong>Image from theme folder</strong> :</p>\n<pre><code>$ wp media import "$(wp theme path)/theme/assets/images/logo.png" --porcelain | wp option update site_icon\n</code></pre>\n<p><strong>Image from url</strong> :</p>\n<pre><code>$ wp media import "https://source.unsplash.com/random/512x512" --porcelain | wp option update site_icon\n</code></pre>\n<p>The flag [--porcelain] output just the new attachment ID.</p>\n<p><strong>References</strong> :</p>\n<p><a href=\"https://developer.wordpress.org/cli/commands/media/import/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/media/import/</a></p>\n<p><a href=\"https://developer.wordpress.org/cli/commands/option/update/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/option/update/</a></p>\n"
}
] | 2019/03/02 | [
"https://wordpress.stackexchange.com/questions/330465",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/162374/"
] | Wordpress has a ["Site Icon"](https://en.support.wordpress.com/site-icons/) feature that serves correctly-sized favicons and so on to browsers. Is there a way to drive this feature programmatically, eg. by uploading media and setting an option with `wp cli`? | Use wp-cli commands `wp media import` and `wp option update`.
`wp media import <file>` : Creates attachments from local files or URLs.
`wp option update <key>` : Updates an option value.
**Image from theme folder** :
```
$ wp media import "$(wp theme path)/theme/assets/images/logo.png" --porcelain | wp option update site_icon
```
**Image from url** :
```
$ wp media import "https://source.unsplash.com/random/512x512" --porcelain | wp option update site_icon
```
The flag [--porcelain] output just the new attachment ID.
**References** :
<https://developer.wordpress.org/cli/commands/media/import/>
<https://developer.wordpress.org/cli/commands/option/update/> |
330,471 | <p>I'm using a filter in the Block API to add a class name to a block's wrapper. I have to add the class name to a specific block, not all blocks.</p>
<p>I tried:</p>
<pre><code>const addClassName = createHigherOrderComponent( ( BlockListBlock ) => {
return ( props, blockType ) => {
if ( blockType.name === 'myplugin/myblock' ) {
return <BlockListBlock { ...props } className="test" />;
}
return <BlockListBlock { ...props } />
}
}, 'addClassName' );
wp.hooks.addFilter( 'editor.BlockListBlock', 'myplugin/add-class-name', addClassName );
</code></pre>
<p>The issue: <code>blockType.name</code> returns undefined. I also tried <code>getBlockType.name</code> and it also returns undefined. I also tried getting the block name of core blocks. For example <code>core/columns</code>.</p>
| [
{
"answer_id": 330667,
"author": "Alvaro",
"author_id": 16533,
"author_profile": "https://wordpress.stackexchange.com/users/16533",
"pm_score": 3,
"selected": true,
"text": "<p>From the props object we can get the block information. The object contains the <code>name</code> property you are looking for; this would be the code:</p>\n\n<pre><code>const addClassName = createHigherOrderComponent(BlockListBlock => {\n return props => {\n if (props.name === \"myplugin/myblock\") {\n return <BlockListBlock {...props} className=\"test\" />;\n }\n return <BlockListBlock {...props} />;\n };\n}, \"addClassName\");\n\nwp.hooks.addFilter(\n \"editor.BlockListBlock\",\n \"myplugin/add-class-name\",\n addClassName\n);\n</code></pre>\n"
},
{
"answer_id": 330716,
"author": "Mehmood Ahmad",
"author_id": 149796,
"author_profile": "https://wordpress.stackexchange.com/users/149796",
"pm_score": 0,
"selected": false,
"text": "<p>You can get the selected block name by using this <code>wp.data.select( 'core/editor' ).getSelectedBlock().name;</code> inside the block edit or save function. This is the answer of what your question title is saying.</p>\n\n<p>By the way you can easily add class anywhere in the layout inside edit function so why are you hassling so much. </p>\n"
},
{
"answer_id": 355337,
"author": "Michel Moraes",
"author_id": 109142,
"author_profile": "https://wordpress.stackexchange.com/users/109142",
"pm_score": 0,
"selected": false,
"text": "<p>You can simple use wp data api to get the default class name of your block like this:</p>\n\n<pre><code>const className = getBlockDefaultClassName(\"namespace/yourblockname\");\n</code></pre>\n\n<p><strong>getBlockDefaultClassName</strong> is from <strong>wp.blocks</strong> so you can import it:</p>\n\n<pre><code>import { getBlockDefaultClassName } from \"@wordpress/blocks\";\n</code></pre>\n\n<p>or</p>\n\n<pre><code>const { getBlockDefaultClassName } = wp.blocks;\n</code></pre>\n\n<p>Hope it helps!</p>\n"
}
] | 2019/03/02 | [
"https://wordpress.stackexchange.com/questions/330471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111085/"
] | I'm using a filter in the Block API to add a class name to a block's wrapper. I have to add the class name to a specific block, not all blocks.
I tried:
```
const addClassName = createHigherOrderComponent( ( BlockListBlock ) => {
return ( props, blockType ) => {
if ( blockType.name === 'myplugin/myblock' ) {
return <BlockListBlock { ...props } className="test" />;
}
return <BlockListBlock { ...props } />
}
}, 'addClassName' );
wp.hooks.addFilter( 'editor.BlockListBlock', 'myplugin/add-class-name', addClassName );
```
The issue: `blockType.name` returns undefined. I also tried `getBlockType.name` and it also returns undefined. I also tried getting the block name of core blocks. For example `core/columns`. | From the props object we can get the block information. The object contains the `name` property you are looking for; this would be the code:
```
const addClassName = createHigherOrderComponent(BlockListBlock => {
return props => {
if (props.name === "myplugin/myblock") {
return <BlockListBlock {...props} className="test" />;
}
return <BlockListBlock {...props} />;
};
}, "addClassName");
wp.hooks.addFilter(
"editor.BlockListBlock",
"myplugin/add-class-name",
addClassName
);
``` |
330,527 | <p>Is anyone aware of means to add html directly under the body tag on the wordpress login page, ideally using functions.php? </p>
<p>I'm aware of the various hooks and filters listed in the codex, but I have a use case which requires a simple line of html be present across the whole site and after several hours of research I'm no further forward.</p>
| [
{
"answer_id": 330528,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 2,
"selected": false,
"text": "<p>If you look the <strong>wp-login.php</strong> file, you will see a hook <strong>login_header</strong>. So you add any custom content above the login form. Here is the example:</p>\n\n<pre><code>add_action( 'login_header', 'wpse330527_add_html_content' );\nfunction wpse330527_add_html_content() {\n?>\n\nENTER YOUR HTML CODE\n\n<?php\n}\n</code></pre>\n\n<p>You will add the code into functions.php file of your active theme.</p>\n"
},
{
"answer_id": 391018,
"author": "Benjamin",
"author_id": 195438,
"author_profile": "https://wordpress.stackexchange.com/users/195438",
"pm_score": 1,
"selected": false,
"text": "<h3>Some notes</h3>\n<p>You may notice that the <code>login_init</code> hook puts the code <em>immediately</em> under the body tag, and the <code>login_header</code> code is inserted later. Other tags are described in the <a href=\"https://codex.wordpress.org/Customizing_the_Login_Form#Login_Hooks\" rel=\"nofollow noreferrer\">documentation, here</a>:</p>\n<ul>\n<li>Actions in the <strong>head</strong> of the document: login_enqueue_scripts, login_head.</li>\n<li>Filters in the <strong>body</strong>: login_headerurl, login_headertitle, login_message, login_errors.</li>\n<li>Actions at the bottom of and below the form: login_form, login_footer.</li>\n</ul>\n<h3>The Code:</h3>\n<pre class=\"lang-php prettyprint-override\"><code>// define the login_init callback \nfunction action_login_init( $array ) { ?>\n <h1 class='even-above-login_header'>hi</h1>\n<?php }; \n \n// add the action \nadd_action( 'login_init', 'action_login_init', 10, 1 ); \n</code></pre>\n<h3>The Result:</h3>\n<pre class=\"lang-html prettyprint-override\"><code><body>\n <h1 class="even-above-login_header">hi</h1>\n <!-- etc -->\n</body>\n</code></pre>\n"
}
] | 2019/03/03 | [
"https://wordpress.stackexchange.com/questions/330527",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3782/"
] | Is anyone aware of means to add html directly under the body tag on the wordpress login page, ideally using functions.php?
I'm aware of the various hooks and filters listed in the codex, but I have a use case which requires a simple line of html be present across the whole site and after several hours of research I'm no further forward. | If you look the **wp-login.php** file, you will see a hook **login\_header**. So you add any custom content above the login form. Here is the example:
```
add_action( 'login_header', 'wpse330527_add_html_content' );
function wpse330527_add_html_content() {
?>
ENTER YOUR HTML CODE
<?php
}
```
You will add the code into functions.php file of your active theme. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.