qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
196,471 |
<p>I removed/unregistered the theme (BirdTIPS) header images, but the default header image is still displayed. How to remove it programmatically (not css or editing header.php)?</p>
<p>My code:</p>
<pre><code>add_action( 'after_setup_theme', 'remove_default_headers', 11 );
function remove_default_headers() {
remove_theme_support( 'custom-header', array(
'default-image',
) );
unregister_default_headers(
array(
'green',
'blue',
'yellow',
'red',
'white',
'orange',
'pink',
'purple'
)
);
}
</code></pre>
<p>In the header block of the header.php there is this code (I want to avoid to edit it, nor in the child theme):</p>
<pre><code> <?php if ( ! empty( $birdtips_header_image ) ) : ?>
<?php if ( 'blank' == get_header_textcolor() ): ?>
<a href="<?php echo home_url( '/' ); ?>"><img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" ></a>
<?php else: ?>
<img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" >
<?php endif; ?>
<?php endif; ?>
</code></pre>
|
[
{
"answer_id": 196473,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>When I started out with Wordpress I was anti-plugin. I wanted to add everything in my theme's <code>functions.php</code>. When I looked at the bigger picture it began making sense having and leaving some functionalities inside a plugin. </p>\n\n<p>There are many write-ups on the subject of what should go into a plugin and what should go into a theme. I, for one, have done one or two posts on this subject, so do yourself the favor and read up on this. I believe it will be very helpful and insightful. </p>\n\n<p>Functions in a plugin and functions in a theme's <code>functions.php</code> does exactly the same job, there is no difference. The only thing is, you cannot declare a function in plugin <strong>and</strong> redeclare it in your theme. This will throw a fatal error crashing the site</p>\n\n<p>To answer your issue, yes, if you think logically about this, your functionality should go into a plugin as this gives functionality to your site, and not the theme. This is functionality that you would need when you switch themes. It is just easier in plugin as you don't need to write or copy this code over and over again into a new theme. </p>\n\n<p>But the choice is still yours. Adding it to your theme is your own choice, although, as I said, not really recommended. But either way, the code will work perfectly fine in a theme and in a plugin, so the choice is yours to make where to add it</p>\n"
},
{
"answer_id": 196476,
"author": "Bora Yalcin",
"author_id": 77039,
"author_profile": "https://wordpress.stackexchange.com/users/77039",
"pm_score": 1,
"selected": false,
"text": "<p>I didn't do this recently but in 2014, in a few WordPress projects that I need additional tables I used Laravel components. </p>\n\n<p>In WordPress, if you want to create your own tables by using wpdb and mysql queries. But with the Laravel database classes I managed to do this much more elegantly.</p>\n\n<p>A quick rundown how I do this: \n(note: At the time, I used Laravel 4 components, I haven't tried with 5)</p>\n\n<pre><code>\"require\": {\n \"illuminate/database\": \"*\",\n \"illuminate/container\": \"*\",\n \"shuber/curl\": \"dev-master\",\n \"sunra/php-simple-html-dom-parser\": \"v1.5.0\"\n\n},\n</code></pre>\n\n<p>I installed the necessary packages (first two) with composer in functions.php (or in a functionality plugin)</p>\n\n<p>I used it for saving an index of magazine articles content, a Recorder class (not very SOLID approach, sorry)</p>\n\n<pre><code><?php\nnamespace Dion\\Volumes;\n\nuse Illuminate\\Database\\Capsule\\Manager as Capsule;\n\n\nclass Recorder {\n\n\n public static $table = 'volume_content';\n\n public function __construct(Page $page){\n $this->recordPage($page);\n }\n\n public static function createTables()\n {\n if( ! Capsule::schema()->hasTable(static::$table) ) {\n\n Capsule::schema()->create(static::$table, function($table) {\n $table->increments('id');\n $table->string('volume');\n $table->integer('month');\n $table->integer('year');\n $table->integer('page');\n $table->longtext('page_content');\n });\n }\n }\n\n\n public function recordPage($page)\n {\n //check if exists\n $exists = Capsule::table(static::$table)->where('volume',$page->volume)\n ->where('page',$page->page)->get();\n\n\n if( empty( $exists ) ) {\n\n $insert = Capsule::table(static::$table)->insert($page->toArray());\n } else {\n $update = Capsule::table(static::$table)->where('volume',$page->volume)\n ->where('page',$page->page)\n ->update($page->toArray());\n }\n }\n}\n</code></pre>\n\n<p>and in the functions.php I added the Laravel database component and made it work like this.</p>\n\n<pre><code>global $wpdb;\n$capsule = new Capsule;\n\n$capsule->addConnection(array(\n 'driver' => 'mysql',\n 'host' => DB_HOST,\n 'database' => DB_NAME,\n 'username' => DB_USER,\n 'password' => DB_PASSWORD,\n 'prefix' => $wpdb->prefix,\n 'charset' => DB_CHARSET,\n 'collation' => 'utf8_unicode_ci',\n));\n\n\n$capsule->bootEloquent();\n\n// Make this Capsule instance available globally via static methods... (optional)\n$capsule->setAsGlobal();\n\n//this one creates table if not exists. Its better to run it in a WP action, like admin_init\n$createVolumes = Dion\\Volumes\\Recorder::createTables();\n</code></pre>\n\n<p>Hope it helps, if you like this solution and have questions, I'll be happy to add more.</p>\n"
},
{
"answer_id": 196478,
"author": "Oleg Butuzov",
"author_id": 14536,
"author_profile": "https://wordpress.stackexchange.com/users/14536",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>can I just create one using PHPMYADMIN ? </p>\n</blockquote>\n\n<p>Yes.You can. And its a shortest way to do it.</p>\n"
}
] |
2015/08/03
|
[
"https://wordpress.stackexchange.com/questions/196471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25187/"
] |
I removed/unregistered the theme (BirdTIPS) header images, but the default header image is still displayed. How to remove it programmatically (not css or editing header.php)?
My code:
```
add_action( 'after_setup_theme', 'remove_default_headers', 11 );
function remove_default_headers() {
remove_theme_support( 'custom-header', array(
'default-image',
) );
unregister_default_headers(
array(
'green',
'blue',
'yellow',
'red',
'white',
'orange',
'pink',
'purple'
)
);
}
```
In the header block of the header.php there is this code (I want to avoid to edit it, nor in the child theme):
```
<?php if ( ! empty( $birdtips_header_image ) ) : ?>
<?php if ( 'blank' == get_header_textcolor() ): ?>
<a href="<?php echo home_url( '/' ); ?>"><img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" ></a>
<?php else: ?>
<img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" >
<?php endif; ?>
<?php endif; ?>
```
|
When I started out with Wordpress I was anti-plugin. I wanted to add everything in my theme's `functions.php`. When I looked at the bigger picture it began making sense having and leaving some functionalities inside a plugin.
There are many write-ups on the subject of what should go into a plugin and what should go into a theme. I, for one, have done one or two posts on this subject, so do yourself the favor and read up on this. I believe it will be very helpful and insightful.
Functions in a plugin and functions in a theme's `functions.php` does exactly the same job, there is no difference. The only thing is, you cannot declare a function in plugin **and** redeclare it in your theme. This will throw a fatal error crashing the site
To answer your issue, yes, if you think logically about this, your functionality should go into a plugin as this gives functionality to your site, and not the theme. This is functionality that you would need when you switch themes. It is just easier in plugin as you don't need to write or copy this code over and over again into a new theme.
But the choice is still yours. Adding it to your theme is your own choice, although, as I said, not really recommended. But either way, the code will work perfectly fine in a theme and in a plugin, so the choice is yours to make where to add it
|
196,502 |
<p>I am trying to retrieve some custom post type from their specific parent category.</p>
<pre><code> <div class="tab-content">
<?php
$cat_menu = get_categories('taxonomy=menu_categorie&type=menus');
foreach($cat_menu as $menu) {
echo '<div role="tabpanel" class="tab-pane active fade" id="'.$menu->slug.'">';
$id = (int) $menu->cat_ID;
$args = array(
'post_type' => 'menus',
'post_status' => 'publish',
'cat' => $id
);
$recipes = new WP_Query($args);
if($recipes->have_posts()) : while($recipes->have_posts()) : $recipes->the_post();
echo the_title();
endwhile; endif;
echo '</div>';
}
?>
</div>
</code></pre>
<p>if I remove, in the array $args, the key 'cat', it will work but it will output ALL my menu. What I want is to be able to output my menu post type from the category_id, but I have nothing that shows up. So I guess $recipes have nothing in it, then fails. </p>
<p>Is there something I missed out to retrieve custom post type with a specific category id?</p>
|
[
{
"answer_id": 196506,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 2,
"selected": false,
"text": "<p>From what u have written so far it seems <code>menu_categorie</code> is the custom taxonomy. Make sure it is this only. I get a feeling that you have misses \"s\" from the end of <code>menu_categorie</code></p>\n\n<p>Anyways </p>\n\n<p>The argument <code>'cat' => $id</code> you were using is used for default taxonomy i.e <code>category</code>.</p>\n\n<p>But in your case you have custom taxonomy <code>menu_categorie</code>.</p>\n\n<p>So you need to use the tax_query.</p>\n\n<p>So this is how your code will look.</p>\n\n<pre><code><div class=\"tab-content\">\n<?php \n $cat_menu = get_categories('taxonomy=menu_categorie&type=menus');\n foreach($cat_menu as $menu) {\n echo '<div role=\"tabpanel\" class=\"tab-pane active fade\" id=\"'.$menu->slug.'\">';\n $id = (int) $menu->cat_ID;\n $args = array(\n 'post_type' => 'menus',\n 'post_status' => 'publish',\n 'tax_query' =>\n array(\n array(\n 'taxonomy' => 'menu_categorie',\n 'field' => 'id',\n 'terms' => $id\n ),\n ), \n );\n $recipes = new WP_Query($args);\n if($recipes->have_posts()) : while($recipes->have_posts()) : $recipes->the_post();\n echo the_title();\n endwhile; endif;\n echo '</div>';\n }\n?>\n</div>\n</code></pre>\n\n<p>This should work . If it doesn't please let me know</p>\n"
},
{
"answer_id": 333847,
"author": "Андрей Гаврилов",
"author_id": 164723,
"author_profile": "https://wordpress.stackexchange.com/users/164723",
"pm_score": -1,
"selected": false,
"text": "<p>use</p>\n\n<pre><code> <?php $category = get_queried_object();\n $categoryOne = $category->term_id;\n $args = array(\n 'post_type' => 'iy-portfolio',\n 'posts_per_page' => 6,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'portfolio-categories',\n 'field' => 'term_id',\n 'terms' => $categoryOne\n ),\n )\n );\n $property = new WP_query( $args );\n\n if( $property->have_posts() ) : ?>\n <?php while( $property->have_posts() ) :\n $property->the_post(); ?>\n <article id=\"post-<?php the_ID(); ?>\" class=\"post-catalog-news col-lg-6\">\n <a href=\"<?=get_permalink() ?>\">\n <?php\n $size = array( 370, 240);\n the_post_thumbnail( $size ); ?>\n <h2 class=\"title-catalog\"><?php the_title(); ?></h2>\n <? if (get_field('preview_post')) { ?>\n <div class=\"preview_post_catalog\">\n <? the_field('preview_post') ?>\n </div>\n <? } ?>\n </a>\n </article>\n <?php endwhile;\n</code></pre>\n"
}
] |
2015/08/03
|
[
"https://wordpress.stackexchange.com/questions/196502",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66181/"
] |
I am trying to retrieve some custom post type from their specific parent category.
```
<div class="tab-content">
<?php
$cat_menu = get_categories('taxonomy=menu_categorie&type=menus');
foreach($cat_menu as $menu) {
echo '<div role="tabpanel" class="tab-pane active fade" id="'.$menu->slug.'">';
$id = (int) $menu->cat_ID;
$args = array(
'post_type' => 'menus',
'post_status' => 'publish',
'cat' => $id
);
$recipes = new WP_Query($args);
if($recipes->have_posts()) : while($recipes->have_posts()) : $recipes->the_post();
echo the_title();
endwhile; endif;
echo '</div>';
}
?>
</div>
```
if I remove, in the array $args, the key 'cat', it will work but it will output ALL my menu. What I want is to be able to output my menu post type from the category\_id, but I have nothing that shows up. So I guess $recipes have nothing in it, then fails.
Is there something I missed out to retrieve custom post type with a specific category id?
|
From what u have written so far it seems `menu_categorie` is the custom taxonomy. Make sure it is this only. I get a feeling that you have misses "s" from the end of `menu_categorie`
Anyways
The argument `'cat' => $id` you were using is used for default taxonomy i.e `category`.
But in your case you have custom taxonomy `menu_categorie`.
So you need to use the tax\_query.
So this is how your code will look.
```
<div class="tab-content">
<?php
$cat_menu = get_categories('taxonomy=menu_categorie&type=menus');
foreach($cat_menu as $menu) {
echo '<div role="tabpanel" class="tab-pane active fade" id="'.$menu->slug.'">';
$id = (int) $menu->cat_ID;
$args = array(
'post_type' => 'menus',
'post_status' => 'publish',
'tax_query' =>
array(
array(
'taxonomy' => 'menu_categorie',
'field' => 'id',
'terms' => $id
),
),
);
$recipes = new WP_Query($args);
if($recipes->have_posts()) : while($recipes->have_posts()) : $recipes->the_post();
echo the_title();
endwhile; endif;
echo '</div>';
}
?>
</div>
```
This should work . If it doesn't please let me know
|
196,508 |
<p>I have googled this a few different ways, but cannot find the answer I'm looking for. I want to be able to count the number of posts each author has within a custom post type. Any suggestions would be really appreciated</p>
|
[
{
"answer_id": 196510,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 1,
"selected": true,
"text": "<p>i found this code wordpress.org . This code would work in author template.</p>\n\n<pre><code><?php\nglobal $wp_query;\n$curauth = $wp_query->get_queried_object();\n$post_count = $wpdb->get_var(\"SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '\" . $curauth->ID . \"' AND post_type = 'post' AND post_status = 'publish'\");\n?>\n<h2>Post Count: <?php echo $post_count; ?></h2>\n</code></pre>\n\n<p>But if you wish to use it somewhere else then replace <code>$curauth->ID</code> with author id and <code>post</code> with the post type you want</p>\n\n<p>it should work .\nAll the best</p>\n"
},
{
"answer_id": 307563,
"author": "inrsaurabh",
"author_id": 116990,
"author_profile": "https://wordpress.stackexchange.com/users/116990",
"pm_score": 0,
"selected": false,
"text": "<pre><code> if you're on a single post, it will return the post object\n if you're on a page, it will return the page object\n if you're on an archive page, it will return the post type object\n if you're on a category archive, it will return the category object\n if you're on an author archive, it will return the author object\netc.\n</code></pre>\n\n<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow noreferrer\">query-object</a> as suggested by @terminator</p>\n\n<p>In place of using sql query use <a href=\"https://developer.wordpress.org/reference/functions/count_user_posts/\" rel=\"nofollow noreferrer\">count_user_posts</a></p>\n\n<pre><code> $queried_object = get_queried_object();\n count_user_posts($queried_object->ID, 'custom_post_type_here');\n</code></pre>\n"
},
{
"answer_id": 327570,
"author": "kwiz",
"author_id": 160458,
"author_profile": "https://wordpress.stackexchange.com/users/160458",
"pm_score": 0,
"selected": false,
"text": "<p>Create a function in <code>functions.php</code></p>\n\n<pre><code> function count_posts_by_author($post_type){\n global $wp_query;\n $curauth = $wp_query->get_queried_object();\n $args = array(\n 'post_type' => $post_type,\n 'author' => $curauth->ID,\n 'posts_per_page' => -1 // no limit\n );\n echo count(get_posts($args));\n }\n</code></pre>\n\n<p>and just call the function in your template file </p>\n\n<pre><code><?php count_posts_by_author('Your post type or custom post type');?>\n</code></pre>\n"
},
{
"answer_id": 361313,
"author": "Abouasy",
"author_id": 48786,
"author_profile": "https://wordpress.stackexchange.com/users/48786",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\n// get author ID\n$author_id = get_the_author_meta( 'ID' ); \n\n// echo count for post type (post and book)\necho count_user_posts( $author_id , ['post','book'] ); \n\n?>\n</code></pre>\n"
}
] |
2015/08/03
|
[
"https://wordpress.stackexchange.com/questions/196508",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77226/"
] |
I have googled this a few different ways, but cannot find the answer I'm looking for. I want to be able to count the number of posts each author has within a custom post type. Any suggestions would be really appreciated
|
i found this code wordpress.org . This code would work in author template.
```
<?php
global $wp_query;
$curauth = $wp_query->get_queried_object();
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'post' AND post_status = 'publish'");
?>
<h2>Post Count: <?php echo $post_count; ?></h2>
```
But if you wish to use it somewhere else then replace `$curauth->ID` with author id and `post` with the post type you want
it should work .
All the best
|
196,521 |
<p>I want to run a PHP script that iterates over WordPress sites found in a certain folder and read the plugins info per each site using get_plugin function</p>
<p>In the code below, I try to require API functions inside the WP folder and use it to retrieve data. However, the problem is the multiple "require".</p>
<p>Sample code:</p>
<pre><code>function get_sites_plugins() {
foreach($this->all_sites as $site_folder) {
$plugins = get_site_plugins($site_folder);
echo "Info for site $site_folder";
var_dump($plugins);
}
}
function get_site_plugins($site_folder) {
// define site path
$site_path = $CONST_SITES_DIR . $site_folder;
// defines ABSPATH
require("$site_path/wp-load.php");
// define get_plugins()
require ABSPATH . 'wp-admin/includes/plugin.php';
// PROBLEM: only first require works, need to "unrequire" but that's not possible.
// get plugins
$all_plugins = get_plugins();
return $all_plugins;
}
get_sites_plugins();
</code></pre>
<p>How do I achieve this?</p>
<p><strong>Note</strong> that the PHP script running is on the same host server.</p>
|
[
{
"answer_id": 196510,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 1,
"selected": true,
"text": "<p>i found this code wordpress.org . This code would work in author template.</p>\n\n<pre><code><?php\nglobal $wp_query;\n$curauth = $wp_query->get_queried_object();\n$post_count = $wpdb->get_var(\"SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '\" . $curauth->ID . \"' AND post_type = 'post' AND post_status = 'publish'\");\n?>\n<h2>Post Count: <?php echo $post_count; ?></h2>\n</code></pre>\n\n<p>But if you wish to use it somewhere else then replace <code>$curauth->ID</code> with author id and <code>post</code> with the post type you want</p>\n\n<p>it should work .\nAll the best</p>\n"
},
{
"answer_id": 307563,
"author": "inrsaurabh",
"author_id": 116990,
"author_profile": "https://wordpress.stackexchange.com/users/116990",
"pm_score": 0,
"selected": false,
"text": "<pre><code> if you're on a single post, it will return the post object\n if you're on a page, it will return the page object\n if you're on an archive page, it will return the post type object\n if you're on a category archive, it will return the category object\n if you're on an author archive, it will return the author object\netc.\n</code></pre>\n\n<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow noreferrer\">query-object</a> as suggested by @terminator</p>\n\n<p>In place of using sql query use <a href=\"https://developer.wordpress.org/reference/functions/count_user_posts/\" rel=\"nofollow noreferrer\">count_user_posts</a></p>\n\n<pre><code> $queried_object = get_queried_object();\n count_user_posts($queried_object->ID, 'custom_post_type_here');\n</code></pre>\n"
},
{
"answer_id": 327570,
"author": "kwiz",
"author_id": 160458,
"author_profile": "https://wordpress.stackexchange.com/users/160458",
"pm_score": 0,
"selected": false,
"text": "<p>Create a function in <code>functions.php</code></p>\n\n<pre><code> function count_posts_by_author($post_type){\n global $wp_query;\n $curauth = $wp_query->get_queried_object();\n $args = array(\n 'post_type' => $post_type,\n 'author' => $curauth->ID,\n 'posts_per_page' => -1 // no limit\n );\n echo count(get_posts($args));\n }\n</code></pre>\n\n<p>and just call the function in your template file </p>\n\n<pre><code><?php count_posts_by_author('Your post type or custom post type');?>\n</code></pre>\n"
},
{
"answer_id": 361313,
"author": "Abouasy",
"author_id": 48786,
"author_profile": "https://wordpress.stackexchange.com/users/48786",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\n// get author ID\n$author_id = get_the_author_meta( 'ID' ); \n\n// echo count for post type (post and book)\necho count_user_posts( $author_id , ['post','book'] ); \n\n?>\n</code></pre>\n"
}
] |
2015/08/03
|
[
"https://wordpress.stackexchange.com/questions/196521",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73742/"
] |
I want to run a PHP script that iterates over WordPress sites found in a certain folder and read the plugins info per each site using get\_plugin function
In the code below, I try to require API functions inside the WP folder and use it to retrieve data. However, the problem is the multiple "require".
Sample code:
```
function get_sites_plugins() {
foreach($this->all_sites as $site_folder) {
$plugins = get_site_plugins($site_folder);
echo "Info for site $site_folder";
var_dump($plugins);
}
}
function get_site_plugins($site_folder) {
// define site path
$site_path = $CONST_SITES_DIR . $site_folder;
// defines ABSPATH
require("$site_path/wp-load.php");
// define get_plugins()
require ABSPATH . 'wp-admin/includes/plugin.php';
// PROBLEM: only first require works, need to "unrequire" but that's not possible.
// get plugins
$all_plugins = get_plugins();
return $all_plugins;
}
get_sites_plugins();
```
How do I achieve this?
**Note** that the PHP script running is on the same host server.
|
i found this code wordpress.org . This code would work in author template.
```
<?php
global $wp_query;
$curauth = $wp_query->get_queried_object();
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'post' AND post_status = 'publish'");
?>
<h2>Post Count: <?php echo $post_count; ?></h2>
```
But if you wish to use it somewhere else then replace `$curauth->ID` with author id and `post` with the post type you want
it should work .
All the best
|
196,552 |
<p>I am new to wordpress and i am learning a lot. But i am making this intranet site and i need to make a form just like Facebook's update status where my logged in users will need to update their status or upload some images with a description on it. Then underneath that, i will need to have a comment section and like buttons.</p>
<p>I know i could use the create post form on the front page but the status won't be having a title. Attached is an image just to show what i am trying to achieve. Any ideas will be appreciated.<a href="https://i.stack.imgur.com/IPCr5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IPCr5.jpg" alt="This is a diagram of what i am trying to achieve"></a></p>
|
[
{
"answer_id": 196510,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 1,
"selected": true,
"text": "<p>i found this code wordpress.org . This code would work in author template.</p>\n\n<pre><code><?php\nglobal $wp_query;\n$curauth = $wp_query->get_queried_object();\n$post_count = $wpdb->get_var(\"SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '\" . $curauth->ID . \"' AND post_type = 'post' AND post_status = 'publish'\");\n?>\n<h2>Post Count: <?php echo $post_count; ?></h2>\n</code></pre>\n\n<p>But if you wish to use it somewhere else then replace <code>$curauth->ID</code> with author id and <code>post</code> with the post type you want</p>\n\n<p>it should work .\nAll the best</p>\n"
},
{
"answer_id": 307563,
"author": "inrsaurabh",
"author_id": 116990,
"author_profile": "https://wordpress.stackexchange.com/users/116990",
"pm_score": 0,
"selected": false,
"text": "<pre><code> if you're on a single post, it will return the post object\n if you're on a page, it will return the page object\n if you're on an archive page, it will return the post type object\n if you're on a category archive, it will return the category object\n if you're on an author archive, it will return the author object\netc.\n</code></pre>\n\n<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow noreferrer\">query-object</a> as suggested by @terminator</p>\n\n<p>In place of using sql query use <a href=\"https://developer.wordpress.org/reference/functions/count_user_posts/\" rel=\"nofollow noreferrer\">count_user_posts</a></p>\n\n<pre><code> $queried_object = get_queried_object();\n count_user_posts($queried_object->ID, 'custom_post_type_here');\n</code></pre>\n"
},
{
"answer_id": 327570,
"author": "kwiz",
"author_id": 160458,
"author_profile": "https://wordpress.stackexchange.com/users/160458",
"pm_score": 0,
"selected": false,
"text": "<p>Create a function in <code>functions.php</code></p>\n\n<pre><code> function count_posts_by_author($post_type){\n global $wp_query;\n $curauth = $wp_query->get_queried_object();\n $args = array(\n 'post_type' => $post_type,\n 'author' => $curauth->ID,\n 'posts_per_page' => -1 // no limit\n );\n echo count(get_posts($args));\n }\n</code></pre>\n\n<p>and just call the function in your template file </p>\n\n<pre><code><?php count_posts_by_author('Your post type or custom post type');?>\n</code></pre>\n"
},
{
"answer_id": 361313,
"author": "Abouasy",
"author_id": 48786,
"author_profile": "https://wordpress.stackexchange.com/users/48786",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\n// get author ID\n$author_id = get_the_author_meta( 'ID' ); \n\n// echo count for post type (post and book)\necho count_user_posts( $author_id , ['post','book'] ); \n\n?>\n</code></pre>\n"
}
] |
2015/08/04
|
[
"https://wordpress.stackexchange.com/questions/196552",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76635/"
] |
I am new to wordpress and i am learning a lot. But i am making this intranet site and i need to make a form just like Facebook's update status where my logged in users will need to update their status or upload some images with a description on it. Then underneath that, i will need to have a comment section and like buttons.
I know i could use the create post form on the front page but the status won't be having a title. Attached is an image just to show what i am trying to achieve. Any ideas will be appreciated.[](https://i.stack.imgur.com/IPCr5.jpg)
|
i found this code wordpress.org . This code would work in author template.
```
<?php
global $wp_query;
$curauth = $wp_query->get_queried_object();
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'post' AND post_status = 'publish'");
?>
<h2>Post Count: <?php echo $post_count; ?></h2>
```
But if you wish to use it somewhere else then replace `$curauth->ID` with author id and `post` with the post type you want
it should work .
All the best
|
196,565 |
<p>I am trying to create a page that shows all users with a selection of details. One of those details is the user role it has. For each role I want to display a different string. In order to achieve this is have the following code:</p>
<pre><code>function smoelenboek_func(){
$users = get_users('orderby=nicename');
foreach ($users as $user) {
switch ($user->roles[0]) {
case 'administrator' :
echo 'Yes';
case 'member' :
echo 'No';
case 'oldmember' :
echo 'Maybe';
};
};
};
</code></pre>
<p>Now the strange thing that happens is, users with an administrator role get output "YesNoMaybe", a member role gets "NoMaybe" and oldmember gets "Maybe". Am I using the Switch-Case incorrectly? Is there something in the roles array that I'm misinterpreting? Any help is hugely appreciated. </p>
|
[
{
"answer_id": 196566,
"author": "Webloper",
"author_id": 29035,
"author_profile": "https://wordpress.stackexchange.com/users/29035",
"pm_score": 1,
"selected": true,
"text": "<p>You missed break statement</p>\n\n<p>This is how switch case works</p>\n\n<pre><code>switch ($i) {\n case \"apple\":\n echo \"i is apple\";\n break;\n case \"bar\":\n echo \"i is bar\";\n break;\n case \"cake\":\n echo \"i is cake\";\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 196571,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": -1,
"selected": false,
"text": "<p>Your code is missing break and also your requirement is like below:</p>\n\n<p>If administrator, <code>YesNoMaybe</code> OR if member, <code>NoMaybe</code> OR if <code>oldmember</code>, Maybe.</p>\n\n<p>Finally code is look like Below:</p>\n\n<pre><code>function smoelenboek_func(){\n $users = get_users('orderby=nicename');\n foreach ($users as $user) {\n switch ($user->roles[0]) {\n case 'administrator' :\n echo 'YesNoMaybe';\n break;\n case 'member' :\n echo 'NoMaybe';\n break;\n case 'oldmember' :\n echo 'Maybe';\n break;\n };\n };\n};\n</code></pre>\n\n<p>I hope this may help you well.</p>\n\n<p>P.S. Let me know if you have any query/concern regarding this.</p>\n"
}
] |
2015/08/04
|
[
"https://wordpress.stackexchange.com/questions/196565",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74864/"
] |
I am trying to create a page that shows all users with a selection of details. One of those details is the user role it has. For each role I want to display a different string. In order to achieve this is have the following code:
```
function smoelenboek_func(){
$users = get_users('orderby=nicename');
foreach ($users as $user) {
switch ($user->roles[0]) {
case 'administrator' :
echo 'Yes';
case 'member' :
echo 'No';
case 'oldmember' :
echo 'Maybe';
};
};
};
```
Now the strange thing that happens is, users with an administrator role get output "YesNoMaybe", a member role gets "NoMaybe" and oldmember gets "Maybe". Am I using the Switch-Case incorrectly? Is there something in the roles array that I'm misinterpreting? Any help is hugely appreciated.
|
You missed break statement
This is how switch case works
```
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
}
```
|
196,567 |
<p>I have written a function in <code>functions.php</code> that gets variables from a contact form and sends the inputs (and some other info like IP and location..) to my email. </p>
<p>I am starting to work on my first plugin and I want to store the parameters in a new table on the database. </p>
<p>How do I get the parameters from <code>function.php</code> right after the user clicks on the <strong>send</strong> button of the <code>contact form</code>? </p>
|
[
{
"answer_id": 196568,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 1,
"selected": false,
"text": "<p>Basic PHP:</p>\n\n<p><strong>functions.php</strong>:</p>\n\n<pre><code>function my_func() {\n //doing my staff\n $my_var = 'data'; //stored data after doing things\n return $my_var;\n}\n</code></pre>\n\n<p>In plugin file:</p>\n\n<pre><code>//retrieved data from a function declared within a system\n$got_data = my_func();\n\nfunction another_func( $got_data ) {\n //doing staff with $got_data\n}\n</code></pre>\n"
},
{
"answer_id": 196573,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 2,
"selected": false,
"text": "<p>There is three way to use <code>function.php</code> file variable into plugin file.</p>\n\n<ol>\n<li><p>Using <a href=\"https://codex.wordpress.org/Global_Variables\" rel=\"nofollow\">global</a>. Make sure you globalize it first.</p>\n\n<p><code>global $my_variable;\necho $my_variable;</code></p></li>\n<li><p>I recommend is using WordPress built-in filter mechanism <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow\">add_filter</a>. You add the filter in your <code>functions.php</code> file and apply it where needed.</p></li>\n</ol>\n\n<p>In <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'my_variable', 'return_my_variable' );\nfunction return_my_variable( $arg = '' ) {\n return '111221122';\n}\n</code></pre>\n\n<p>Now you can use in your plugin files:</p>\n\n<pre><code>echo apply_filters( 'my_variable', '' );\n</code></pre>\n\n<ol start=\"3\">\n<li>Use an action hook <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow\">add_action</a></li>\n</ol>\n\n<p>In <code>functions.php</code>:</p>\n\n<pre><code>add_action( 'my_variable', 'echo_my_variable' );\nfunction echo_my_variable() {\n echo '888998899';\n}\n</code></pre>\n\n<p>In your plugin files:</p>\n\n<pre><code>do_action( 'my_variable' );\n</code></pre>\n\n<p>Again, I recommend a filter because it can return a value. This is far more flexible than injecting echo calls in your plugin file. Whether you use an action hook or a filter is entirely up to you.</p>\n"
}
] |
2015/08/04
|
[
"https://wordpress.stackexchange.com/questions/196567",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75062/"
] |
I have written a function in `functions.php` that gets variables from a contact form and sends the inputs (and some other info like IP and location..) to my email.
I am starting to work on my first plugin and I want to store the parameters in a new table on the database.
How do I get the parameters from `function.php` right after the user clicks on the **send** button of the `contact form`?
|
There is three way to use `function.php` file variable into plugin file.
1. Using [global](https://codex.wordpress.org/Global_Variables). Make sure you globalize it first.
`global $my_variable;
echo $my_variable;`
2. I recommend is using WordPress built-in filter mechanism [add\_filter](https://developer.wordpress.org/reference/functions/add_filter/). You add the filter in your `functions.php` file and apply it where needed.
In `functions.php`:
```
add_filter( 'my_variable', 'return_my_variable' );
function return_my_variable( $arg = '' ) {
return '111221122';
}
```
Now you can use in your plugin files:
```
echo apply_filters( 'my_variable', '' );
```
3. Use an action hook [add\_action](https://developer.wordpress.org/reference/functions/add_action/)
In `functions.php`:
```
add_action( 'my_variable', 'echo_my_variable' );
function echo_my_variable() {
echo '888998899';
}
```
In your plugin files:
```
do_action( 'my_variable' );
```
Again, I recommend a filter because it can return a value. This is far more flexible than injecting echo calls in your plugin file. Whether you use an action hook or a filter is entirely up to you.
|
196,577 |
<p>I was working on my MacOS System with everything well configured and working. Now I try to migrate all of my work to Windows using the same software as in MacOS MAMP to run Wordpress on localhost. So I set up MAMP on my Windows System and copied all files from GitHub to my workstation on Windows.</p>
<p>The problem is, when I try to access to my Wordpress Project on my localhost, I get the error:</p>
<p>"Error establishing a database connection"</p>
<p><a href="https://i.stack.imgur.com/p2tz0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p2tz0.png" alt="enter image description here"></a></p>
<p>I can not even have <code>wp-config.php</code> file and I can't get it.</p>
<p>Searching for <a href="https://wordpress.stackexchange.com/questions/56623/error-establishing-a-database-connection-when-migrating-site-to-localhost">similar</a> problems around here I have this <a href="http://www.wpkube.com/how-to-fix-error-establishing-database-connection-in-wordpress/" rel="nofollow noreferrer">link</a>, but is not the same solutions.</p>
|
[
{
"answer_id": 196568,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 1,
"selected": false,
"text": "<p>Basic PHP:</p>\n\n<p><strong>functions.php</strong>:</p>\n\n<pre><code>function my_func() {\n //doing my staff\n $my_var = 'data'; //stored data after doing things\n return $my_var;\n}\n</code></pre>\n\n<p>In plugin file:</p>\n\n<pre><code>//retrieved data from a function declared within a system\n$got_data = my_func();\n\nfunction another_func( $got_data ) {\n //doing staff with $got_data\n}\n</code></pre>\n"
},
{
"answer_id": 196573,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 2,
"selected": false,
"text": "<p>There is three way to use <code>function.php</code> file variable into plugin file.</p>\n\n<ol>\n<li><p>Using <a href=\"https://codex.wordpress.org/Global_Variables\" rel=\"nofollow\">global</a>. Make sure you globalize it first.</p>\n\n<p><code>global $my_variable;\necho $my_variable;</code></p></li>\n<li><p>I recommend is using WordPress built-in filter mechanism <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow\">add_filter</a>. You add the filter in your <code>functions.php</code> file and apply it where needed.</p></li>\n</ol>\n\n<p>In <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'my_variable', 'return_my_variable' );\nfunction return_my_variable( $arg = '' ) {\n return '111221122';\n}\n</code></pre>\n\n<p>Now you can use in your plugin files:</p>\n\n<pre><code>echo apply_filters( 'my_variable', '' );\n</code></pre>\n\n<ol start=\"3\">\n<li>Use an action hook <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow\">add_action</a></li>\n</ol>\n\n<p>In <code>functions.php</code>:</p>\n\n<pre><code>add_action( 'my_variable', 'echo_my_variable' );\nfunction echo_my_variable() {\n echo '888998899';\n}\n</code></pre>\n\n<p>In your plugin files:</p>\n\n<pre><code>do_action( 'my_variable' );\n</code></pre>\n\n<p>Again, I recommend a filter because it can return a value. This is far more flexible than injecting echo calls in your plugin file. Whether you use an action hook or a filter is entirely up to you.</p>\n"
}
] |
2015/08/04
|
[
"https://wordpress.stackexchange.com/questions/196577",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77261/"
] |
I was working on my MacOS System with everything well configured and working. Now I try to migrate all of my work to Windows using the same software as in MacOS MAMP to run Wordpress on localhost. So I set up MAMP on my Windows System and copied all files from GitHub to my workstation on Windows.
The problem is, when I try to access to my Wordpress Project on my localhost, I get the error:
"Error establishing a database connection"
[](https://i.stack.imgur.com/p2tz0.png)
I can not even have `wp-config.php` file and I can't get it.
Searching for [similar](https://wordpress.stackexchange.com/questions/56623/error-establishing-a-database-connection-when-migrating-site-to-localhost) problems around here I have this [link](http://www.wpkube.com/how-to-fix-error-establishing-database-connection-in-wordpress/), but is not the same solutions.
|
There is three way to use `function.php` file variable into plugin file.
1. Using [global](https://codex.wordpress.org/Global_Variables). Make sure you globalize it first.
`global $my_variable;
echo $my_variable;`
2. I recommend is using WordPress built-in filter mechanism [add\_filter](https://developer.wordpress.org/reference/functions/add_filter/). You add the filter in your `functions.php` file and apply it where needed.
In `functions.php`:
```
add_filter( 'my_variable', 'return_my_variable' );
function return_my_variable( $arg = '' ) {
return '111221122';
}
```
Now you can use in your plugin files:
```
echo apply_filters( 'my_variable', '' );
```
3. Use an action hook [add\_action](https://developer.wordpress.org/reference/functions/add_action/)
In `functions.php`:
```
add_action( 'my_variable', 'echo_my_variable' );
function echo_my_variable() {
echo '888998899';
}
```
In your plugin files:
```
do_action( 'my_variable' );
```
Again, I recommend a filter because it can return a value. This is far more flexible than injecting echo calls in your plugin file. Whether you use an action hook or a filter is entirely up to you.
|
196,586 |
<p>I'm trying to get into wordpress theme development. I currently work at agency which uses Roots framework and piklist. </p>
<p>I created a custom post type into which i wanted to add an icon from font-awesome.
I wanted a more userfriendly approach in the select box inside the metabox container.</p>
<p>i was suggested this: <a href="https://github.com/tommusrhodus/FontAwesome-4.3.0-Class-Names/blob/master/array.php" rel="nofollow">https://github.com/tommusrhodus/FontAwesome-4.3.0-Class-Names/blob/master/array.php</a></p>
<p>Which I got to work somewhat, the select box has more user friendly names for the classes, however i have trouble outputing them. This is the code i use for outputing it:</p>
<pre><code> $font_awesome_icon = get_post_meta(get_the_ID(), 'font-awesome-icon');
<i class="fa <?php echo $font_awesome_icon; ?>"></i>
</code></pre>
<p>This is what i get in the output:</p>
<pre><code><i class="fa <br />
<b>Notice</b>: Array to string conversion in <b>/home/html/grg.sk/public_html/_sub/dusan/dummytest/wp- content/themes/theme/templates/blocks/block-aboutus.php</b> on line <b>19</b><br />
Array"></i>
</code></pre>
<p>However if i add array with any attributes (that don't even exist suddenly it works. I found this out by mistake when adding array to the wrong line of code... :)</p>
<pre><code>$font_awesome_icon = get_post_meta(get_the_ID(), 'font-awesome-icon',array('size' => 'whatever'));
</code></pre>
<p>So can please anyone explain to me why this doesn't work?</p>
<p>I could also include the thread from piklist, but i'm not sure if that's allowed.</p>
|
[
{
"answer_id": 196568,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 1,
"selected": false,
"text": "<p>Basic PHP:</p>\n\n<p><strong>functions.php</strong>:</p>\n\n<pre><code>function my_func() {\n //doing my staff\n $my_var = 'data'; //stored data after doing things\n return $my_var;\n}\n</code></pre>\n\n<p>In plugin file:</p>\n\n<pre><code>//retrieved data from a function declared within a system\n$got_data = my_func();\n\nfunction another_func( $got_data ) {\n //doing staff with $got_data\n}\n</code></pre>\n"
},
{
"answer_id": 196573,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 2,
"selected": false,
"text": "<p>There is three way to use <code>function.php</code> file variable into plugin file.</p>\n\n<ol>\n<li><p>Using <a href=\"https://codex.wordpress.org/Global_Variables\" rel=\"nofollow\">global</a>. Make sure you globalize it first.</p>\n\n<p><code>global $my_variable;\necho $my_variable;</code></p></li>\n<li><p>I recommend is using WordPress built-in filter mechanism <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow\">add_filter</a>. You add the filter in your <code>functions.php</code> file and apply it where needed.</p></li>\n</ol>\n\n<p>In <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'my_variable', 'return_my_variable' );\nfunction return_my_variable( $arg = '' ) {\n return '111221122';\n}\n</code></pre>\n\n<p>Now you can use in your plugin files:</p>\n\n<pre><code>echo apply_filters( 'my_variable', '' );\n</code></pre>\n\n<ol start=\"3\">\n<li>Use an action hook <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow\">add_action</a></li>\n</ol>\n\n<p>In <code>functions.php</code>:</p>\n\n<pre><code>add_action( 'my_variable', 'echo_my_variable' );\nfunction echo_my_variable() {\n echo '888998899';\n}\n</code></pre>\n\n<p>In your plugin files:</p>\n\n<pre><code>do_action( 'my_variable' );\n</code></pre>\n\n<p>Again, I recommend a filter because it can return a value. This is far more flexible than injecting echo calls in your plugin file. Whether you use an action hook or a filter is entirely up to you.</p>\n"
}
] |
2015/08/04
|
[
"https://wordpress.stackexchange.com/questions/196586",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76716/"
] |
I'm trying to get into wordpress theme development. I currently work at agency which uses Roots framework and piklist.
I created a custom post type into which i wanted to add an icon from font-awesome.
I wanted a more userfriendly approach in the select box inside the metabox container.
i was suggested this: <https://github.com/tommusrhodus/FontAwesome-4.3.0-Class-Names/blob/master/array.php>
Which I got to work somewhat, the select box has more user friendly names for the classes, however i have trouble outputing them. This is the code i use for outputing it:
```
$font_awesome_icon = get_post_meta(get_the_ID(), 'font-awesome-icon');
<i class="fa <?php echo $font_awesome_icon; ?>"></i>
```
This is what i get in the output:
```
<i class="fa <br />
<b>Notice</b>: Array to string conversion in <b>/home/html/grg.sk/public_html/_sub/dusan/dummytest/wp- content/themes/theme/templates/blocks/block-aboutus.php</b> on line <b>19</b><br />
Array"></i>
```
However if i add array with any attributes (that don't even exist suddenly it works. I found this out by mistake when adding array to the wrong line of code... :)
```
$font_awesome_icon = get_post_meta(get_the_ID(), 'font-awesome-icon',array('size' => 'whatever'));
```
So can please anyone explain to me why this doesn't work?
I could also include the thread from piklist, but i'm not sure if that's allowed.
|
There is three way to use `function.php` file variable into plugin file.
1. Using [global](https://codex.wordpress.org/Global_Variables). Make sure you globalize it first.
`global $my_variable;
echo $my_variable;`
2. I recommend is using WordPress built-in filter mechanism [add\_filter](https://developer.wordpress.org/reference/functions/add_filter/). You add the filter in your `functions.php` file and apply it where needed.
In `functions.php`:
```
add_filter( 'my_variable', 'return_my_variable' );
function return_my_variable( $arg = '' ) {
return '111221122';
}
```
Now you can use in your plugin files:
```
echo apply_filters( 'my_variable', '' );
```
3. Use an action hook [add\_action](https://developer.wordpress.org/reference/functions/add_action/)
In `functions.php`:
```
add_action( 'my_variable', 'echo_my_variable' );
function echo_my_variable() {
echo '888998899';
}
```
In your plugin files:
```
do_action( 'my_variable' );
```
Again, I recommend a filter because it can return a value. This is far more flexible than injecting echo calls in your plugin file. Whether you use an action hook or a filter is entirely up to you.
|
196,594 |
<p>I want to know the best use of adding custom <code>JS/CSS</code> to a theme.</p>
<p>I have built a small plugin which has a section to allow users to add <code>CSS/JS</code> to their theme. Now I am trying to figure out is which is the best way to do this:</p>
<blockquote>
<ol>
<li><p>Save all of the code inside an custom DB and load this as plain code inside the header/footer.</p></li>
<li><p>Save all of the code inside an custom js/css file(no DB) and add the file inside the /header/footer</p></li>
</ol>
</blockquote>
<p>Notice: these custom JS/CSS files are custom build by the users so the user can add the own rules inside the plugin.</p>
<p>Which is the better, most secure solution?</p>
|
[
{
"answer_id": 196597,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": -1,
"selected": false,
"text": "<p>You've probably came across several different methods for including JavaScript and CSS.</p>\n\n<p>There is one primary method recommended in the <a href=\"http://codex.wordpress.org\" rel=\"nofollow\">WordPress Codex</a>.</p>\n\n<p>The safe and recommended method of adding JavaScript to a WordPress generated page, and WordPress Theme or Plugin, is by using <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">wp_enqueue_script()</a>. This function includes the script if it hasn't already been included, and safely handles dependencies. </p>\n\n<p>A safe way to add/enqueue a stylesheet file to the WordPress generated page. Use <code>wp_enqueue_style( $handle, $src, $deps, $ver, $media );</code> This function <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_style\" rel=\"nofollow\">wp_enqueue_style()</a> does not return a value.</p>\n"
},
{
"answer_id": 196604,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>I actually ran into a similar issue yesterday. A theme I was working with was adding 500+ lines of internal styles to the header which absolutely drives me nuts! I ended up finding a clever solution online to work around this which you could use for CSS. The JavaScript side I'll explain toward the bottom.</p>\n\n<p><strong>--- :: CSS :: ---</strong></p>\n\n<p>There's a few key points in how this code works. Since you need to handle variables in your CSS files we <em>need</em> to make sure the file given supports PHP <strong>and</strong> has access to WordPress functions so to get any presets. We cannot do this using a <code>.css</code> file alone so we need to fool the server into presenting our PHP file as CSS. </p>\n\n<p>This is purely for testing purposes: Create a file called <code>customcss.php</code> with the following code, note the PHP <a href=\"http://php.net/manual/en/function.header.php\" rel=\"nofollow\"><code>header()</code></a> function needed to tell the server we're going to show <code>text/css</code>:</p>\n\n<pre><code><?php\n header( \"Content-type: text/css; charset: UTF-8\" );\n $test = 'blue';\n?>\n\nbody {color: <?php echo $test; ?>;}\n</code></pre>\n\n<p>Next, we need to load this file in the context of WordPress so that we still have access to functions such as <code>get_post_meta()</code> or any <code>global</code> variables. Let's include this \"css\" file using <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow\">WP AJAX</a>. Note, when including or requiring we need to use absolute paths. This will look for your plugin folder and into the <code>/css/</code> directory for your \"css\" php file.</p>\n\n<pre><code>function plugin_dynamicss() {\n include_once( plugin_dir_path( __FILE__ ) . '/css/customcss.php' );\n exit;\n}\nadd_action( 'wp_ajax_plugin_dynamicss', 'plugin_dynamicss' );\nadd_action( 'wp_ajax_nopriv_plugin_dynamicss', 'plugin_dynamicss' );\n</code></pre>\n\n<p>Finally, we need to actually enqueue our CSS via <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> hook:</p>\n\n<pre><code>function plugin_enqueue_css() {\n wp_enqueue_style(\n 'dynamicss', admin_url( 'admin-ajax.php' ) . '?action=plugin_dynamicss',\n array(),\n '',\n 'screen'\n );\n}\nadd_action( 'wp_enqueue_scripts', 'plugin_enqueue_css' );\n</code></pre>\n\n<hr>\n\n<p><strong>--- :: JavaScript :: ---</strong></p>\n\n<p>Enqueueing JS with variables is much easier with <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow\"><code>wp_localize_script()</code></a>. All you need to do is <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_script\" rel=\"nofollow\">register the script</a>, <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow\">localize the script</a> with data, and finally <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">enqueue the script</a>.</p>\n\n<pre><code>function plugin_enqueue_js() {\n wp_register_script( 'plugin_js', plugin_dir_path( __FILE__ ) . '/js/customjs.js' );\n\n $data = array( // Define Our Data\n 'robert' => 'bobbert',\n 'nine' => 'nein'\n );\n\n wp_localize_script( 'plugin_js', 'plugin_data', $data ); // Localize Our Data\n\n wp_enqueue_script( 'plugin_js' );\n}\nadd_action( 'wp_enqueue_scripts', 'plugin_enqueue_js' );\n</code></pre>\n\n<p>The 2nd parameter of <code>wp_localize_script()</code> actually defines our JS Object name. In our object if we want to get and use one of the values we can say: <code>alert( plugin_data.robert );</code> which will alert to the screen \"bobbert\".</p>\n"
}
] |
2015/08/04
|
[
"https://wordpress.stackexchange.com/questions/196594",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47687/"
] |
I want to know the best use of adding custom `JS/CSS` to a theme.
I have built a small plugin which has a section to allow users to add `CSS/JS` to their theme. Now I am trying to figure out is which is the best way to do this:
>
> 1. Save all of the code inside an custom DB and load this as plain code inside the header/footer.
> 2. Save all of the code inside an custom js/css file(no DB) and add the file inside the /header/footer
>
>
>
Notice: these custom JS/CSS files are custom build by the users so the user can add the own rules inside the plugin.
Which is the better, most secure solution?
|
I actually ran into a similar issue yesterday. A theme I was working with was adding 500+ lines of internal styles to the header which absolutely drives me nuts! I ended up finding a clever solution online to work around this which you could use for CSS. The JavaScript side I'll explain toward the bottom.
**--- :: CSS :: ---**
There's a few key points in how this code works. Since you need to handle variables in your CSS files we *need* to make sure the file given supports PHP **and** has access to WordPress functions so to get any presets. We cannot do this using a `.css` file alone so we need to fool the server into presenting our PHP file as CSS.
This is purely for testing purposes: Create a file called `customcss.php` with the following code, note the PHP [`header()`](http://php.net/manual/en/function.header.php) function needed to tell the server we're going to show `text/css`:
```
<?php
header( "Content-type: text/css; charset: UTF-8" );
$test = 'blue';
?>
body {color: <?php echo $test; ?>;}
```
Next, we need to load this file in the context of WordPress so that we still have access to functions such as `get_post_meta()` or any `global` variables. Let's include this "css" file using [WP AJAX](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)). Note, when including or requiring we need to use absolute paths. This will look for your plugin folder and into the `/css/` directory for your "css" php file.
```
function plugin_dynamicss() {
include_once( plugin_dir_path( __FILE__ ) . '/css/customcss.php' );
exit;
}
add_action( 'wp_ajax_plugin_dynamicss', 'plugin_dynamicss' );
add_action( 'wp_ajax_nopriv_plugin_dynamicss', 'plugin_dynamicss' );
```
Finally, we need to actually enqueue our CSS via [`wp_enqueue_scripts`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts) hook:
```
function plugin_enqueue_css() {
wp_enqueue_style(
'dynamicss', admin_url( 'admin-ajax.php' ) . '?action=plugin_dynamicss',
array(),
'',
'screen'
);
}
add_action( 'wp_enqueue_scripts', 'plugin_enqueue_css' );
```
---
**--- :: JavaScript :: ---**
Enqueueing JS with variables is much easier with [`wp_localize_script()`](https://codex.wordpress.org/Function_Reference/wp_localize_script). All you need to do is [register the script](https://codex.wordpress.org/Function_Reference/wp_register_script), [localize the script](https://codex.wordpress.org/Function_Reference/wp_localize_script) with data, and finally [enqueue the script](https://codex.wordpress.org/Function_Reference/wp_enqueue_script).
```
function plugin_enqueue_js() {
wp_register_script( 'plugin_js', plugin_dir_path( __FILE__ ) . '/js/customjs.js' );
$data = array( // Define Our Data
'robert' => 'bobbert',
'nine' => 'nein'
);
wp_localize_script( 'plugin_js', 'plugin_data', $data ); // Localize Our Data
wp_enqueue_script( 'plugin_js' );
}
add_action( 'wp_enqueue_scripts', 'plugin_enqueue_js' );
```
The 2nd parameter of `wp_localize_script()` actually defines our JS Object name. In our object if we want to get and use one of the values we can say: `alert( plugin_data.robert );` which will alert to the screen "bobbert".
|
196,600 |
<p>I thought I read that when you send in a post via email you can add the category tag with a short code. So I try this with something like </p>
<pre><code>[my-category-name]
</code></pre>
<p>But all that does is print the literal with brackets. </p>
<p>I must be missing something obvious. </p>
<p>Anyone know, offhand?</p>
|
[
{
"answer_id": 196597,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": -1,
"selected": false,
"text": "<p>You've probably came across several different methods for including JavaScript and CSS.</p>\n\n<p>There is one primary method recommended in the <a href=\"http://codex.wordpress.org\" rel=\"nofollow\">WordPress Codex</a>.</p>\n\n<p>The safe and recommended method of adding JavaScript to a WordPress generated page, and WordPress Theme or Plugin, is by using <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">wp_enqueue_script()</a>. This function includes the script if it hasn't already been included, and safely handles dependencies. </p>\n\n<p>A safe way to add/enqueue a stylesheet file to the WordPress generated page. Use <code>wp_enqueue_style( $handle, $src, $deps, $ver, $media );</code> This function <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_style\" rel=\"nofollow\">wp_enqueue_style()</a> does not return a value.</p>\n"
},
{
"answer_id": 196604,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>I actually ran into a similar issue yesterday. A theme I was working with was adding 500+ lines of internal styles to the header which absolutely drives me nuts! I ended up finding a clever solution online to work around this which you could use for CSS. The JavaScript side I'll explain toward the bottom.</p>\n\n<p><strong>--- :: CSS :: ---</strong></p>\n\n<p>There's a few key points in how this code works. Since you need to handle variables in your CSS files we <em>need</em> to make sure the file given supports PHP <strong>and</strong> has access to WordPress functions so to get any presets. We cannot do this using a <code>.css</code> file alone so we need to fool the server into presenting our PHP file as CSS. </p>\n\n<p>This is purely for testing purposes: Create a file called <code>customcss.php</code> with the following code, note the PHP <a href=\"http://php.net/manual/en/function.header.php\" rel=\"nofollow\"><code>header()</code></a> function needed to tell the server we're going to show <code>text/css</code>:</p>\n\n<pre><code><?php\n header( \"Content-type: text/css; charset: UTF-8\" );\n $test = 'blue';\n?>\n\nbody {color: <?php echo $test; ?>;}\n</code></pre>\n\n<p>Next, we need to load this file in the context of WordPress so that we still have access to functions such as <code>get_post_meta()</code> or any <code>global</code> variables. Let's include this \"css\" file using <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow\">WP AJAX</a>. Note, when including or requiring we need to use absolute paths. This will look for your plugin folder and into the <code>/css/</code> directory for your \"css\" php file.</p>\n\n<pre><code>function plugin_dynamicss() {\n include_once( plugin_dir_path( __FILE__ ) . '/css/customcss.php' );\n exit;\n}\nadd_action( 'wp_ajax_plugin_dynamicss', 'plugin_dynamicss' );\nadd_action( 'wp_ajax_nopriv_plugin_dynamicss', 'plugin_dynamicss' );\n</code></pre>\n\n<p>Finally, we need to actually enqueue our CSS via <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> hook:</p>\n\n<pre><code>function plugin_enqueue_css() {\n wp_enqueue_style(\n 'dynamicss', admin_url( 'admin-ajax.php' ) . '?action=plugin_dynamicss',\n array(),\n '',\n 'screen'\n );\n}\nadd_action( 'wp_enqueue_scripts', 'plugin_enqueue_css' );\n</code></pre>\n\n<hr>\n\n<p><strong>--- :: JavaScript :: ---</strong></p>\n\n<p>Enqueueing JS with variables is much easier with <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow\"><code>wp_localize_script()</code></a>. All you need to do is <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_script\" rel=\"nofollow\">register the script</a>, <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow\">localize the script</a> with data, and finally <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">enqueue the script</a>.</p>\n\n<pre><code>function plugin_enqueue_js() {\n wp_register_script( 'plugin_js', plugin_dir_path( __FILE__ ) . '/js/customjs.js' );\n\n $data = array( // Define Our Data\n 'robert' => 'bobbert',\n 'nine' => 'nein'\n );\n\n wp_localize_script( 'plugin_js', 'plugin_data', $data ); // Localize Our Data\n\n wp_enqueue_script( 'plugin_js' );\n}\nadd_action( 'wp_enqueue_scripts', 'plugin_enqueue_js' );\n</code></pre>\n\n<p>The 2nd parameter of <code>wp_localize_script()</code> actually defines our JS Object name. In our object if we want to get and use one of the values we can say: <code>alert( plugin_data.robert );</code> which will alert to the screen \"bobbert\".</p>\n"
}
] |
2015/08/04
|
[
"https://wordpress.stackexchange.com/questions/196600",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77268/"
] |
I thought I read that when you send in a post via email you can add the category tag with a short code. So I try this with something like
```
[my-category-name]
```
But all that does is print the literal with brackets.
I must be missing something obvious.
Anyone know, offhand?
|
I actually ran into a similar issue yesterday. A theme I was working with was adding 500+ lines of internal styles to the header which absolutely drives me nuts! I ended up finding a clever solution online to work around this which you could use for CSS. The JavaScript side I'll explain toward the bottom.
**--- :: CSS :: ---**
There's a few key points in how this code works. Since you need to handle variables in your CSS files we *need* to make sure the file given supports PHP **and** has access to WordPress functions so to get any presets. We cannot do this using a `.css` file alone so we need to fool the server into presenting our PHP file as CSS.
This is purely for testing purposes: Create a file called `customcss.php` with the following code, note the PHP [`header()`](http://php.net/manual/en/function.header.php) function needed to tell the server we're going to show `text/css`:
```
<?php
header( "Content-type: text/css; charset: UTF-8" );
$test = 'blue';
?>
body {color: <?php echo $test; ?>;}
```
Next, we need to load this file in the context of WordPress so that we still have access to functions such as `get_post_meta()` or any `global` variables. Let's include this "css" file using [WP AJAX](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)). Note, when including or requiring we need to use absolute paths. This will look for your plugin folder and into the `/css/` directory for your "css" php file.
```
function plugin_dynamicss() {
include_once( plugin_dir_path( __FILE__ ) . '/css/customcss.php' );
exit;
}
add_action( 'wp_ajax_plugin_dynamicss', 'plugin_dynamicss' );
add_action( 'wp_ajax_nopriv_plugin_dynamicss', 'plugin_dynamicss' );
```
Finally, we need to actually enqueue our CSS via [`wp_enqueue_scripts`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts) hook:
```
function plugin_enqueue_css() {
wp_enqueue_style(
'dynamicss', admin_url( 'admin-ajax.php' ) . '?action=plugin_dynamicss',
array(),
'',
'screen'
);
}
add_action( 'wp_enqueue_scripts', 'plugin_enqueue_css' );
```
---
**--- :: JavaScript :: ---**
Enqueueing JS with variables is much easier with [`wp_localize_script()`](https://codex.wordpress.org/Function_Reference/wp_localize_script). All you need to do is [register the script](https://codex.wordpress.org/Function_Reference/wp_register_script), [localize the script](https://codex.wordpress.org/Function_Reference/wp_localize_script) with data, and finally [enqueue the script](https://codex.wordpress.org/Function_Reference/wp_enqueue_script).
```
function plugin_enqueue_js() {
wp_register_script( 'plugin_js', plugin_dir_path( __FILE__ ) . '/js/customjs.js' );
$data = array( // Define Our Data
'robert' => 'bobbert',
'nine' => 'nein'
);
wp_localize_script( 'plugin_js', 'plugin_data', $data ); // Localize Our Data
wp_enqueue_script( 'plugin_js' );
}
add_action( 'wp_enqueue_scripts', 'plugin_enqueue_js' );
```
The 2nd parameter of `wp_localize_script()` actually defines our JS Object name. In our object if we want to get and use one of the values we can say: `alert( plugin_data.robert );` which will alert to the screen "bobbert".
|
196,614 |
<p>Hoping someone can assist with Wordpress table prefix for an already established site.</p>
<p>What is the best approach in changing the existing table prefix within both DB and wp-config file to reflect new table prefix.</p>
<p>Actually, it's more the backend DB changes required.</p>
<p>Is there a decent plugin or can someone pls point me to the manual steps required. Just worried that I might cause issues with the DB.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 196619,
"author": "Matt van Andel",
"author_id": 15324,
"author_profile": "https://wordpress.stackexchange.com/users/15324",
"pm_score": 1,
"selected": false,
"text": "<p>This is pretty straightforward. You can use <a href=\"https://stackoverflow.com/questions/23960321/how-to-change-table-prefixes-in-phpmyadmin\">phpMyAdmin</a> or <a href=\"https://stackoverflow.com/questions/26888738/mysql-workbench-add-prefix-to-all-tabels\">MySQL Workbench</a> to change the prefix on all the tables at once, or you can do it one-at-a-time with a tool like SequelPro. If you need to run the SQL by hand, the syntax is…</p>\n\n<pre><code>RENAME TABLE `old_name` TO `new_name`;\n</code></pre>\n\n<p>Once all the table names are updated, you simply update the <code>$table_prefix</code> value in your <code>wp-config.php</code> to match the new prefix.</p>\n"
},
{
"answer_id": 207009,
"author": "RMS",
"author_id": 82695,
"author_profile": "https://wordpress.stackexchange.com/users/82695",
"pm_score": 1,
"selected": false,
"text": "<p>You shouldn't do it manually (SQL), or by using a plugin. It's possible, but quite dangerous.</p>\n\n<p>Because there are some WordPress core tables (like <code>wp_options</code>) that often refer to custom tables (i.e. plugin tables). And moreover, some of the data in those core tables are often serialized (with fixed length and positions), which means that even changing them manually would result in a buggy installation.</p>\n\n<p>You should give a try to a tool like WP-CLI. That really does the job, as it takes in account the serialized data, and parses all the database.</p>\n"
},
{
"answer_id": 262912,
"author": "ghanshyam v",
"author_id": 117204,
"author_profile": "https://wordpress.stackexchange.com/users/117204",
"pm_score": 0,
"selected": false,
"text": "<p>use this plugin : <a href=\"https://wordpress.org/plugins/change-table-prefix/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/change-table-prefix/</a></p>\n\n<p>OR </p>\n\n<p>There are a total of 11 default WordPress tables, so changing them manually would be pain.</p>\n\n<p>SQL Query</p>\n\n<p>That’s why to make things faster, we have a SQL query that you can use.</p>\n\n<p>RENAME table <code>wp_commentmeta</code> TO <code>wp_a123456_commentmeta</code>;\nRENAME table <code>wp_comments</code> TO <code>wp_a123456_comments</code>;\nRENAME table <code>wp_links</code> TO <code>wp_a123456_links</code>;\nRENAME table <code>wp_options</code> TO <code>wp_a123456_options</code>;\nRENAME table <code>wp_postmeta</code> TO <code>wp_a123456_postmeta</code>;\nRENAME table <code>wp_posts</code> TO <code>wp_a123456_posts</code>;\nRENAME table <code>wp_terms</code> TO <code>wp_a123456_terms</code>;\nRENAME table <code>wp_termmeta</code> TO <code>wp_a123456_termmeta</code>;\nRENAME table <code>wp_term_relationships</code> TO <code>wp_a123456_term_relationships</code>;\nRENAME table <code>wp_term_taxonomy</code> TO <code>wp_a123456_term_taxonomy</code>;\nRENAME table <code>wp_usermeta</code> TO <code>wp_a123456_usermeta</code>;\nRENAME table <code>wp_users</code> TO <code>wp_a123456_users</code>;</p>\n\n<p>You may have to add lines for other plugins that may add their own tables in the WordPress database. The idea is that you change all tables prefix to the one that you want.\nThe Options Table</p>\n\n<p>We need to search the options table for any other fields that is using wp_ as a prefix, so we can replace them. To ease up the process, use this query:</p>\n\n<p>SELECT * FROM <code>wp_a123456_options</code> WHERE <code>option_name</code> LIKE '%wp_%'</p>\n\n<p>This will return a lot of results, and you need to go one by one to change these lines.\nUserMeta Table</p>\n\n<p>Next, we need to search the usermeta for all fields that is using wp_ as a prefix, so we can replace it. Use this SQL query for that:</p>\n\n<p>SELECT * FROM <code>wp_a123456_usermeta</code> WHERE <code>meta_key</code> LIKE '%wp_%'</p>\n\n<p>Number of entries may vary on how many plugins you are using and such. Just change everything that has wp_ to the new prefix.</p>\n"
}
] |
2015/08/04
|
[
"https://wordpress.stackexchange.com/questions/196614",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1053/"
] |
Hoping someone can assist with Wordpress table prefix for an already established site.
What is the best approach in changing the existing table prefix within both DB and wp-config file to reflect new table prefix.
Actually, it's more the backend DB changes required.
Is there a decent plugin or can someone pls point me to the manual steps required. Just worried that I might cause issues with the DB.
Thanks.
|
This is pretty straightforward. You can use [phpMyAdmin](https://stackoverflow.com/questions/23960321/how-to-change-table-prefixes-in-phpmyadmin) or [MySQL Workbench](https://stackoverflow.com/questions/26888738/mysql-workbench-add-prefix-to-all-tabels) to change the prefix on all the tables at once, or you can do it one-at-a-time with a tool like SequelPro. If you need to run the SQL by hand, the syntax is…
```
RENAME TABLE `old_name` TO `new_name`;
```
Once all the table names are updated, you simply update the `$table_prefix` value in your `wp-config.php` to match the new prefix.
|
196,649 |
<p>I'm setting up a series of questions and based on the answers, I am trying to redirect to a specific page. For one example, the questions have to be answer correctly, they need to be male and 65 or older. For the other, correct questions, they need to be female and 55 or older. Here is the code I am using below. I am accessing the session variables and able to print them below the questions as I move through each question. </p>
<pre><code>add_filter( 'gform_confirmation_6', __NAMESPACE__ . '\\custom_confirmation', 10, 4 );
function custom_confirmation($confirmation, $form, $entry, $ajax) {
session_start();
if(isset($_SESSION['form'])) {
$result = array();
foreach($_SESSION['form'] as $row){
$result[] = $row;
}
if ($result[0] == 'Yes' && $result[1] == 'Male' && $result[2] >= 65 && $result[3] == 'No' && $result[5] == 'No' ) {
$confirmation = array('redirect' => esc_url(home_url('/welcome')));
}
elseif($result[0] == 'Yes' && $result[1] == 'Female' && $result[2] >= 55 && $result[3] == 'No' && $result[5] == 'No' ) {
$confirmation = array('redirect' => esc_url(home_url('/welcome')));
} else {
$confirmation = array('redirect' => esc_url(home_url('/sorry-you-do-not-qualify')));
}
return $confirmation;
}
}
</code></pre>
<p>What am I doing wrong here? The logic is not working correctly. </p>
<p>Any help would be much appreciated.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 196747,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 0,
"selected": false,
"text": "<p>Without testing your code, I believe the problem lies in the structure of the data you are expecting from the form. Gravity Forms will store the submitted form contents in an array like this</p>\n\n<pre><code>Array\n(\n [form_id] => 4\n [entry_id] => 58\n [form_title] => Auto Bill Pay Form\n [form_description] => \n [date_created] => 3/8/2015\n [date_created_usa] => 8/3/2015\n [pages] => \n [misc] => Array\n (\n [date_time] => 2015-08-03 22:17:19\n [time_24hr] => 22:17\n [time_12hr] => 10:17pm\n [is_starred] => 0\n [is_read] => 0\n [ip] => 97.77.25.130\n [source_url] => http://example/\n [post_id] => \n [currency] => USD\n [payment_status] => \n [payment_date] => \n [transaction_id] => \n [payment_amount] => \n [is_fulfilled] => \n [created_by] => 1\n [transaction_type] => \n [user_agent] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36\n [status] => active\n )\n\n [field_descriptions] => Array\n (\n [17] => (Please enter subscriber’s name above if different than payment info)\n [1] => \n [2] => \n [8] => \n [15] => Confirmation will be sent to the e-mail address we have on file when the transaction is complete. Please keep your e-mail address up-to-date.\n [9] => \n [10] => \n [11] => \n [13] => \n [12] => \n [14] => \n )\n\n [field] => Array\n (\n [17.Subscriber's Name] => George Washington\n [17] => George Washington\n [Subscriber's Name] => George Washington\n</code></pre>\n\n<p>It is a multi-dimensional array with each field having it's own ID and multiple ways to access the value submitted.</p>\n\n<p>In this example, the subscriber's name field has field ID of 17. The simplest way to access that value would be with <code>$form['field'][17]</code>.</p>\n\n<p>In your code, you appear to build an array <code>$result[]</code> but you are not testing a specific field for your 'yes' result.</p>\n\n<p>I would recommend a <code>var_dump()</code> of the form result first to examine the contents, find the field you want to test for a certain value and proceed from there.</p>\n"
},
{
"answer_id": 196916,
"author": "eristic",
"author_id": 77297,
"author_profile": "https://wordpress.stackexchange.com/users/77297",
"pm_score": 3,
"selected": true,
"text": "<p>If anyone runs into this problem, the answer lies in the fact that gform_confirmation is fired after gform_after_submission. The logic is correct, however, the 5th session variable was not being stored before the confirmation was sent. Therefore, no variable ever equaled 'No' and it failed every time.</p>\n\n<p>The solution is to call the $entry in the gform_confirmation and use it below in the conditional logic:</p>\n\n<pre><code>$question6 = $entry['1'];\n\n if(isset($_SESSION['form'])) {\n $result = array();\n foreach($_SESSION['form'] as $row){\n $result[] = $row;\n }\n\n if ($result[0] === 'Yes' && $result[1] === 'Male' && $result[2] >= 65 && $result[3] === 'No' && $question6 === 'No' ) {\n $confirmation = array('redirect' => esc_url(home_url('/welcome')));\n }\n</code></pre>\n"
}
] |
2015/08/04
|
[
"https://wordpress.stackexchange.com/questions/196649",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77297/"
] |
I'm setting up a series of questions and based on the answers, I am trying to redirect to a specific page. For one example, the questions have to be answer correctly, they need to be male and 65 or older. For the other, correct questions, they need to be female and 55 or older. Here is the code I am using below. I am accessing the session variables and able to print them below the questions as I move through each question.
```
add_filter( 'gform_confirmation_6', __NAMESPACE__ . '\\custom_confirmation', 10, 4 );
function custom_confirmation($confirmation, $form, $entry, $ajax) {
session_start();
if(isset($_SESSION['form'])) {
$result = array();
foreach($_SESSION['form'] as $row){
$result[] = $row;
}
if ($result[0] == 'Yes' && $result[1] == 'Male' && $result[2] >= 65 && $result[3] == 'No' && $result[5] == 'No' ) {
$confirmation = array('redirect' => esc_url(home_url('/welcome')));
}
elseif($result[0] == 'Yes' && $result[1] == 'Female' && $result[2] >= 55 && $result[3] == 'No' && $result[5] == 'No' ) {
$confirmation = array('redirect' => esc_url(home_url('/welcome')));
} else {
$confirmation = array('redirect' => esc_url(home_url('/sorry-you-do-not-qualify')));
}
return $confirmation;
}
}
```
What am I doing wrong here? The logic is not working correctly.
Any help would be much appreciated.
Thanks!
|
If anyone runs into this problem, the answer lies in the fact that gform\_confirmation is fired after gform\_after\_submission. The logic is correct, however, the 5th session variable was not being stored before the confirmation was sent. Therefore, no variable ever equaled 'No' and it failed every time.
The solution is to call the $entry in the gform\_confirmation and use it below in the conditional logic:
```
$question6 = $entry['1'];
if(isset($_SESSION['form'])) {
$result = array();
foreach($_SESSION['form'] as $row){
$result[] = $row;
}
if ($result[0] === 'Yes' && $result[1] === 'Male' && $result[2] >= 65 && $result[3] === 'No' && $question6 === 'No' ) {
$confirmation = array('redirect' => esc_url(home_url('/welcome')));
}
```
|
196,666 |
<p>I mean the speed of query records from database, not the way we render the content gained.
More specifically, I just want to query the posts' IDs, my site contains more than 4000 posts (they are custom post type) and I just want to have all their ID.</p>
|
[
{
"answer_id": 196668,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, custom SQL queries are in essence faster than a custom instance of <code>WP_Query</code>. The disadvantage of a custom SQL query is that you are loosing a lot, like object cache, filters and actions, etc, etc, and it is also discouraged to use custom SQL if Wordpress already offers that specific functionality.</p>\n\n<p><code>WP_Query</code> does have the option however to only query post ID's (<em>which is really fast and very lean</em>) by means of adding and using the <code>fields</code> parameter in your query arguments. You can also just use <code>get_posts</code> which uses <code>WP_Query</code> but does not return the post object but just the array of posts</p>\n\n<p>So, you can basically do the following</p>\n\n<pre><code>$args = [\n 'nopaging' => true,\n 'fields' => 'ids' // Just get post ID's\n];\n$q = get_posts( $args );\nvar_dump( $q );\n</code></pre>\n"
},
{
"answer_id": 313545,
"author": "David Labbe",
"author_id": 38434,
"author_profile": "https://wordpress.stackexchange.com/users/38434",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an example of how to cache a custom SQL.</p>\n\n<pre><code> function get_sample_data() {\n global $wpdb;\n\n $query\n = \"\n SELECT ID ,post_title\n FROM $wpdb->posts\n LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)\n WHERE $wpdb->posts.post_status = 'publish' \n AND $wpdb->posts.post_type = 'sample_type'\n AND $wpdb->postmeta.meta_key = '_sample_meta_key'\n AND $wpdb->postmeta.meta_value = 'singular'\n ORDER BY $wpdb->posts.post_date ASC\n \";\n\n $result = wp_cache_get( 'sample_cache_key' );\n if ( false === $result ) {\n $result = $wpdb->get_results( $query );\n wp_cache_set( 'sample_cache_key', $result );\n }\n\n return $result;\n }\n</code></pre>\n"
}
] |
2015/08/05
|
[
"https://wordpress.stackexchange.com/questions/196666",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70868/"
] |
I mean the speed of query records from database, not the way we render the content gained.
More specifically, I just want to query the posts' IDs, my site contains more than 4000 posts (they are custom post type) and I just want to have all their ID.
|
Yes, custom SQL queries are in essence faster than a custom instance of `WP_Query`. The disadvantage of a custom SQL query is that you are loosing a lot, like object cache, filters and actions, etc, etc, and it is also discouraged to use custom SQL if Wordpress already offers that specific functionality.
`WP_Query` does have the option however to only query post ID's (*which is really fast and very lean*) by means of adding and using the `fields` parameter in your query arguments. You can also just use `get_posts` which uses `WP_Query` but does not return the post object but just the array of posts
So, you can basically do the following
```
$args = [
'nopaging' => true,
'fields' => 'ids' // Just get post ID's
];
$q = get_posts( $args );
var_dump( $q );
```
|
196,673 |
<p>I was trying to add category images for custom taxonomy I am using this plugin <a href="https://wordpress.org/plugins/taxonomy-images/" rel="nofollow">taxonomy-images</a> but I don't know how to get that custom taxonomy image</p>
<p>I tried to keep print <code>apply_filters( 'taxonomy-images-queried-term-image', '' );</code></p>
<p>but not getting image in taxonomy page </p>
<p>here's my <code>taxonomy.php</code> code</p>
<pre><code><?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); ?>
<h2> <?php echo $term->name;?></h2>
<?php query_posts(array( 'post_type'=>'deals', 'brands' => $term->slug, 'posts_per_page' => -1 )); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<!--your content goes here-->
<p>Deal Name: <?php echo the_field('deal_title'); ?></p>
<p>test:<?php echo the_field('dealdescription'); ?></p>
<?php
print apply_filters( 'taxonomy-images-queried-term-image', '' );
?>
<!--your content goes here-->
<?php endwhile; else: ?>
<h3>Sorry, no matched your criteria.</h3>
<?php endif; ?>
</code></pre>
|
[
{
"answer_id": 196668,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, custom SQL queries are in essence faster than a custom instance of <code>WP_Query</code>. The disadvantage of a custom SQL query is that you are loosing a lot, like object cache, filters and actions, etc, etc, and it is also discouraged to use custom SQL if Wordpress already offers that specific functionality.</p>\n\n<p><code>WP_Query</code> does have the option however to only query post ID's (<em>which is really fast and very lean</em>) by means of adding and using the <code>fields</code> parameter in your query arguments. You can also just use <code>get_posts</code> which uses <code>WP_Query</code> but does not return the post object but just the array of posts</p>\n\n<p>So, you can basically do the following</p>\n\n<pre><code>$args = [\n 'nopaging' => true,\n 'fields' => 'ids' // Just get post ID's\n];\n$q = get_posts( $args );\nvar_dump( $q );\n</code></pre>\n"
},
{
"answer_id": 313545,
"author": "David Labbe",
"author_id": 38434,
"author_profile": "https://wordpress.stackexchange.com/users/38434",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an example of how to cache a custom SQL.</p>\n\n<pre><code> function get_sample_data() {\n global $wpdb;\n\n $query\n = \"\n SELECT ID ,post_title\n FROM $wpdb->posts\n LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)\n WHERE $wpdb->posts.post_status = 'publish' \n AND $wpdb->posts.post_type = 'sample_type'\n AND $wpdb->postmeta.meta_key = '_sample_meta_key'\n AND $wpdb->postmeta.meta_value = 'singular'\n ORDER BY $wpdb->posts.post_date ASC\n \";\n\n $result = wp_cache_get( 'sample_cache_key' );\n if ( false === $result ) {\n $result = $wpdb->get_results( $query );\n wp_cache_set( 'sample_cache_key', $result );\n }\n\n return $result;\n }\n</code></pre>\n"
}
] |
2015/08/05
|
[
"https://wordpress.stackexchange.com/questions/196673",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76780/"
] |
I was trying to add category images for custom taxonomy I am using this plugin [taxonomy-images](https://wordpress.org/plugins/taxonomy-images/) but I don't know how to get that custom taxonomy image
I tried to keep print `apply_filters( 'taxonomy-images-queried-term-image', '' );`
but not getting image in taxonomy page
here's my `taxonomy.php` code
```
<?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); ?>
<h2> <?php echo $term->name;?></h2>
<?php query_posts(array( 'post_type'=>'deals', 'brands' => $term->slug, 'posts_per_page' => -1 )); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<!--your content goes here-->
<p>Deal Name: <?php echo the_field('deal_title'); ?></p>
<p>test:<?php echo the_field('dealdescription'); ?></p>
<?php
print apply_filters( 'taxonomy-images-queried-term-image', '' );
?>
<!--your content goes here-->
<?php endwhile; else: ?>
<h3>Sorry, no matched your criteria.</h3>
<?php endif; ?>
```
|
Yes, custom SQL queries are in essence faster than a custom instance of `WP_Query`. The disadvantage of a custom SQL query is that you are loosing a lot, like object cache, filters and actions, etc, etc, and it is also discouraged to use custom SQL if Wordpress already offers that specific functionality.
`WP_Query` does have the option however to only query post ID's (*which is really fast and very lean*) by means of adding and using the `fields` parameter in your query arguments. You can also just use `get_posts` which uses `WP_Query` but does not return the post object but just the array of posts
So, you can basically do the following
```
$args = [
'nopaging' => true,
'fields' => 'ids' // Just get post ID's
];
$q = get_posts( $args );
var_dump( $q );
```
|
196,683 |
<p>I have one template file for the main page, after creating home page I have added text to check if it reflect changes on my home page or not and it was successfully displaying text. But when I try to add image by clicking on add media option then image is uploaded but not displaying on my page. What piece of code should be used to get this image on my template file or any other suggestions?</p>
|
[
{
"answer_id": 196668,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, custom SQL queries are in essence faster than a custom instance of <code>WP_Query</code>. The disadvantage of a custom SQL query is that you are loosing a lot, like object cache, filters and actions, etc, etc, and it is also discouraged to use custom SQL if Wordpress already offers that specific functionality.</p>\n\n<p><code>WP_Query</code> does have the option however to only query post ID's (<em>which is really fast and very lean</em>) by means of adding and using the <code>fields</code> parameter in your query arguments. You can also just use <code>get_posts</code> which uses <code>WP_Query</code> but does not return the post object but just the array of posts</p>\n\n<p>So, you can basically do the following</p>\n\n<pre><code>$args = [\n 'nopaging' => true,\n 'fields' => 'ids' // Just get post ID's\n];\n$q = get_posts( $args );\nvar_dump( $q );\n</code></pre>\n"
},
{
"answer_id": 313545,
"author": "David Labbe",
"author_id": 38434,
"author_profile": "https://wordpress.stackexchange.com/users/38434",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an example of how to cache a custom SQL.</p>\n\n<pre><code> function get_sample_data() {\n global $wpdb;\n\n $query\n = \"\n SELECT ID ,post_title\n FROM $wpdb->posts\n LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)\n WHERE $wpdb->posts.post_status = 'publish' \n AND $wpdb->posts.post_type = 'sample_type'\n AND $wpdb->postmeta.meta_key = '_sample_meta_key'\n AND $wpdb->postmeta.meta_value = 'singular'\n ORDER BY $wpdb->posts.post_date ASC\n \";\n\n $result = wp_cache_get( 'sample_cache_key' );\n if ( false === $result ) {\n $result = $wpdb->get_results( $query );\n wp_cache_set( 'sample_cache_key', $result );\n }\n\n return $result;\n }\n</code></pre>\n"
}
] |
2015/08/05
|
[
"https://wordpress.stackexchange.com/questions/196683",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76941/"
] |
I have one template file for the main page, after creating home page I have added text to check if it reflect changes on my home page or not and it was successfully displaying text. But when I try to add image by clicking on add media option then image is uploaded but not displaying on my page. What piece of code should be used to get this image on my template file or any other suggestions?
|
Yes, custom SQL queries are in essence faster than a custom instance of `WP_Query`. The disadvantage of a custom SQL query is that you are loosing a lot, like object cache, filters and actions, etc, etc, and it is also discouraged to use custom SQL if Wordpress already offers that specific functionality.
`WP_Query` does have the option however to only query post ID's (*which is really fast and very lean*) by means of adding and using the `fields` parameter in your query arguments. You can also just use `get_posts` which uses `WP_Query` but does not return the post object but just the array of posts
So, you can basically do the following
```
$args = [
'nopaging' => true,
'fields' => 'ids' // Just get post ID's
];
$q = get_posts( $args );
var_dump( $q );
```
|
196,714 |
<p>I'm looking to retrieve a specific meta value for users from the Wordpress types plugin. I know the value is stored in a wpcf-team-experience-member-type. This is a checkbox option and I'd like to retrieve a list of all selected values.</p>
<p>Right off the bat if I do something like:</p>
<pre><code>var_dump(get_user_meta($user->ID, 'wpcf-team-experience-member-type'))
</code></pre>
<p>I get something like this:</p>
<pre><code>array(1) { [0]=> array(1) { ["wpcf-fields-checkboxes-option-f4fe375f6cad3c44eff97e6e6f16deb2-1"]=> array(1) { [0]=> string(7) "student" } } }
</code></pre>
<p>wpcf seems to put all of its values inside of an array, and on top of that the checkbox values are stored in an array as well. In this case, the value I'm looking for is 'student' but that array might have multiple values.</p>
<p>How would I go about retrieving it? Thank you!</p>
|
[
{
"answer_id": 196668,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, custom SQL queries are in essence faster than a custom instance of <code>WP_Query</code>. The disadvantage of a custom SQL query is that you are loosing a lot, like object cache, filters and actions, etc, etc, and it is also discouraged to use custom SQL if Wordpress already offers that specific functionality.</p>\n\n<p><code>WP_Query</code> does have the option however to only query post ID's (<em>which is really fast and very lean</em>) by means of adding and using the <code>fields</code> parameter in your query arguments. You can also just use <code>get_posts</code> which uses <code>WP_Query</code> but does not return the post object but just the array of posts</p>\n\n<p>So, you can basically do the following</p>\n\n<pre><code>$args = [\n 'nopaging' => true,\n 'fields' => 'ids' // Just get post ID's\n];\n$q = get_posts( $args );\nvar_dump( $q );\n</code></pre>\n"
},
{
"answer_id": 313545,
"author": "David Labbe",
"author_id": 38434,
"author_profile": "https://wordpress.stackexchange.com/users/38434",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an example of how to cache a custom SQL.</p>\n\n<pre><code> function get_sample_data() {\n global $wpdb;\n\n $query\n = \"\n SELECT ID ,post_title\n FROM $wpdb->posts\n LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)\n WHERE $wpdb->posts.post_status = 'publish' \n AND $wpdb->posts.post_type = 'sample_type'\n AND $wpdb->postmeta.meta_key = '_sample_meta_key'\n AND $wpdb->postmeta.meta_value = 'singular'\n ORDER BY $wpdb->posts.post_date ASC\n \";\n\n $result = wp_cache_get( 'sample_cache_key' );\n if ( false === $result ) {\n $result = $wpdb->get_results( $query );\n wp_cache_set( 'sample_cache_key', $result );\n }\n\n return $result;\n }\n</code></pre>\n"
}
] |
2015/08/05
|
[
"https://wordpress.stackexchange.com/questions/196714",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/72946/"
] |
I'm looking to retrieve a specific meta value for users from the Wordpress types plugin. I know the value is stored in a wpcf-team-experience-member-type. This is a checkbox option and I'd like to retrieve a list of all selected values.
Right off the bat if I do something like:
```
var_dump(get_user_meta($user->ID, 'wpcf-team-experience-member-type'))
```
I get something like this:
```
array(1) { [0]=> array(1) { ["wpcf-fields-checkboxes-option-f4fe375f6cad3c44eff97e6e6f16deb2-1"]=> array(1) { [0]=> string(7) "student" } } }
```
wpcf seems to put all of its values inside of an array, and on top of that the checkbox values are stored in an array as well. In this case, the value I'm looking for is 'student' but that array might have multiple values.
How would I go about retrieving it? Thank you!
|
Yes, custom SQL queries are in essence faster than a custom instance of `WP_Query`. The disadvantage of a custom SQL query is that you are loosing a lot, like object cache, filters and actions, etc, etc, and it is also discouraged to use custom SQL if Wordpress already offers that specific functionality.
`WP_Query` does have the option however to only query post ID's (*which is really fast and very lean*) by means of adding and using the `fields` parameter in your query arguments. You can also just use `get_posts` which uses `WP_Query` but does not return the post object but just the array of posts
So, you can basically do the following
```
$args = [
'nopaging' => true,
'fields' => 'ids' // Just get post ID's
];
$q = get_posts( $args );
var_dump( $q );
```
|
196,731 |
<p>As per the title, what I want to do is run a custom query that (using WP-Cron) will run once a day to check for users who registered exactly 360 days before the current date (don't need time, just date) and gather their <code>ID</code>. I have this:</p>
<pre><code>global $wpdb;
$sql = $wpdb->prepare(
"SELECT * FROM {$wpdb->users}
WHERE {$wpdb->users}.user_registered = CURRENT-DATE-MINUS-360-DAYS";
);
$userdata = HOW-DO-I-GET-THE-RESULTS-IN-AN-ARRAY
</code></pre>
<p>Where the bit in caps represents the bit I have no idea what to do :) Any help much appreciated.</p>
|
[
{
"answer_id": 196743,
"author": "Trang",
"author_id": 70868,
"author_profile": "https://wordpress.stackexchange.com/users/70868",
"pm_score": 0,
"selected": false,
"text": "<p>Use</p>\n\n<pre><code>$wpdb->get_results(\"SELECT *, (DATEDIFF(NOW(),user_registered)) AS daydiff FROM {$wpdb->users} WHERE 'daydiff' = 360\");\n</code></pre>\n"
},
{
"answer_id": 196774,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/user.php#L794\" rel=\"nofollow\">peeked</a> into the <code>WP_User_Query</code> class and it supports a <code>WP_Date_Query</code> query on the user registration date.</p>\n\n<p>So we could use:</p>\n\n<pre><code>$query = new WP_User_Query( $args );\n</code></pre>\n\n<p>or simply:</p>\n\n<pre><code>$users = get_users( $args );\n</code></pre>\n\n<p>where:</p>\n\n<pre><code>$args = [\n 'fields' => 'ID',\n 'number' => 8,\n 'date_query' => [\n [ 'before' => '359 days ago midnight' ],\n [ 'after' => '360 days ago midnight', 'inclusive' => true ],\n ] \n];\n</code></pre>\n\n<p>This generates the following SQL query (<em>expanded view</em>):</p>\n\n<pre><code>SELECT wp_users.ID \n FROM wp_users \n WHERE 1=1 \n AND ( \n wp_users.user_registered >= '2014-08-10 00:00:00' \n AND \n wp_users.user_registered < '2014-08-11 00:00:00' \n ) \n ORDER BY user_login ASC \n LIMIT 10;\n</code></pre>\n\n<p>where today is <code>2015-08-05</code>.</p>\n\n<p>It looks like we should update the Codex on <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow\"><code>get_users()</code></a> function, regarding the <code>date_query</code> argument.</p>\n"
}
] |
2015/08/05
|
[
"https://wordpress.stackexchange.com/questions/196731",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35299/"
] |
As per the title, what I want to do is run a custom query that (using WP-Cron) will run once a day to check for users who registered exactly 360 days before the current date (don't need time, just date) and gather their `ID`. I have this:
```
global $wpdb;
$sql = $wpdb->prepare(
"SELECT * FROM {$wpdb->users}
WHERE {$wpdb->users}.user_registered = CURRENT-DATE-MINUS-360-DAYS";
);
$userdata = HOW-DO-I-GET-THE-RESULTS-IN-AN-ARRAY
```
Where the bit in caps represents the bit I have no idea what to do :) Any help much appreciated.
|
I [peeked](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/user.php#L794) into the `WP_User_Query` class and it supports a `WP_Date_Query` query on the user registration date.
So we could use:
```
$query = new WP_User_Query( $args );
```
or simply:
```
$users = get_users( $args );
```
where:
```
$args = [
'fields' => 'ID',
'number' => 8,
'date_query' => [
[ 'before' => '359 days ago midnight' ],
[ 'after' => '360 days ago midnight', 'inclusive' => true ],
]
];
```
This generates the following SQL query (*expanded view*):
```
SELECT wp_users.ID
FROM wp_users
WHERE 1=1
AND (
wp_users.user_registered >= '2014-08-10 00:00:00'
AND
wp_users.user_registered < '2014-08-11 00:00:00'
)
ORDER BY user_login ASC
LIMIT 10;
```
where today is `2015-08-05`.
It looks like we should update the Codex on [`get_users()`](https://codex.wordpress.org/Function_Reference/get_users) function, regarding the `date_query` argument.
|
196,739 |
<p>I'm having difficulty returning a list of posts. This file is contained in a plugin folder (ultimately I want to have a cron job just run the script here to delete posts with invalid urls in the given meta value). </p>
<p>I've tried using get_posts to return posts with no success. So I tried working and reworking a wp_query with still no success. </p>
<p>Also, the only way I can successfully get to the part where the array would be printed and the 'No items here' displays is if the post_status is set to inherit. Otherwise absolutely no output is generated. </p>
<p>Can anyone give me a hint to the fundamental I'm missing here? I've structured the pull correctly both when attempting the get_posts and wp_query because I recycled code structures I already successfully use in other areas of the site. Is there another file I need to call? A special piece of code that has to be added in a stand alone file like this? Another approach I should take? </p>
<pre><code>ini_set("memory_limit","64M");
require('./wp-blog-header.php');
global $wp_query;
$ready_delete = array();
$query = new WP_Query(array(
'post_type' => 'cars',
'posts_per_page' => -1));
if( $query->have_posts() ) :
while ($query->have_posts()) : $query->the_post();
$checklink_id = get_the_ID();
$checklink = get_post_meta($checklink_id, 'ca_link', true);
//$ch = curl_init($checklink);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//if (curl_exec($ch) === false) {
$ready_delete[] = $checklink;
//wp_delete_post( $checklink_id, $force_delete );
//} else {
//}
//curl_close($ch);
endwhile;
else:
echo 'No items here ';
endif;
print_r($ready_delete);
wp_reset_postdata();
</code></pre>
|
[
{
"answer_id": 196743,
"author": "Trang",
"author_id": 70868,
"author_profile": "https://wordpress.stackexchange.com/users/70868",
"pm_score": 0,
"selected": false,
"text": "<p>Use</p>\n\n<pre><code>$wpdb->get_results(\"SELECT *, (DATEDIFF(NOW(),user_registered)) AS daydiff FROM {$wpdb->users} WHERE 'daydiff' = 360\");\n</code></pre>\n"
},
{
"answer_id": 196774,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/user.php#L794\" rel=\"nofollow\">peeked</a> into the <code>WP_User_Query</code> class and it supports a <code>WP_Date_Query</code> query on the user registration date.</p>\n\n<p>So we could use:</p>\n\n<pre><code>$query = new WP_User_Query( $args );\n</code></pre>\n\n<p>or simply:</p>\n\n<pre><code>$users = get_users( $args );\n</code></pre>\n\n<p>where:</p>\n\n<pre><code>$args = [\n 'fields' => 'ID',\n 'number' => 8,\n 'date_query' => [\n [ 'before' => '359 days ago midnight' ],\n [ 'after' => '360 days ago midnight', 'inclusive' => true ],\n ] \n];\n</code></pre>\n\n<p>This generates the following SQL query (<em>expanded view</em>):</p>\n\n<pre><code>SELECT wp_users.ID \n FROM wp_users \n WHERE 1=1 \n AND ( \n wp_users.user_registered >= '2014-08-10 00:00:00' \n AND \n wp_users.user_registered < '2014-08-11 00:00:00' \n ) \n ORDER BY user_login ASC \n LIMIT 10;\n</code></pre>\n\n<p>where today is <code>2015-08-05</code>.</p>\n\n<p>It looks like we should update the Codex on <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow\"><code>get_users()</code></a> function, regarding the <code>date_query</code> argument.</p>\n"
}
] |
2015/08/05
|
[
"https://wordpress.stackexchange.com/questions/196739",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73442/"
] |
I'm having difficulty returning a list of posts. This file is contained in a plugin folder (ultimately I want to have a cron job just run the script here to delete posts with invalid urls in the given meta value).
I've tried using get\_posts to return posts with no success. So I tried working and reworking a wp\_query with still no success.
Also, the only way I can successfully get to the part where the array would be printed and the 'No items here' displays is if the post\_status is set to inherit. Otherwise absolutely no output is generated.
Can anyone give me a hint to the fundamental I'm missing here? I've structured the pull correctly both when attempting the get\_posts and wp\_query because I recycled code structures I already successfully use in other areas of the site. Is there another file I need to call? A special piece of code that has to be added in a stand alone file like this? Another approach I should take?
```
ini_set("memory_limit","64M");
require('./wp-blog-header.php');
global $wp_query;
$ready_delete = array();
$query = new WP_Query(array(
'post_type' => 'cars',
'posts_per_page' => -1));
if( $query->have_posts() ) :
while ($query->have_posts()) : $query->the_post();
$checklink_id = get_the_ID();
$checklink = get_post_meta($checklink_id, 'ca_link', true);
//$ch = curl_init($checklink);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//if (curl_exec($ch) === false) {
$ready_delete[] = $checklink;
//wp_delete_post( $checklink_id, $force_delete );
//} else {
//}
//curl_close($ch);
endwhile;
else:
echo 'No items here ';
endif;
print_r($ready_delete);
wp_reset_postdata();
```
|
I [peeked](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/user.php#L794) into the `WP_User_Query` class and it supports a `WP_Date_Query` query on the user registration date.
So we could use:
```
$query = new WP_User_Query( $args );
```
or simply:
```
$users = get_users( $args );
```
where:
```
$args = [
'fields' => 'ID',
'number' => 8,
'date_query' => [
[ 'before' => '359 days ago midnight' ],
[ 'after' => '360 days ago midnight', 'inclusive' => true ],
]
];
```
This generates the following SQL query (*expanded view*):
```
SELECT wp_users.ID
FROM wp_users
WHERE 1=1
AND (
wp_users.user_registered >= '2014-08-10 00:00:00'
AND
wp_users.user_registered < '2014-08-11 00:00:00'
)
ORDER BY user_login ASC
LIMIT 10;
```
where today is `2015-08-05`.
It looks like we should update the Codex on [`get_users()`](https://codex.wordpress.org/Function_Reference/get_users) function, regarding the `date_query` argument.
|
196,750 |
<p>I need, somehow, to enable that when you logout, that <em>'My Account'</em> item is getting hidden from the navbar, and instead it displays a <em>'Log in'</em> link. The item <em>'My Account'</em> also have submenus with the items <em>'Log out'</em> and <em>'Track your order'</em>. This should be hidden as well <em>(I guess it gets hidden when you hide the parent 'My Account')</em>.</p>
<p>I use the theme Mystile, WordPress and I use the latest version of WooCommerce.</p>
<p>Any suggestions how to?</p>
<p>The JSFiddle of my menu's HTML source: <a href="http://jsfiddle.net/qcuckt1f/" rel="nofollow">http://jsfiddle.net/qcuckt1f/</a></p>
<pre><code><nav id="navigation" class="col-full parent" role="navigation">
<ul id="main-nav" class="nav fr parent">
<li id="menu-item-68" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-68"><a href="http://renhud.square-brain.com/">Forside</a>
</li>
<li id="menu-item-67" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-67"><a href="http://renhud.square-brain.com/butik/">Butik</a>
</li>
<li id="menu-item-61" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-61"><a href="http://renhud.square-brain.com/support/">Kundeservice</a>
</li>
<li id="menu-item-62" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-8 current_page_item menu-item-has-children menu-item-62 parent"><a href="http://renhud.square-brain.com/min-konto/">Min Konto</a>
<ul class="sub-menu">
<li id="menu-item-63" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-63"><a href="http://renhud.square-brain.com/min-konto/track-din-ordre/">Track din ordre</a>
</li>
<li id="menu-item-71" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-71"><a href="http://renhud.square-brain.com/min-konto/log-ud/">Log Ud</a>
</li>
</ul>
</li>
</ul>
</nav>
</code></pre>
|
[
{
"answer_id": 196908,
"author": "somebodysomewhere",
"author_id": 44937,
"author_profile": "https://wordpress.stackexchange.com/users/44937",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the WordPress function <code>is_user_logged_in()</code> to check that, and create some basic if statements to show and hide the appropriate code.</p>\n"
},
{
"answer_id": 196932,
"author": "5ervant - techintel.github.io",
"author_id": 73330,
"author_profile": "https://wordpress.stackexchange.com/users/73330",
"pm_score": 3,
"selected": true,
"text": "<p>It seems that the OP have managed to solve his/her problem by doing this, which can be found at <a href=\"https://codex.wordpress.org/Function_Reference/wp_nav_menu#Different_menus_for_logged-in_users\" rel=\"nofollow noreferrer\">Different menus for logged-in users</a>.</p>\n\n<pre><code>if ( is_user_logged_in() ) {\n wp_nav_menu( array( 'theme_location' => 'logged-in-menu' ) );\n} else {\n wp_nav_menu( array( 'theme_location' => 'logged-out-menu' ) );\n}\n</code></pre>\n\n<p>The more shorter way to achieve that is by doing this, which is <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/#div-comment-208\" rel=\"nofollow noreferrer\">posted in new developer.wordpress.org</a> version:</p>\n\n<pre><code>wp_nav_menu( array(\n 'theme_location' => is_user_logged_in() ? 'logged-in-menu' : 'logged-out-menu'\n) );\n</code></pre>\n\n<p>The robust way to achieve that without creating two different menus, is to use a custom <code>'walker'</code> function:</p>\n\n<ol>\n<li><p>Look for the custom walker class that your theme is using in its <code>wp_nav_menu()</code>:</p>\n\n<pre><code>wp_nav_menu( array(\n // More arguments here..\n 'walker' => new Your_Theme_Custom_Nav_Walker(),\n) );\n</code></pre></li>\n<li><p>Write a new class in your <em>\"functions.php\"</em>, extend <code>Your_Theme_Custom_Nav_Walker</code> class <em>(you can easily search its declaration by using an IDE)</em> or extend the <code>Walker_Nav_Menu</code> class if they're not using any custom walker, and copy the necessary function<em>(s)</em> to modify, mostly the <code>start_el()</code> function, of that walker class in their declaration. Here is the simple custom class that extends the <code>Walker_Nav_Menu</code> that I build to suit your needs:</p>\n\n<pre><code>class WP_Custom_Nav_Walker extends Walker_Nav_Menu {\n\n/**\n * Start the element output.\n *\n * @see Walker::start_el()\n *\n * @since 3.0.0\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param object $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array $args An array of arguments. @see wp_nav_menu()\n * @param int $id Current item ID.\n */\npublic function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n $indent = ( $depth ) ? str_repeat( \"\\t\", $depth ) : '';\n\n $classes = empty( $item->classes ) ? array() : (array) $item->classes;\n $classes[] = 'menu-item-' . $item->ID;\n\n /**\n * Filter the CSS class(es) applied to a menu item's list item element.\n *\n * @since 3.0.0\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param array $classes The CSS classes that are applied to the menu item's `<li>` element.\n * @param object $item The current menu item.\n * @param array $args An array of {@see wp_nav_menu()} arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );\n $class_names = $class_names ? ' class=\"' . esc_attr( $class_names ) . '\"' : '';\n\n /**\n * Filter the ID applied to a menu item's list item element.\n *\n * @since 3.0.1\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param string $menu_id The ID that is applied to the menu item's `<li>` element.\n * @param object $item The current menu item.\n * @param array $args An array of {@see wp_nav_menu()} arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth );\n $id = $id ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n\n\n // MODIFICATION STARTS HERE!!\n $output .= $indent . '<li' . $id . $class_names;\n\n if (apply_filters('the_title', $item->title, $item->ID) === 'My Account') {\n if ( is_user_logged_in() ) {\n $output .= '>';\n } else {\n $output .= '><a href=\"' . get_site_url() . '/wp-login.php\">Log in</a></li>';\n $output .= '<li style=\"display: none\">';\n }\n } else {\n $output .= '>';\n }\n // MODIFICATION ENDS HERE!!\n\n\n $atts = array();\n $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';\n $atts['target'] = ! empty( $item->target ) ? $item->target : '';\n $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';\n $atts['href'] = ! empty( $item->url ) ? $item->url : '';\n\n /**\n * Filter the HTML attributes applied to a menu item's anchor element.\n *\n * @since 3.6.0\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param array $atts {\n * The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.\n *\n * @type string $title Title attribute.\n * @type string $target Target attribute.\n * @type string $rel The rel attribute.\n * @type string $href The href attribute.\n * }\n * @param object $item The current menu item.\n * @param array $args An array of {@see wp_nav_menu()} arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );\n\n $attributes = '';\n foreach ( $atts as $attr => $value ) {\n if ( ! empty( $value ) ) {\n $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );\n $attributes .= ' ' . $attr . '=\"' . $value . '\"';\n }\n }\n\n $item_output = $args->before;\n $item_output .= '<a'. $attributes .'>';\n /** This filter is documented in wp-includes/post-template.php */\n $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;\n $item_output .= '</a>';\n $item_output .= $args->after;\n\n /**\n * Filter a menu item's starting output.\n *\n * The menu item's starting output only includes `$args->before`, the opening `<a>`,\n * the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is\n * no filter for modifying the opening and closing `<li>` for a menu item.\n *\n * @since 3.0.0\n *\n * @param string $item_output The menu item's starting HTML output.\n * @param object $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array $args An array of {@see wp_nav_menu()} arguments.\n */\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n}\n\n}\n</code></pre></li>\n<li><p>You can use that <code>WP_Custom_Nav_Walker</code> like this:</p>\n\n<pre><code>wp_nav_menu( array(\n // More arguments here..\n 'walker' => new WP_Custom_Nav_Walker(),\n) );\n</code></pre></li>\n</ol>\n\n<p>You can check <a href=\"https://wordpress.stackexchange.com/a/196901/73330\">this answer</a> for another example how to do that.</p>\n"
}
] |
2015/08/05
|
[
"https://wordpress.stackexchange.com/questions/196750",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77322/"
] |
I need, somehow, to enable that when you logout, that *'My Account'* item is getting hidden from the navbar, and instead it displays a *'Log in'* link. The item *'My Account'* also have submenus with the items *'Log out'* and *'Track your order'*. This should be hidden as well *(I guess it gets hidden when you hide the parent 'My Account')*.
I use the theme Mystile, WordPress and I use the latest version of WooCommerce.
Any suggestions how to?
The JSFiddle of my menu's HTML source: <http://jsfiddle.net/qcuckt1f/>
```
<nav id="navigation" class="col-full parent" role="navigation">
<ul id="main-nav" class="nav fr parent">
<li id="menu-item-68" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-68"><a href="http://renhud.square-brain.com/">Forside</a>
</li>
<li id="menu-item-67" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-67"><a href="http://renhud.square-brain.com/butik/">Butik</a>
</li>
<li id="menu-item-61" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-61"><a href="http://renhud.square-brain.com/support/">Kundeservice</a>
</li>
<li id="menu-item-62" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-8 current_page_item menu-item-has-children menu-item-62 parent"><a href="http://renhud.square-brain.com/min-konto/">Min Konto</a>
<ul class="sub-menu">
<li id="menu-item-63" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-63"><a href="http://renhud.square-brain.com/min-konto/track-din-ordre/">Track din ordre</a>
</li>
<li id="menu-item-71" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-71"><a href="http://renhud.square-brain.com/min-konto/log-ud/">Log Ud</a>
</li>
</ul>
</li>
</ul>
</nav>
```
|
It seems that the OP have managed to solve his/her problem by doing this, which can be found at [Different menus for logged-in users](https://codex.wordpress.org/Function_Reference/wp_nav_menu#Different_menus_for_logged-in_users).
```
if ( is_user_logged_in() ) {
wp_nav_menu( array( 'theme_location' => 'logged-in-menu' ) );
} else {
wp_nav_menu( array( 'theme_location' => 'logged-out-menu' ) );
}
```
The more shorter way to achieve that is by doing this, which is [posted in new developer.wordpress.org](https://developer.wordpress.org/reference/functions/wp_nav_menu/#div-comment-208) version:
```
wp_nav_menu( array(
'theme_location' => is_user_logged_in() ? 'logged-in-menu' : 'logged-out-menu'
) );
```
The robust way to achieve that without creating two different menus, is to use a custom `'walker'` function:
1. Look for the custom walker class that your theme is using in its `wp_nav_menu()`:
```
wp_nav_menu( array(
// More arguments here..
'walker' => new Your_Theme_Custom_Nav_Walker(),
) );
```
2. Write a new class in your *"functions.php"*, extend `Your_Theme_Custom_Nav_Walker` class *(you can easily search its declaration by using an IDE)* or extend the `Walker_Nav_Menu` class if they're not using any custom walker, and copy the necessary function*(s)* to modify, mostly the `start_el()` function, of that walker class in their declaration. Here is the simple custom class that extends the `Walker_Nav_Menu` that I build to suit your needs:
```
class WP_Custom_Nav_Walker extends Walker_Nav_Menu {
/**
* Start the element output.
*
* @see Walker::start_el()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
* @param int $id Current item ID.
*/
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
/**
* Filter the CSS class(es) applied to a menu item's list item element.
*
* @since 3.0.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $classes The CSS classes that are applied to the menu item's `<li>` element.
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
/**
* Filter the ID applied to a menu item's list item element.
*
* @since 3.0.1
* @since 4.1.0 The `$depth` parameter was added.
*
* @param string $menu_id The ID that is applied to the menu item's `<li>` element.
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
// MODIFICATION STARTS HERE!!
$output .= $indent . '<li' . $id . $class_names;
if (apply_filters('the_title', $item->title, $item->ID) === 'My Account') {
if ( is_user_logged_in() ) {
$output .= '>';
} else {
$output .= '><a href="' . get_site_url() . '/wp-login.php">Log in</a></li>';
$output .= '<li style="display: none">';
}
} else {
$output .= '>';
}
// MODIFICATION ENDS HERE!!
$atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
/**
* Filter the HTML attributes applied to a menu item's anchor element.
*
* @since 3.6.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $title Title attribute.
* @type string $target Target attribute.
* @type string $rel The rel attribute.
* @type string $href The href attribute.
* }
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
/** This filter is documented in wp-includes/post-template.php */
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
/**
* Filter a menu item's starting output.
*
* The menu item's starting output only includes `$args->before`, the opening `<a>`,
* the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is
* no filter for modifying the opening and closing `<li>` for a menu item.
*
* @since 3.0.0
*
* @param string $item_output The menu item's starting HTML output.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of {@see wp_nav_menu()} arguments.
*/
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
```
3. You can use that `WP_Custom_Nav_Walker` like this:
```
wp_nav_menu( array(
// More arguments here..
'walker' => new WP_Custom_Nav_Walker(),
) );
```
You can check [this answer](https://wordpress.stackexchange.com/a/196901/73330) for another example how to do that.
|
196,811 |
<p>I am currently listing posts based on user role, with the following query:</p>
<pre><code>$ids = get_users( array('role' => 'author' ,'fields' => 'ID') );
$args = array(
'author' => implode(',', $ids),
'orderby' => 'date',
'order' => 'ASC',
);
</code></pre>
<p>Would it be possible to also limit the posts based on the membership level of the author using Paid Membership Pro? The plugin has the following hook to check user level:</p>
<pre><code>if(pmpro_hasMembershipLevel($level_id))
</code></pre>
<p>But I'm not sure how to incorporate it into the above query (if possible)?</p>
|
[
{
"answer_id": 196801,
"author": "Rene Korss",
"author_id": 69908,
"author_profile": "https://wordpress.stackexchange.com/users/69908",
"pm_score": 0,
"selected": false,
"text": "<p>Add <code>.htaccess</code> file to root folder in arkansaspicker.com.</p>\n\n<p><strong>.htaccess</strong></p>\n\n<pre><code>RewriteEngine On\nRewriteRule ^(blog/.*)$ http://news.arkansaspickem.com/$1 [R=301,L,NC]\n</code></pre>\n\n<p>Then you have two options to get contents of <code>/blog</code> to show on news.arkansaspickem.com.</p>\n\n<ul>\n<li>Move your WP to subdomain folder. <a href=\"https://www.akeebabackup.com/download/backup-wordpress/1-4-1.html\" rel=\"nofollow\">Akeeba Backup</a> will help you with that.</li>\n<li>Change your subdomain's <code>vhost</code> <code>DocumentRoot</code> to path to <code>/blog</code> folder. This is usually not possible, if using shared hosting. See <a href=\"https://httpd.apache.org/docs/2.2/vhosts/examples.html\" rel=\"nofollow\">VirtualHost Examples</a>.</li>\n</ul>\n"
},
{
"answer_id": 351762,
"author": "imba Agency",
"author_id": 177406,
"author_profile": "https://wordpress.stackexchange.com/users/177406",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest way is to use WordPress plugins. For example:</p>\n\n<ol>\n<li>301 SEO Redirection</li>\n<li>301 Redirects</li>\n</ol>\n\n<p>Or use <code>.htaccess</code> file</p>\n"
}
] |
2015/08/06
|
[
"https://wordpress.stackexchange.com/questions/196811",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58166/"
] |
I am currently listing posts based on user role, with the following query:
```
$ids = get_users( array('role' => 'author' ,'fields' => 'ID') );
$args = array(
'author' => implode(',', $ids),
'orderby' => 'date',
'order' => 'ASC',
);
```
Would it be possible to also limit the posts based on the membership level of the author using Paid Membership Pro? The plugin has the following hook to check user level:
```
if(pmpro_hasMembershipLevel($level_id))
```
But I'm not sure how to incorporate it into the above query (if possible)?
|
The simplest way is to use WordPress plugins. For example:
1. 301 SEO Redirection
2. 301 Redirects
Or use `.htaccess` file
|
196,812 |
<p>I am using latest wordpres. I have created child theme. </p>
<p>I am trying to overwride the .box style of parent theme but it is not overriding it. If i do this in parent themes <code>style.css</code> it works.</p>
<pre><code>//This is style.css of child theme
/*
Theme Name: Custom Theme
Description: Child Theme
Author: Shahrukh
Template: basetheme
Version: 0.1
*/
.box {
width: 600px;
max-width: 75%;
/* padding: 4rem; */
margin: 0 auto;
border: solid 1px #fff;
border: solid 1px hsla(0, 0%, 100%, .3);
}
</code></pre>
<p>This is function.php of child theme
<pre><code>add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',get_stylesheet_directory_uri() . '/style.css',array('parent-style') );
}
require get_stylesheet_directory() . '/myGallery/gallery_functions_include.php';
?>
</code></pre>
|
[
{
"answer_id": 196817,
"author": "Ernedar",
"author_id": 74019,
"author_profile": "https://wordpress.stackexchange.com/users/74019",
"pm_score": 1,
"selected": false,
"text": "<p>Is this: <strong>/</strong> just overwritten or is it a mistake in your code? <code>max-width: 75%;/</code> </p>\n\n<p>It might cause to not work properly. Otherwise i will try a bit shady way, try to make your parent attributes <code>!important</code>.</p>\n"
},
{
"answer_id": 196829,
"author": "Shahrukh Khan",
"author_id": 67596,
"author_profile": "https://wordpress.stackexchange.com/users/67596",
"pm_score": 0,
"selected": false,
"text": "<p>I actully figured out the problem. I did not want the padding porperty i.e <code>padding: 4rem;</code>.\nSo instead of overriding it in child them as <code>padding: 0rem;</code> I did not mention it.\nTherefore that property was not being overridden.</p>\n"
}
] |
2015/08/06
|
[
"https://wordpress.stackexchange.com/questions/196812",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67596/"
] |
I am using latest wordpres. I have created child theme.
I am trying to overwride the .box style of parent theme but it is not overriding it. If i do this in parent themes `style.css` it works.
```
//This is style.css of child theme
/*
Theme Name: Custom Theme
Description: Child Theme
Author: Shahrukh
Template: basetheme
Version: 0.1
*/
.box {
width: 600px;
max-width: 75%;
/* padding: 4rem; */
margin: 0 auto;
border: solid 1px #fff;
border: solid 1px hsla(0, 0%, 100%, .3);
}
```
This is function.php of child theme
```
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',get_stylesheet_directory_uri() . '/style.css',array('parent-style') );
}
require get_stylesheet_directory() . '/myGallery/gallery_functions_include.php';
?>
```
|
Is this: **/** just overwritten or is it a mistake in your code? `max-width: 75%;/`
It might cause to not work properly. Otherwise i will try a bit shady way, try to make your parent attributes `!important`.
|
196,830 |
<p>I've got myself into a little pickle, and while I'm so close, my understanding of PHP is letting me down.</p>
<p>I want to display the image associated with each category in the menu - working from the answer <a href="https://stackoverflow.com/questions/26079190/add-featured-image-to-wp-nav-menu-items">over here</a> I needed to make that code work with a custom taxonomy as I'm working with woocommerce product categories. I should add that my use case is fairly narrow, so I stripped much of the original answer away to focus on this product category image.</p>
<p>First I add all this to the menu.</p>
<pre><code><?php add_filter('wp_nav_menu_args', 'add_filter_to_menus');
function add_filter_to_menus($args) {
add_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
return $args;
} ?>
</code></pre>
<p>The next bit is the problematic stuff...</p>
<pre><code><?php
function filter_menu_items($item) {
// if the menu item is taxonomy
if( $item->type == 'taxonomy') {
// explicitly set the category for now
$cat_base = 'product-category';
// strip away everything except the term path
$cat_path = str_replace(home_url().'/'.$cat_base.'/', '', $item->url);
// get the term object by using the slug
$term = get_term_by('slug', $cat_path, 'product_cat');
// get the term id from the object
$term_id = $term->term_id;
// $term_array = get_object_vars($term);
// echo '<pre>'; var_dump( $term ); echo '</pre>';
$thumbnail_id = get_woocommerce_term_meta( $term_id, 'thumbnail_id', false );
$image = wp_get_attachment_url( $thumbnail_id );
if( !empty($image) ) {
$item->title = $item->title . '<span class="menu-image"><img src="' . $image . '" alt=""></span>';
}
}
} ?>
</code></pre>
<p>Im having a problem getting the <code>$term_id</code> from the <code>$term</code> object. I get a notice <code>Trying to get property of non-object</code>. But when I do a <code>var_dump</code> on <code>$term</code> i get the following:</p>
<pre><code><pre>object(stdClass)#4511 (10) {
["term_id"]=>
int(21)
["name"]=>
string(9) "Furniture"
["slug"]=>
string(9) "furniture"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(21)
["taxonomy"]=>
string(11) "product_cat"
["description"]=>
string(0) ""
["parent"]=>
int(0)
["count"]=>
int(0)
["filter"]=>
string(3) "raw"
}
</pre>
</code></pre>
<p>This looks to me like <code>$term</code> is an object, so why the non-object notice and a total failure? You can also see commented out that I tried to turn this object into an array, but that didn't work out so well either...</p>
<p>Apologies for my PHP skills here - I'm clearly not understanding something fairly basic, but I really did want to solve this myself, but I must admit defeat!</p>
<p>Many thanks for reading.</p>
<hr>
<p>EDIT:</p>
<p>As alluded to in Mark's answer below, the default <code>get_term_by()</code> returns an object. Quite why my code was getting caught up on the is-it-or-isnt-it-an-object thing, I don't know. Using <code>$term = get_term_by('slug', $cat_path, 'product_cat', ARRAY_A);</code> did the trick though, along with using array rather than object syntax to select the value I wanted.</p>
<p>As an aside, I realised that the above would return <code>false</code> if these product categories were nested, as there would be two (or more) slugs being returned; so I did a bit more cleaning up of the slug before attempting to get the term id from it.</p>
<p>Replacing:</p>
<pre><code>$cat_path = str_replace(home_url().'/'.$cat_base.'/', '', $item->url);
</code></pre>
<p>With:</p>
<pre><code>$path = parse_url($item->url, PHP_URL_PATH);
$path_trimmed = trim($path, '/');
$parts = explode('/', $path_trimmed);
$cat_path = end($parts);
</code></pre>
|
[
{
"answer_id": 196833,
"author": "markmoxx",
"author_id": 70674,
"author_profile": "https://wordpress.stackexchange.com/users/70674",
"pm_score": 2,
"selected": true,
"text": "<p>Not sure why your object is returning the non-object notice, but you can set the output of <code>get_term_by</code> to <code>OBJECT</code>, <code>ARRAY_A</code>, or <code>ARRAY_N</code> - You'll want to use <code>ARRAY_A</code> and then access the term ID via <code>$term['term_id']</code>.</p>\n"
},
{
"answer_id": 235116,
"author": "milicua",
"author_id": 100534,
"author_profile": "https://wordpress.stackexchange.com/users/100534",
"pm_score": 0,
"selected": false,
"text": "<p>I think this will work for you:</p>\n\n<pre><code>function wpa_category_nav_class( $classes, $item ){\n if( 'product_cat' == $item->object ){\n $classes[] = 'menu-category-' . $item->object_id;\n }\n return $classes;\n}\nadd_filter( 'nav_menu_css_class', 'wpa_category_nav_class', 10, 2 );\n</code></pre>\n"
}
] |
2015/08/06
|
[
"https://wordpress.stackexchange.com/questions/196830",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77390/"
] |
I've got myself into a little pickle, and while I'm so close, my understanding of PHP is letting me down.
I want to display the image associated with each category in the menu - working from the answer [over here](https://stackoverflow.com/questions/26079190/add-featured-image-to-wp-nav-menu-items) I needed to make that code work with a custom taxonomy as I'm working with woocommerce product categories. I should add that my use case is fairly narrow, so I stripped much of the original answer away to focus on this product category image.
First I add all this to the menu.
```
<?php add_filter('wp_nav_menu_args', 'add_filter_to_menus');
function add_filter_to_menus($args) {
add_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
return $args;
} ?>
```
The next bit is the problematic stuff...
```
<?php
function filter_menu_items($item) {
// if the menu item is taxonomy
if( $item->type == 'taxonomy') {
// explicitly set the category for now
$cat_base = 'product-category';
// strip away everything except the term path
$cat_path = str_replace(home_url().'/'.$cat_base.'/', '', $item->url);
// get the term object by using the slug
$term = get_term_by('slug', $cat_path, 'product_cat');
// get the term id from the object
$term_id = $term->term_id;
// $term_array = get_object_vars($term);
// echo '<pre>'; var_dump( $term ); echo '</pre>';
$thumbnail_id = get_woocommerce_term_meta( $term_id, 'thumbnail_id', false );
$image = wp_get_attachment_url( $thumbnail_id );
if( !empty($image) ) {
$item->title = $item->title . '<span class="menu-image"><img src="' . $image . '" alt=""></span>';
}
}
} ?>
```
Im having a problem getting the `$term_id` from the `$term` object. I get a notice `Trying to get property of non-object`. But when I do a `var_dump` on `$term` i get the following:
```
<pre>object(stdClass)#4511 (10) {
["term_id"]=>
int(21)
["name"]=>
string(9) "Furniture"
["slug"]=>
string(9) "furniture"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(21)
["taxonomy"]=>
string(11) "product_cat"
["description"]=>
string(0) ""
["parent"]=>
int(0)
["count"]=>
int(0)
["filter"]=>
string(3) "raw"
}
</pre>
```
This looks to me like `$term` is an object, so why the non-object notice and a total failure? You can also see commented out that I tried to turn this object into an array, but that didn't work out so well either...
Apologies for my PHP skills here - I'm clearly not understanding something fairly basic, but I really did want to solve this myself, but I must admit defeat!
Many thanks for reading.
---
EDIT:
As alluded to in Mark's answer below, the default `get_term_by()` returns an object. Quite why my code was getting caught up on the is-it-or-isnt-it-an-object thing, I don't know. Using `$term = get_term_by('slug', $cat_path, 'product_cat', ARRAY_A);` did the trick though, along with using array rather than object syntax to select the value I wanted.
As an aside, I realised that the above would return `false` if these product categories were nested, as there would be two (or more) slugs being returned; so I did a bit more cleaning up of the slug before attempting to get the term id from it.
Replacing:
```
$cat_path = str_replace(home_url().'/'.$cat_base.'/', '', $item->url);
```
With:
```
$path = parse_url($item->url, PHP_URL_PATH);
$path_trimmed = trim($path, '/');
$parts = explode('/', $path_trimmed);
$cat_path = end($parts);
```
|
Not sure why your object is returning the non-object notice, but you can set the output of `get_term_by` to `OBJECT`, `ARRAY_A`, or `ARRAY_N` - You'll want to use `ARRAY_A` and then access the term ID via `$term['term_id']`.
|
196,847 |
<p>I've created some custom columns to display my custom post types more attractively in the admin section - the columns are mostly custom fields. Mostly, this works absolutely fine, and I can sort by the custom field columns as expected.</p>
<p>However, one of the custom fields points to the post ID of a different post type. When displaying it, it looks fine, as I can grab the title of the associated post from its ID, rather than displaying the ID itself - all this is in my code below.</p>
<p>I can't figure out how to replicate this in the column sort though, or even if it's possible - I can only see how to sort by the meta-value, which is the ID of the linked post, rather than the title. </p>
<p>My code is working technically correctly, as in it's sorting by the meta value correctly, but I want to sort it alphabetically by the post title with that ID rather than the ID itself. Can this be done, and if so, how?</p>
<pre><code>add_action( 'manage_posts_custom_column' , 'custom_columns', 10, 2 );
function custom_columns( $column, $post_id ) {
global $wpdb;
switch ( $column ) {
case 'extranet_client_area': // Extranet documents
$get_case_ID = get_post_meta( $post_id, 'extranet_client_area', true );
$get_case_name = $wpdb->get_results('SELECT post_title FROM `cn_bf_posts` WHERE `ID` = '.$get_case_ID);
echo '<a href="http://www.bishopfleminginsolvency.co.uk/wp-admin/post.php?post='.$get_case_ID.'&action=edit">'.$get_case_name[0]->post_title.'</a>';
break;
case 'extranet_document_type':
extranet_nice_document_type(get_post_meta( $post_id, 'extranet_document_type', true ));
break;
case 'extranet_document_date':
echo date('d/m/Y',strtotime(get_post_meta( $post_id, 'extranet_document_date', true )));
break;
case 'extranet_file':
echo '<a target="_blank" href="'.get_the_guid(get_post_meta( $post_id, 'extranet_file', true )).'">Download</a>';
break;
default:
break;
}
}
add_action( 'pre_get_posts', 'extranet_orderby' );
function extranet_orderby( $query ) {
if( ! is_admin() )
return;
$orderby = $query->get( 'orderby');
switch ( $orderby ) {
case 'extranet_sort_document_case':
$query->set('meta_key','extranet_client_area');
$query->set('orderby','meta_value');
break;
case 'extranet_sort_document_type':
$query->set('meta_key','extranet_document_type');
$query->set('orderby','meta_value_num');
break;
case 'extranet_sort_document_date':
$query->set('meta_key','extranet_document_date');
$query->set('orderby','meta_value');
break;
default:
break;
}
add_filter('manage_clientdocument_posts_columns','extranet_document_columns');
function extranet_document_columns($columns) {
$columns = array(
'cb'=>'<input type="checkbox" />',
'extranet_client_area' => __( 'Case Name' ),
'title' => __( 'Document Name' ),
'extranet_document_type' => __( 'Document Type' ),
'extranet_document_date' => __( 'Document Date' ),
'extranet_file' => __( 'Download link' )
);
return $columns;
}
add_filter( 'manage_edit-clientdocument_sortable_columns', 'my_sortable_clientdocuments_columns' );
function my_sortable_clientdocuments_columns( $columns ) {
$columns['extranet_client_area'] = 'extranet_sort_document_case';
$columns['extranet_document_type'] = 'extranet_sort_document_type';
$columns['extranet_document_date'] = 'extranet_sort_document_date';
return $columns;
}
</code></pre>
|
[
{
"answer_id": 196848,
"author": "phil",
"author_id": 21347,
"author_profile": "https://wordpress.stackexchange.com/users/21347",
"pm_score": 1,
"selected": false,
"text": "<p>(I was going to add this as a comment as it's not a full answer, but I can't yet...)</p>\n\n<p>I think you will need to use an SQL query as the standard meta_queries / orderby won't work. Have a look at <a href=\"https://wordpress.stackexchange.com/questions/109955/custom-table-column-sortable-by-taxonomy-query\">Custom Table Column Sortable by Taxonomy Query</a> and <a href=\"http://wpdreamer.com/2014/04/how-to-make-your-wordpress-admin-columns-sortable/#sorting-posts-option-b\" rel=\"nofollow noreferrer\">http://wpdreamer.com/2014/04/how-to-make-your-wordpress-admin-columns-sortable/#sorting-posts-option-b</a> for a couple of examples.</p>\n"
},
{
"answer_id": 196867,
"author": "SinisterBeard",
"author_id": 63673,
"author_profile": "https://wordpress.stackexchange.com/users/63673",
"pm_score": 1,
"selected": true,
"text": "<p>Building on Phil's answer:</p>\n\n<p>Made the following change to the switch:</p>\n\n<pre><code>case 'extranet_sort_document_case':\nadd_filter('posts_join', 'extranet_clientdocument_case_join');\nadd_filter('posts_fields', 'extranet_clientdocument_case_fields');\nadd_filter('posts_orderby', 'extranet_clientdocument_case_order');\nbreak; \n</code></pre>\n\n<p>and wrote the following functions:</p>\n\n<pre><code>function extranet_clientdocument_case_join($join) {\n global $wpdb;\n $join .= \" LEFT JOIN \".$wpdb->postmeta.\" AS case_ids ON (\".$wpdb->posts.\".ID = case_ids.post_id AND case_ids.meta_key = 'extranet_client_area') \n LEFT JOIN \".$wpdb->posts.\" AS case_names ON (case_names.ID = case_ids.meta_value) \";\n return $join; \n}\n\nfunction extranet_clientdocument_case_fields($fields) {\n $fields.=\", case_names.post_title\";\n return $fields;\n}\n\nfunction extranet_clientdocument_case_order($order_by) {\n if(isset($_GET['order'])) $direction = $_GET['order'];\n else $direction = 'ASC';\n $order_by = 'case_names.post_title '.$direction;\n return($order_by); \n}\n</code></pre>\n\n<p>This worked in terms of making the column sortable by the post name of the related custom post, rather than by the metadata itself. However, it created a new problem in that the Title of the main post being listed, which is unusually the second column, now turned into the post title of the related post. I fixed this with the following additional code:</p>\n\n<pre><code>function restore_original_title($title) {\n global $wpdb;\n $post_id = get_the_ID();\n $get_document_name = $wpdb->get_results('SELECT * FROM `wp_posts` WHERE `ID` = '.$post_id);\n $title = $get_document_name[0]->post_title;\n return $title; \n}\n</code></pre>\n\n<p>and added the following additional filter:</p>\n\n<pre><code>add_filter( 'the_title', 'restore_original_title', 10, 2 );\n</code></pre>\n"
}
] |
2015/08/06
|
[
"https://wordpress.stackexchange.com/questions/196847",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63673/"
] |
I've created some custom columns to display my custom post types more attractively in the admin section - the columns are mostly custom fields. Mostly, this works absolutely fine, and I can sort by the custom field columns as expected.
However, one of the custom fields points to the post ID of a different post type. When displaying it, it looks fine, as I can grab the title of the associated post from its ID, rather than displaying the ID itself - all this is in my code below.
I can't figure out how to replicate this in the column sort though, or even if it's possible - I can only see how to sort by the meta-value, which is the ID of the linked post, rather than the title.
My code is working technically correctly, as in it's sorting by the meta value correctly, but I want to sort it alphabetically by the post title with that ID rather than the ID itself. Can this be done, and if so, how?
```
add_action( 'manage_posts_custom_column' , 'custom_columns', 10, 2 );
function custom_columns( $column, $post_id ) {
global $wpdb;
switch ( $column ) {
case 'extranet_client_area': // Extranet documents
$get_case_ID = get_post_meta( $post_id, 'extranet_client_area', true );
$get_case_name = $wpdb->get_results('SELECT post_title FROM `cn_bf_posts` WHERE `ID` = '.$get_case_ID);
echo '<a href="http://www.bishopfleminginsolvency.co.uk/wp-admin/post.php?post='.$get_case_ID.'&action=edit">'.$get_case_name[0]->post_title.'</a>';
break;
case 'extranet_document_type':
extranet_nice_document_type(get_post_meta( $post_id, 'extranet_document_type', true ));
break;
case 'extranet_document_date':
echo date('d/m/Y',strtotime(get_post_meta( $post_id, 'extranet_document_date', true )));
break;
case 'extranet_file':
echo '<a target="_blank" href="'.get_the_guid(get_post_meta( $post_id, 'extranet_file', true )).'">Download</a>';
break;
default:
break;
}
}
add_action( 'pre_get_posts', 'extranet_orderby' );
function extranet_orderby( $query ) {
if( ! is_admin() )
return;
$orderby = $query->get( 'orderby');
switch ( $orderby ) {
case 'extranet_sort_document_case':
$query->set('meta_key','extranet_client_area');
$query->set('orderby','meta_value');
break;
case 'extranet_sort_document_type':
$query->set('meta_key','extranet_document_type');
$query->set('orderby','meta_value_num');
break;
case 'extranet_sort_document_date':
$query->set('meta_key','extranet_document_date');
$query->set('orderby','meta_value');
break;
default:
break;
}
add_filter('manage_clientdocument_posts_columns','extranet_document_columns');
function extranet_document_columns($columns) {
$columns = array(
'cb'=>'<input type="checkbox" />',
'extranet_client_area' => __( 'Case Name' ),
'title' => __( 'Document Name' ),
'extranet_document_type' => __( 'Document Type' ),
'extranet_document_date' => __( 'Document Date' ),
'extranet_file' => __( 'Download link' )
);
return $columns;
}
add_filter( 'manage_edit-clientdocument_sortable_columns', 'my_sortable_clientdocuments_columns' );
function my_sortable_clientdocuments_columns( $columns ) {
$columns['extranet_client_area'] = 'extranet_sort_document_case';
$columns['extranet_document_type'] = 'extranet_sort_document_type';
$columns['extranet_document_date'] = 'extranet_sort_document_date';
return $columns;
}
```
|
Building on Phil's answer:
Made the following change to the switch:
```
case 'extranet_sort_document_case':
add_filter('posts_join', 'extranet_clientdocument_case_join');
add_filter('posts_fields', 'extranet_clientdocument_case_fields');
add_filter('posts_orderby', 'extranet_clientdocument_case_order');
break;
```
and wrote the following functions:
```
function extranet_clientdocument_case_join($join) {
global $wpdb;
$join .= " LEFT JOIN ".$wpdb->postmeta." AS case_ids ON (".$wpdb->posts.".ID = case_ids.post_id AND case_ids.meta_key = 'extranet_client_area')
LEFT JOIN ".$wpdb->posts." AS case_names ON (case_names.ID = case_ids.meta_value) ";
return $join;
}
function extranet_clientdocument_case_fields($fields) {
$fields.=", case_names.post_title";
return $fields;
}
function extranet_clientdocument_case_order($order_by) {
if(isset($_GET['order'])) $direction = $_GET['order'];
else $direction = 'ASC';
$order_by = 'case_names.post_title '.$direction;
return($order_by);
}
```
This worked in terms of making the column sortable by the post name of the related custom post, rather than by the metadata itself. However, it created a new problem in that the Title of the main post being listed, which is unusually the second column, now turned into the post title of the related post. I fixed this with the following additional code:
```
function restore_original_title($title) {
global $wpdb;
$post_id = get_the_ID();
$get_document_name = $wpdb->get_results('SELECT * FROM `wp_posts` WHERE `ID` = '.$post_id);
$title = $get_document_name[0]->post_title;
return $title;
}
```
and added the following additional filter:
```
add_filter( 'the_title', 'restore_original_title', 10, 2 );
```
|
196,855 |
<p>I want to know if a user with a specific user id has logged in on my wordpress site.How can I achieve this accurately.</p>
|
[
{
"answer_id": 196865,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>try this code, it is in user-edit.php :<br>\n<code>$sessions = WP_Session_Tokens::get_instance( $profileuser->ID );</code></p>\n"
},
{
"answer_id": 196883,
"author": "markmoxx",
"author_id": 70674,
"author_profile": "https://wordpress.stackexchange.com/users/70674",
"pm_score": 1,
"selected": false,
"text": "<p>You could always try using the <code>wp_login</code> action hook:</p>\n\n<pre><code>function custom_check_for_user($user_login, $user) {\n if($user->ID == 123) { // Where 123 is the particular user's ID\n // Do something here, eg. PHP mail() function\n }\n}\nadd_action('wp_login', 'custom_check_for_user', 10, 2);\n</code></pre>\n\n<p>Further reading: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login</a></p>\n"
}
] |
2015/08/06
|
[
"https://wordpress.stackexchange.com/questions/196855",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77400/"
] |
I want to know if a user with a specific user id has logged in on my wordpress site.How can I achieve this accurately.
|
You could always try using the `wp_login` action hook:
```
function custom_check_for_user($user_login, $user) {
if($user->ID == 123) { // Where 123 is the particular user's ID
// Do something here, eg. PHP mail() function
}
}
add_action('wp_login', 'custom_check_for_user', 10, 2);
```
Further reading: <https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login>
|
196,868 |
<p>I'm trying to load a template via ajax if the user clicks on a button. This is the code I'm using:</p>
<p>On <code>functions.php</code>:</p>
<pre><code>function phantom_scripts() {
global $child_dir;
/* Ajax Requests */
wp_enqueue_script( 'ajax-stuff', get_stylesheet_directory_uri() . '/js/ajax.js', array( 'jquery' ), true );
}
add_action( 'wp_enqueue_scripts', 'phantom_scripts' );
function portfolio_ajax() {
include( 'templates/cards.php' );
die();
}
add_action('wp_ajax_nopriv_portfolio_ajax', 'portfolio_ajax');
add_action('wp_ajax_portfolio_ajax', 'portfolio_ajax');
wp_localize_script( 'ajax-stuff', 'ajaxStuff', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
</code></pre>
<p>On <code>ajax.js</code>:</p>
<pre><code>(function($) {
$('#load-cards').click(function() {
alert();
$.ajax({
url: ajaxurl,
data: {
action: 'portfolio_ajax'
},
success: function(data) {
$('#cards-container').append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
})(jQuery);
</code></pre>
<p><code>HTML</code>:</p>
<pre><code><a href="javascript:void(0)" id="load-cards">Load cards</a>
</code></pre>
<p>Right now, the console is not showing to me any error but is not loading the content I have in <code>templates/cards.php</code> file. Any idea what I'm missing?</p>
|
[
{
"answer_id": 196891,
"author": "Dougal Campbell",
"author_id": 65,
"author_profile": "https://wordpress.stackexchange.com/users/65",
"pm_score": 2,
"selected": true,
"text": "<p>So, you're using <code>wp_localize_script</code> to inject the ajax url. But you didn't use the localized var handle to access that value. Try this:</p>\n\n<pre><code>/* ... */\n$.ajax({\n url: ajaxStuff.ajaxurl, // NOTE use of 'ajaxStuff' object\n/* ... */\n</code></pre>\n"
},
{
"answer_id": 196998,
"author": "Lasse M. Tvedt",
"author_id": 40819,
"author_profile": "https://wordpress.stackexchange.com/users/40819",
"pm_score": 0,
"selected": false,
"text": "<p>First you need to do what Dougal said about getting the <strong>ajax-url</strong> right. I would also specify the <strong>dataType</strong>. dataType is the type of data that you're expecting back from the server, you can read more about it <a href=\"http://api.jquery.com/jquery.ajax/\" rel=\"nofollow\">here.</a></p>\n\n<p>And I would use wordpress's <a href=\"https://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\">get_template_part</a> to get the template. </p>\n"
}
] |
2015/08/06
|
[
"https://wordpress.stackexchange.com/questions/196868",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22933/"
] |
I'm trying to load a template via ajax if the user clicks on a button. This is the code I'm using:
On `functions.php`:
```
function phantom_scripts() {
global $child_dir;
/* Ajax Requests */
wp_enqueue_script( 'ajax-stuff', get_stylesheet_directory_uri() . '/js/ajax.js', array( 'jquery' ), true );
}
add_action( 'wp_enqueue_scripts', 'phantom_scripts' );
function portfolio_ajax() {
include( 'templates/cards.php' );
die();
}
add_action('wp_ajax_nopriv_portfolio_ajax', 'portfolio_ajax');
add_action('wp_ajax_portfolio_ajax', 'portfolio_ajax');
wp_localize_script( 'ajax-stuff', 'ajaxStuff', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
```
On `ajax.js`:
```
(function($) {
$('#load-cards').click(function() {
alert();
$.ajax({
url: ajaxurl,
data: {
action: 'portfolio_ajax'
},
success: function(data) {
$('#cards-container').append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
})(jQuery);
```
`HTML`:
```
<a href="javascript:void(0)" id="load-cards">Load cards</a>
```
Right now, the console is not showing to me any error but is not loading the content I have in `templates/cards.php` file. Any idea what I'm missing?
|
So, you're using `wp_localize_script` to inject the ajax url. But you didn't use the localized var handle to access that value. Try this:
```
/* ... */
$.ajax({
url: ajaxStuff.ajaxurl, // NOTE use of 'ajaxStuff' object
/* ... */
```
|
196,879 |
<p>I am trying to integrate a ‘subscribe to newsletter’ feature on my wordpress blog</p>
<p>Users just need to enter their name and email address, hit subscribe. This is then supposed to send me an email and I add them to the mailing list.</p>
<p>I activated the WP SMTP Mail plugin and entered in the relevant email server information to enable WordPress to send emails, asked WordPress to send me a test message and this worked.</p>
<p>Now I want to receive an email whenever someone fills in their name & email and hit subscribe.</p>
<p>If I do this at the moment it just does nothing, it re-loads the page without sending an email.</p>
<p>I have attached my code below, can anyone help me out here?</p>
<p>Code for the signup form <code>sidebar.php</code> - This is not a plugin.</p>
<pre><code> <form action="newsletter_signup.php" method="post">
<p><input class="full" type="text" name="name" placeholder="Your name*"></p>
<p><input class="full" type="email" name="Email" placeholder="Your email address*"></p>
<p><input type="submit" class="sub-btn" value="Subscribe"></p>
</form>
</code></pre>
<p>The code in the <code>newsletter_signup.php</code> file:</p>
<pre><code><?php
require_once('wp-load.php');
$name = $_POST['name'];
$Email = $_POST['Email'];
$to = '[email protected]';
wp_mail($to, $name, 'From: ' . $Email);
echo 'Your request Has Been Sent, Thank You. ';
?>
</code></pre>
|
[
{
"answer_id": 196891,
"author": "Dougal Campbell",
"author_id": 65,
"author_profile": "https://wordpress.stackexchange.com/users/65",
"pm_score": 2,
"selected": true,
"text": "<p>So, you're using <code>wp_localize_script</code> to inject the ajax url. But you didn't use the localized var handle to access that value. Try this:</p>\n\n<pre><code>/* ... */\n$.ajax({\n url: ajaxStuff.ajaxurl, // NOTE use of 'ajaxStuff' object\n/* ... */\n</code></pre>\n"
},
{
"answer_id": 196998,
"author": "Lasse M. Tvedt",
"author_id": 40819,
"author_profile": "https://wordpress.stackexchange.com/users/40819",
"pm_score": 0,
"selected": false,
"text": "<p>First you need to do what Dougal said about getting the <strong>ajax-url</strong> right. I would also specify the <strong>dataType</strong>. dataType is the type of data that you're expecting back from the server, you can read more about it <a href=\"http://api.jquery.com/jquery.ajax/\" rel=\"nofollow\">here.</a></p>\n\n<p>And I would use wordpress's <a href=\"https://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\">get_template_part</a> to get the template. </p>\n"
}
] |
2015/08/06
|
[
"https://wordpress.stackexchange.com/questions/196879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77410/"
] |
I am trying to integrate a ‘subscribe to newsletter’ feature on my wordpress blog
Users just need to enter their name and email address, hit subscribe. This is then supposed to send me an email and I add them to the mailing list.
I activated the WP SMTP Mail plugin and entered in the relevant email server information to enable WordPress to send emails, asked WordPress to send me a test message and this worked.
Now I want to receive an email whenever someone fills in their name & email and hit subscribe.
If I do this at the moment it just does nothing, it re-loads the page without sending an email.
I have attached my code below, can anyone help me out here?
Code for the signup form `sidebar.php` - This is not a plugin.
```
<form action="newsletter_signup.php" method="post">
<p><input class="full" type="text" name="name" placeholder="Your name*"></p>
<p><input class="full" type="email" name="Email" placeholder="Your email address*"></p>
<p><input type="submit" class="sub-btn" value="Subscribe"></p>
</form>
```
The code in the `newsletter_signup.php` file:
```
<?php
require_once('wp-load.php');
$name = $_POST['name'];
$Email = $_POST['Email'];
$to = '[email protected]';
wp_mail($to, $name, 'From: ' . $Email);
echo 'Your request Has Been Sent, Thank You. ';
?>
```
|
So, you're using `wp_localize_script` to inject the ajax url. But you didn't use the localized var handle to access that value. Try this:
```
/* ... */
$.ajax({
url: ajaxStuff.ajaxurl, // NOTE use of 'ajaxStuff' object
/* ... */
```
|
196,881 |
<p>I want to capture the click event on the "<strong>Save all changes</strong>" button? </p>
<p>Is there any callback method like there is when you click (<strong>window.send_to_editor</strong>) the "<strong>Insert into Post</strong>" button</p>
<p><a href="https://i.stack.imgur.com/CiEBa.jpg"><img src="https://i.stack.imgur.com/CiEBa.jpg" alt="Here is a screenshot"></a></p>
|
[
{
"answer_id": 196891,
"author": "Dougal Campbell",
"author_id": 65,
"author_profile": "https://wordpress.stackexchange.com/users/65",
"pm_score": 2,
"selected": true,
"text": "<p>So, you're using <code>wp_localize_script</code> to inject the ajax url. But you didn't use the localized var handle to access that value. Try this:</p>\n\n<pre><code>/* ... */\n$.ajax({\n url: ajaxStuff.ajaxurl, // NOTE use of 'ajaxStuff' object\n/* ... */\n</code></pre>\n"
},
{
"answer_id": 196998,
"author": "Lasse M. Tvedt",
"author_id": 40819,
"author_profile": "https://wordpress.stackexchange.com/users/40819",
"pm_score": 0,
"selected": false,
"text": "<p>First you need to do what Dougal said about getting the <strong>ajax-url</strong> right. I would also specify the <strong>dataType</strong>. dataType is the type of data that you're expecting back from the server, you can read more about it <a href=\"http://api.jquery.com/jquery.ajax/\" rel=\"nofollow\">here.</a></p>\n\n<p>And I would use wordpress's <a href=\"https://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\">get_template_part</a> to get the template. </p>\n"
}
] |
2015/08/06
|
[
"https://wordpress.stackexchange.com/questions/196881",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77411/"
] |
I want to capture the click event on the "**Save all changes**" button?
Is there any callback method like there is when you click (**window.send\_to\_editor**) the "**Insert into Post**" button
[](https://i.stack.imgur.com/CiEBa.jpg)
|
So, you're using `wp_localize_script` to inject the ajax url. But you didn't use the localized var handle to access that value. Try this:
```
/* ... */
$.ajax({
url: ajaxStuff.ajaxurl, // NOTE use of 'ajaxStuff' object
/* ... */
```
|
196,929 |
<p>I am new in buddypress. </p>
<p>My problem is: I have create a template for get member list based on role Like:</p>
<pre><code><?php if ( bp_has_members( bp_ajax_querystring( 'members' ). '&per_page=25&role=author' ) ) : ?>
<ul id="members-list" class="item-list row kleo-isotope masonry">
<?php while ( bp_members() ) : bp_the_member(); ?>
<li><a href="<?php bp_member_permalink(); ?>"><?php bp_member_avatar(); ?></a></li>
<?php endwhile; ?>
</ul>
</code></pre>
<p>But i am not getting user list based on role. Please help me and suggest me any idea.</p>
|
[
{
"answer_id": 196931,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>If you use this code directly below <code>while ( bp_members() ) : bp_the_member();</code> in the members loop, you’ll be able to see which members are author.</p>\n\n<pre><code><?php \n $user_id = bp_get_member_user_id(); \n $user = new WP_User( $user_id );\n\n if ( $user->roles[0] == 'author' ) {\n echo 'this user is an author';\n } \n?>\n</code></pre>\n\n<p>I know this isn’t exactly what you’d like to do but it should put you on the right track.</p>\n\n<p>Note: This code assumes that all of your users have a single role assigned. </p>\n"
},
{
"answer_id": 196977,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 2,
"selected": false,
"text": "<p>To preserve pagination, try:</p>\n\n<pre><code><?php \n$authors = get_users( array( 'fields' => 'ID', 'role' => 'author' ) );\n$authors = implode(',', $authors);\n?>\n\n<?php if ( bp_has_members( bp_ajax_querystring( 'members' ). '&per_page=25&include=' . $authors) ) : ?>\n//etc\n</code></pre>\n"
}
] |
2015/08/07
|
[
"https://wordpress.stackexchange.com/questions/196929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59532/"
] |
I am new in buddypress.
My problem is: I have create a template for get member list based on role Like:
```
<?php if ( bp_has_members( bp_ajax_querystring( 'members' ). '&per_page=25&role=author' ) ) : ?>
<ul id="members-list" class="item-list row kleo-isotope masonry">
<?php while ( bp_members() ) : bp_the_member(); ?>
<li><a href="<?php bp_member_permalink(); ?>"><?php bp_member_avatar(); ?></a></li>
<?php endwhile; ?>
</ul>
```
But i am not getting user list based on role. Please help me and suggest me any idea.
|
To preserve pagination, try:
```
<?php
$authors = get_users( array( 'fields' => 'ID', 'role' => 'author' ) );
$authors = implode(',', $authors);
?>
<?php if ( bp_has_members( bp_ajax_querystring( 'members' ). '&per_page=25&include=' . $authors) ) : ?>
//etc
```
|
196,952 |
<p>I am trying to display my menu, while menu is displaying perectly, it does have open within nav, which hide everything behind it, as navbar-fixed has come style. what should i be doing to fix the issue?</p>
<pre><code> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php bloginfo( 'url' ); ?>"><?php bloginfo( 'name' ); ?></a>
</div>
<div class="navbar-collapse collapse">
<?php
$args = array(
'menu' => 'header-menu',
'menu_class' => 'nav navbar-nav',
'container' => 'false'
);
wp_nav_menu( $args );
?>
</div><!--/.navbar-collapse -->
</div>
</nav>
</code></pre>
|
[
{
"answer_id": 196953,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Source: <a href=\"http://chrislema.com/high-performance-wordpress-membership-site/\" rel=\"nofollow\">Chris Lima - Managing a High Performance WordPress Membership Site</a></strong></p>\n\n<hr>\n\n<p>I should look at caching plugins because it makes things faster, better and worked for you. The problem with that answer is that most caching plugins don’t do much for logged in users.</p>\n\n<p>Most sites have is that non-logged in users should get pre-cached pages that load super fast, and logged-in users are the authors and admins who are working on the back-end, and don’t need the same level of performance. And for most sites, this works. But membership sites are a bit different.</p>\n\n<p>The end user is a logged-in user. So you need a solution that works for logged-in users. Additionally, membership sites are often filled with user-specific data (like menus, sidebar widgets, content..etc) that needs to be current. So full page caching isn’t a solution – from a plugin or hosting provider.</p>\n\n<p>Instead, what you need is part of page caching.</p>\n\n<p><strong>1. Part of page caching:</strong>\nthese kinds of approaches are neither in abundance, nor are they often talked about when you’re evaluating a membership plugin. I’m to blame too. There’s a great article explaining why it’s not great by <a href=\"http://wpengine.com/2013/02/wordpress-transient-api/\" rel=\"nofollow\">Austin Gunter of WP Engine</a> on their blog. Suffice to say, if your options table is growing like crazy, you may be doing it wrong.</p>\n\n<p>BTW, <a href=\"http://core.trac.wordpress.org/ticket/20316\" rel=\"nofollow\">garbage collection for transients</a> (an issue raised in Austin’s article) may get added to WordPress in 3.7</p>\n\n<p><strong>2. Fragment caching:</strong>\nYou can use a little class created by Mark Jaquith. He calls it <a href=\"http://markjaquith.wordpress.com/2013/04/26/fragment-caching-in-wordpress/\" rel=\"nofollow\">fragment caching</a>,\n but it’s not different from partial page caching. You’d want to check out this article that has the code in it, and read the comments.</p>\n\n<p>I think this is a pretty powerful option for a lot of situations, but scaling a membership site is all about limiting the application processing side of things.</p>\n\n<p>So finally there is one option that you need to try cache only database do not catch page data, browser data. I do not proposed to use <a href=\"https://wordpress.org/plugins/w3-total-cache/\" rel=\"nofollow\">W3 Total Cache</a> but check it once this plugin may be your solution.</p>\n"
},
{
"answer_id": 205086,
"author": "Cristián Lávaque",
"author_id": 81709,
"author_profile": "https://wordpress.stackexchange.com/users/81709",
"pm_score": 0,
"selected": false,
"text": "<p>@absikandar In this article I explain how I cache logged in user pages on my membership sites: <a href=\"http://s2member.net/how-to-cache-your-membership-site-225\" rel=\"nofollow\">http://s2member.net/how-to-cache-your-membership-site-225</a></p>\n\n<blockquote>\n <p>A better approach would be to cache separate copies of the page, unique for each logged in user. A member would not benefit from the cache someone else caused, but he'd still benefit from it when visiting the same page again.</p>\n</blockquote>\n\n<p>I hope that helps! :)</p>\n"
}
] |
2015/08/07
|
[
"https://wordpress.stackexchange.com/questions/196952",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33028/"
] |
I am trying to display my menu, while menu is displaying perectly, it does have open within nav, which hide everything behind it, as navbar-fixed has come style. what should i be doing to fix the issue?
```
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php bloginfo( 'url' ); ?>"><?php bloginfo( 'name' ); ?></a>
</div>
<div class="navbar-collapse collapse">
<?php
$args = array(
'menu' => 'header-menu',
'menu_class' => 'nav navbar-nav',
'container' => 'false'
);
wp_nav_menu( $args );
?>
</div><!--/.navbar-collapse -->
</div>
</nav>
```
|
**Source: [Chris Lima - Managing a High Performance WordPress Membership Site](http://chrislema.com/high-performance-wordpress-membership-site/)**
---
I should look at caching plugins because it makes things faster, better and worked for you. The problem with that answer is that most caching plugins don’t do much for logged in users.
Most sites have is that non-logged in users should get pre-cached pages that load super fast, and logged-in users are the authors and admins who are working on the back-end, and don’t need the same level of performance. And for most sites, this works. But membership sites are a bit different.
The end user is a logged-in user. So you need a solution that works for logged-in users. Additionally, membership sites are often filled with user-specific data (like menus, sidebar widgets, content..etc) that needs to be current. So full page caching isn’t a solution – from a plugin or hosting provider.
Instead, what you need is part of page caching.
**1. Part of page caching:**
these kinds of approaches are neither in abundance, nor are they often talked about when you’re evaluating a membership plugin. I’m to blame too. There’s a great article explaining why it’s not great by [Austin Gunter of WP Engine](http://wpengine.com/2013/02/wordpress-transient-api/) on their blog. Suffice to say, if your options table is growing like crazy, you may be doing it wrong.
BTW, [garbage collection for transients](http://core.trac.wordpress.org/ticket/20316) (an issue raised in Austin’s article) may get added to WordPress in 3.7
**2. Fragment caching:**
You can use a little class created by Mark Jaquith. He calls it [fragment caching](http://markjaquith.wordpress.com/2013/04/26/fragment-caching-in-wordpress/),
but it’s not different from partial page caching. You’d want to check out this article that has the code in it, and read the comments.
I think this is a pretty powerful option for a lot of situations, but scaling a membership site is all about limiting the application processing side of things.
So finally there is one option that you need to try cache only database do not catch page data, browser data. I do not proposed to use [W3 Total Cache](https://wordpress.org/plugins/w3-total-cache/) but check it once this plugin may be your solution.
|
196,960 |
<p>We know that we can check if the particular post has a term by using this code: </p>
<pre><code>has_term('term', 'taxonomy', $post->ID )) {
</code></pre>
<p>I was wondering if there is a code to check if a particular post does not have a particular term.
Thanks. </p>
|
[
{
"answer_id": 196964,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 4,
"selected": true,
"text": "<pre><code>if ( !has_term('term', 'taxonomy', $post->ID )) {\n</code></pre>\n\n<p>Use the NOT (<code>!</code>) operator</p>\n"
},
{
"answer_id": 246948,
"author": "Joe",
"author_id": 107469,
"author_profile": "https://wordpress.stackexchange.com/users/107469",
"pm_score": 1,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<pre><code>function myFunction() {\n $value = \"\";\n if( has_term( 'myterm', 'taxonomy' ) ) {\n $value = \"foo\";\n }\n elseif( has_term( 'nextterm', 'taxonomy' ) ) {\n $value = \"nextfoo\";\n }\n if( !empty( $value ) ) {\n echo \n //do something with \n $value;\n }\n}\n</code></pre>\n"
}
] |
2015/08/07
|
[
"https://wordpress.stackexchange.com/questions/196960",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13058/"
] |
We know that we can check if the particular post has a term by using this code:
```
has_term('term', 'taxonomy', $post->ID )) {
```
I was wondering if there is a code to check if a particular post does not have a particular term.
Thanks.
|
```
if ( !has_term('term', 'taxonomy', $post->ID )) {
```
Use the NOT (`!`) operator
|
196,990 |
<p>I am working on dailysuit.de, which features 8 related articles below the content in every post, defined by some tags.</p>
<p>Now I wanted to reduce the number of "posts per page" from 8 to 4. Of course, I can easily achieve that by changing the functions.php, but as soon as the theme gets an update, the figure is back to 8.</p>
<p>So, I wanted to change the function and add it to the child theme's functions.php:</p>
<pre><code>/* Related posts */
function longform_the_related_posts_change() {
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) {
$tag_ids[] = $individual_tag->term_id;
}
$args = array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => 4, // Number of related posts to display.
'ignore_sticky_posts' => 1
);
$my_query = new wp_query( $args ); ?>
<h2 class="related-articles-title"><?php _e( 'Related articles', 'longform' ); ?></h2>
<div class="related-articles">
<?php
while( $my_query->have_posts() ) {
$my_query->the_post(); ?>
<div class="related-thumb col-sm-3 col-md-3 col-lg-3">
<a rel="external" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(array(500,350)); ?>
<div class="related-content">
<h2><?php the_title(); ?></h2>
</div>
</a>
</div>
<?php } ?>
<div class="clearfix"></div>
</div>
<?php
}
wp_reset_postdata();
wp_reset_query();
}
add_filter( 'longform_the_related_posts', 'longform_the_related_posts_change' );
</code></pre>
<p>Unfortunately, that did not work. It still shows 8 relates posts instead of the 4, that I entered at "posts_per_page".</p>
<p>Anyone knows what is wrong there? Or is there a easier/shorter way without copying all this code?</p>
<p>I also tried the remove_filter thing, that was mentioned, but that did not work out either.</p>
<pre><code>longform_the_related_posts_child () {
remove_filter('longform_the_related_posts');
add_filter('longform_the_related_posts', array(
'longform_the_related_posts_filter' => 'longform_the_related_posts',
'posts_per_page' => 4,
) );
}
</code></pre>
|
[
{
"answer_id": 196992,
"author": "Pooja Mistry",
"author_id": 71675,
"author_profile": "https://wordpress.stackexchange.com/users/71675",
"pm_score": 0,
"selected": false,
"text": "<p>The above code looks okay. I think the reason why you are getting 8 posts instead of 4 is that, you still have a code that fetches 8 posts in parent theme's functions.php. </p>\n\n<p>Try removing filter of parent theme in child theme. Like this - </p>\n\n<pre><code>remove_filter('<filter_name>','<function_name>');\n</code></pre>\n\n<p>By doing this, parent themes's function would not take effect and child theme's code would work. </p>\n\n<p>For more info on remove_filter - <a href=\"https://codex.wordpress.org/Function_Reference/remove_filter\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/remove_filter</a></p>\n\n<p>Hope this helps. </p>\n"
},
{
"answer_id": 198191,
"author": "Pooja Mistry",
"author_id": 71675,
"author_profile": "https://wordpress.stackexchange.com/users/71675",
"pm_score": 2,
"selected": true,
"text": "<p>I have gone through your code and found that the function <code>longform_the_related_posts</code> displays 8 related posts. This function is defined in functions.php of parent theme and called in single.php. </p>\n\n<p>Thus, to override the function, follow below steps - <br>\n1. Create another function that displays 4 related posts in functions.php of child theme. (As you have already created function <code>longform_the_related_posts_change()</code> ) <br>\n2. Copy the file <code>single.php</code> from parent to child theme and replace the line 47 </p>\n\n<p>From </p>\n\n<pre><code>echo longform_the_related_posts();\n</code></pre>\n\n<p>To </p>\n\n<pre><code>echo longform_the_related_posts_change();\n</code></pre>\n\n<p>This would call the function that display 4 posts. <br>\nHope this helps. </p>\n"
}
] |
2015/08/07
|
[
"https://wordpress.stackexchange.com/questions/196990",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50311/"
] |
I am working on dailysuit.de, which features 8 related articles below the content in every post, defined by some tags.
Now I wanted to reduce the number of "posts per page" from 8 to 4. Of course, I can easily achieve that by changing the functions.php, but as soon as the theme gets an update, the figure is back to 8.
So, I wanted to change the function and add it to the child theme's functions.php:
```
/* Related posts */
function longform_the_related_posts_change() {
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) {
$tag_ids[] = $individual_tag->term_id;
}
$args = array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => 4, // Number of related posts to display.
'ignore_sticky_posts' => 1
);
$my_query = new wp_query( $args ); ?>
<h2 class="related-articles-title"><?php _e( 'Related articles', 'longform' ); ?></h2>
<div class="related-articles">
<?php
while( $my_query->have_posts() ) {
$my_query->the_post(); ?>
<div class="related-thumb col-sm-3 col-md-3 col-lg-3">
<a rel="external" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(array(500,350)); ?>
<div class="related-content">
<h2><?php the_title(); ?></h2>
</div>
</a>
</div>
<?php } ?>
<div class="clearfix"></div>
</div>
<?php
}
wp_reset_postdata();
wp_reset_query();
}
add_filter( 'longform_the_related_posts', 'longform_the_related_posts_change' );
```
Unfortunately, that did not work. It still shows 8 relates posts instead of the 4, that I entered at "posts\_per\_page".
Anyone knows what is wrong there? Or is there a easier/shorter way without copying all this code?
I also tried the remove\_filter thing, that was mentioned, but that did not work out either.
```
longform_the_related_posts_child () {
remove_filter('longform_the_related_posts');
add_filter('longform_the_related_posts', array(
'longform_the_related_posts_filter' => 'longform_the_related_posts',
'posts_per_page' => 4,
) );
}
```
|
I have gone through your code and found that the function `longform_the_related_posts` displays 8 related posts. This function is defined in functions.php of parent theme and called in single.php.
Thus, to override the function, follow below steps -
1. Create another function that displays 4 related posts in functions.php of child theme. (As you have already created function `longform_the_related_posts_change()` )
2. Copy the file `single.php` from parent to child theme and replace the line 47
From
```
echo longform_the_related_posts();
```
To
```
echo longform_the_related_posts_change();
```
This would call the function that display 4 posts.
Hope this helps.
|
196,995 |
<p>I am developing a WP theme with MVC approach. It only have <code>index.php</code>, <code>functions.php</code> and <code>styles.css</code> on the parent directory. So, I do not want to place page templates on it rather then I want to programmatically provide them from View classes while functionality from edit screen stays the same. </p>
<p>Users need to have page templates select option on the edit screen. How do I successfully add Items to the template dropdown?</p>
<p>I tried to hook into <a href="https://core.trac.wordpress.org/browser/trunk/src/wp-includes/class-wp-theme.php#L1022" rel="nofollow"><code>theme_page_templates</code></a> filter. </p>
<p><strong>Example code:</strong></p>
<pre><code>add_filter( 'theme_page_templates', function($templates){
$templates['my-page-template.php'] = "My Page Template";
return $templates;
});
</code></pre>
<p>This does not work because of the use of <a href="http://php.net/manual/en/function.array-intersect-assoc.php" rel="nofollow"><code>array_intersect_assoc()</code></a> on the filtered array, which removes the added page template item. I don't understand why this function is used. It seems you can only remove page template from the list but can not add a new one using the given filter.</p>
<p>Is there any other way around?</p>
|
[
{
"answer_id": 197041,
"author": "Sisir",
"author_id": 3094,
"author_profile": "https://wordpress.stackexchange.com/users/3094",
"pm_score": 1,
"selected": false,
"text": "<p>Got around with a ugly hack :-/. I will update the answer If I go with jQuery later on. The solution still requires to have template files but code for the template file loads from the <code>index.php</code></p>\n\n<ol>\n<li>I made a new <code>template/</code> directory and put all page template there.</li>\n<li>All page templates are blank. We need it only for them to show up on the dropdown.</li>\n<li>Use <code>template_include</code> filter to redirect to <code>index.php</code></li>\n</ol>\n\n<h2>Code</h2>\n\n<p><strong>Blank Page Template Example</strong></p>\n\n<pre><code><?php\n/*\nTemplate Name: No Sidebar\n *\n * */\n</code></pre>\n\n<p><strong>Filter</strong></p>\n\n<pre><code>add_filter( 'template_include', function ($template ) {\n\n if ( !is_page_template() )\n return $template;\n\n return locate_template( array( 'index.php' ), true );\n\n}, 99);\n</code></pre>\n\n<p><a href=\"https://core.trac.wordpress.org/ticket/33309\" rel=\"nofollow\">I have created a trac ticket</a> to allow adding templates via filter.</p>\n"
},
{
"answer_id": 198064,
"author": "MikeSchinkel",
"author_id": 89,
"author_profile": "https://wordpress.stackexchange.com/users/89",
"pm_score": 4,
"selected": true,
"text": "<p>I thought I would provide you with another approach. It is also a bit hackish, but it is general purpose and allows you to simply register the filename and label that you want to use, like so:</p>\n\n<pre><code>if ( class_exists( 'WPSE_196995_Page_Templates' ) ) { \n WPSE_196995_Page_Templates::register_page_template(\n 'My Page Template',\n 'my-page-template.php'\n );\n}\n</code></pre>\n\n<p>You could add the above code to your theme's <code>functions.php</code> file.</p>\n\n<p>To enable the above to actually work I implemented a self-contained class that could be used as a plugin or just copied into <code>functions.php</code>:</p>\n\n<pre><code><?php \n/**\n * Plugin Name: WPSE 196995 Page Templates\n *\n * Class WPSE_196995_Page_Templates\n *\n * Allows registering page templates via code.\n */\nclass WPSE_196995_Page_Templates {\n\n static $registered_templates = array();\n\n static function on_load() {\n\n /**\n * Add registered page templates to 'page_template' cache.\n * @note This hook is called just before page templates are loaded\n */\n add_action( 'default_page_template_title', array( __CLASS__, '_default_page_template_title' ) );\n }\n\n /**\n * Register page templates\n *\n * @param string $label\n * @param string $filename\n */\n static function register_page_template( $label, $filename ) {\n\n self::$registered_templates[ $filename ] = $label;\n\n }\n\n /**\n * Add registered page templates to 'page_template' cache.\n *\n * @param string $title\n *\n * @return string mixed\n */\n static function _default_page_template_title( $title ) {\n\n /**\n * @var WP_Theme $theme\n */\n $theme = wp_get_theme();\n\n /**\n * Access the cache the hard way since WP_Theme makes almost everything private\n */\n $cache_hash = md5( $theme->get_stylesheet_directory() );\n\n /**\n * Get the page templates as the 'page_templates' cache will already be primed\n */\n $page_templates = wp_cache_get( $key = \"page_templates-{$cache_hash}\", $group = 'themes' );\n\n /**\n * Add in registered page templates\n */\n $page_templates += self::$registered_templates;\n\n /**\n * Now update the cache, which is what the get_page_templates() uses.\n */\n wp_cache_set( $key, $page_templates, $group, 1800 );\n\n /**\n * We are using this hook as if it were an action.\n * So do not modify $title, just return it.\n */\n return $title;\n\n }\n\n}\nWPSE_196995_Page_Templates::on_load();\n</code></pre>\n\n<p>The class provides the <code>register_page_template()</code> method, of course, but to actually add your page template it updates the value for <code>'page_templates'</code> set in the object cache. </p>\n\n<p>It is a bit hacky because WordPress made most methods and properties of the <code>WP_Theme</code> class <code>private</code>, but fortunately they used the publicly-accessible WordPress object cache to store the values. And by updating the object cache in the <code>'default_page_template_title'</code> hook, which is called just before the page templates dropdown is generated and sent to the browser, we can get WordPress to display your page template(s), as you desired.</p>\n"
}
] |
2015/08/07
|
[
"https://wordpress.stackexchange.com/questions/196995",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3094/"
] |
I am developing a WP theme with MVC approach. It only have `index.php`, `functions.php` and `styles.css` on the parent directory. So, I do not want to place page templates on it rather then I want to programmatically provide them from View classes while functionality from edit screen stays the same.
Users need to have page templates select option on the edit screen. How do I successfully add Items to the template dropdown?
I tried to hook into [`theme_page_templates`](https://core.trac.wordpress.org/browser/trunk/src/wp-includes/class-wp-theme.php#L1022) filter.
**Example code:**
```
add_filter( 'theme_page_templates', function($templates){
$templates['my-page-template.php'] = "My Page Template";
return $templates;
});
```
This does not work because of the use of [`array_intersect_assoc()`](http://php.net/manual/en/function.array-intersect-assoc.php) on the filtered array, which removes the added page template item. I don't understand why this function is used. It seems you can only remove page template from the list but can not add a new one using the given filter.
Is there any other way around?
|
I thought I would provide you with another approach. It is also a bit hackish, but it is general purpose and allows you to simply register the filename and label that you want to use, like so:
```
if ( class_exists( 'WPSE_196995_Page_Templates' ) ) {
WPSE_196995_Page_Templates::register_page_template(
'My Page Template',
'my-page-template.php'
);
}
```
You could add the above code to your theme's `functions.php` file.
To enable the above to actually work I implemented a self-contained class that could be used as a plugin or just copied into `functions.php`:
```
<?php
/**
* Plugin Name: WPSE 196995 Page Templates
*
* Class WPSE_196995_Page_Templates
*
* Allows registering page templates via code.
*/
class WPSE_196995_Page_Templates {
static $registered_templates = array();
static function on_load() {
/**
* Add registered page templates to 'page_template' cache.
* @note This hook is called just before page templates are loaded
*/
add_action( 'default_page_template_title', array( __CLASS__, '_default_page_template_title' ) );
}
/**
* Register page templates
*
* @param string $label
* @param string $filename
*/
static function register_page_template( $label, $filename ) {
self::$registered_templates[ $filename ] = $label;
}
/**
* Add registered page templates to 'page_template' cache.
*
* @param string $title
*
* @return string mixed
*/
static function _default_page_template_title( $title ) {
/**
* @var WP_Theme $theme
*/
$theme = wp_get_theme();
/**
* Access the cache the hard way since WP_Theme makes almost everything private
*/
$cache_hash = md5( $theme->get_stylesheet_directory() );
/**
* Get the page templates as the 'page_templates' cache will already be primed
*/
$page_templates = wp_cache_get( $key = "page_templates-{$cache_hash}", $group = 'themes' );
/**
* Add in registered page templates
*/
$page_templates += self::$registered_templates;
/**
* Now update the cache, which is what the get_page_templates() uses.
*/
wp_cache_set( $key, $page_templates, $group, 1800 );
/**
* We are using this hook as if it were an action.
* So do not modify $title, just return it.
*/
return $title;
}
}
WPSE_196995_Page_Templates::on_load();
```
The class provides the `register_page_template()` method, of course, but to actually add your page template it updates the value for `'page_templates'` set in the object cache.
It is a bit hacky because WordPress made most methods and properties of the `WP_Theme` class `private`, but fortunately they used the publicly-accessible WordPress object cache to store the values. And by updating the object cache in the `'default_page_template_title'` hook, which is called just before the page templates dropdown is generated and sent to the browser, we can get WordPress to display your page template(s), as you desired.
|
197,001 |
<p>I've got a True/False value added to posts (Exclusive versus Curated) that was added via Advanced Custom Fields. How do I get that value to show up as a column on the Post list (/wp-admin/edit.php) to allow editors to quickly sort via that field?</p>
<p>I found this example (<a href="http://code.tutsplus.com/articles/add-a-custom-column-in-posts-and-custom-post-types-admin-screen--wp-24934" rel="nofollow">http://code.tutsplus.com/articles/add-a-custom-column-in-posts-and-custom-post-types-admin-screen--wp-24934</a>) for adding the post thumbnail, but do not know how to adjust to pull and ACF field in instead.</p>
<p>Field name is company_exclusive and type is True/False.</p>
<p>Any pointers would be appreciated.</p>
<p>Edit: I found this solution (<a href="http://olliebarker.co.uk/articles/2014/06/displaying-custom-fields-wordpress-admin-post-lists/" rel="nofollow">http://olliebarker.co.uk/articles/2014/06/displaying-custom-fields-wordpress-admin-post-lists/</a>), and adapted its code to my needs, but after creating this, I'm not seeing the fields in on wp-admin/edit.php screen (either in Screen options or visible). I'm adding it to my theme's functions.php. That is the right place, correct?</p>
<pre><code>//Adds ACF fields to Post List
add_filter('posts_columns', 'custom_posts_table_head');
function custom_posts_table_head( $columns ) {
$columns['author_name'] = 'Author Name';
$columns['company_exclusive'] = 'Company Exclusive?';
$columns['region'] = 'Region';
$columns['article_excerpt_title'] = 'Article Excerpt Title';
return $columns;
}
add_action( 'posts_columns', 'custom_posts_table_content', 10, 2);
function bs_projects_table_content( $column_name, $post_id ) {
if( $column_name == 'author_name' ) {
$author_name = get_post_meta( $post_id, 'author_name', true );
echo $author_name;
}
if( $column_name == 'company_exclusive' ) {
$company_exclusive = get_post_meta( $post_id, 'company_exclusive', true );
if( $company_exclusive == '1' ) { echo 'Yes'; } else { echo 'No'; }
}
if( $column_name == 'region' ) {
$region = get_post_meta( $post_id, 'region', true );
echo $region;
}
if( $column_name == 'article_excerpt_title' ) {
$article_excerpt_title = get_post_meta( $post_id, 'article_excerpt_title', true );
echo $article_excerpt_title;
}
}
</code></pre>
|
[
{
"answer_id": 198528,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>You've got your action/filter names slightly off:</p>\n\n<pre><code>// For registering the column\nadd_filter( 'manage_posts_columns', 'custom_posts_table_head' );\n\n// For rendering the column\nadd_action( 'manage_posts_custom_column', 'custom_posts_table_content', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 205574,
"author": "Rijo",
"author_id": 81858,
"author_profile": "https://wordpress.stackexchange.com/users/81858",
"pm_score": 2,
"selected": false,
"text": "<p>I used following code to specify featured products in admin panel product list.</p>\n\n<pre><code>add_filter('manage_product_posts_columns', 'hs_product_table_head');\nfunction hs_product_table_head( $columns ) {\n $columns['product_featured'] = 'Featured';\n return $columns;\n\n}\nadd_action( 'manage_product_posts_custom_column', 'hs_product_table_content', 10, 2 );\n\nfunction hs_product_table_content( $column_name, $post_id ) {\n if( $column_name == 'product_featured' ) {\n $featured_product = get_post_meta( $post_id, 'featured_product', true );\n if($featured_product == 1) {\n echo \"Yes\";\n }\n }\n}\n</code></pre>\n\n<p>To use this for other post types - change the following code. For example - post type is \"portfolio\"</p>\n\n<pre><code>add_filter('manage_portfolio_posts_columns', 'hs_portfolio_table_head');\nadd_action( 'manage_portfolio_posts_custom_column', 'hs_portfolio_table_content', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 219665,
"author": "Julian Alvarado",
"author_id": 89951,
"author_profile": "https://wordpress.stackexchange.com/users/89951",
"pm_score": 1,
"selected": false,
"text": "<p>For Advanced Custom Fields, put this code in <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'manage_faq_posts_columns', 'set_custom_edit_faq_columns' ); \nadd_action( 'manage_faq_posts_custom_column' , 'custom_faq_column', 10, 2 );\n\nfunction set_custom_edit_faq_columns($columns) { \n unset( $columns['author'] );\n $columns['is_useful'] = 'Is Useful';\n $columns['is_unless'] = 'Is Unless';\n return $columns; \n}\n\nfunction custom_faq_column( $column, $post_id ) { \n global $post;\n switch ( $column ) {\n case 'is_useful' :\n if(get_field( \"is_useful\", $post_id )) {\n echo get_field( \"is_useful\", $post_id );\n } else {\n echo 0;\n }\n break;\n\n case 'is_unless' :\n if(get_field( \"is_unless\", $post_id )) {\n echo get_field( \"is_unless\", $post_id );\n } else {\n echo 0;\n }\n break; \n } \n}\n\nfunction my_column_register_sortable( $columns ) {\n $columns['is_useful'] = 'is_useful';\n $columns['is_unless'] = 'is_unless';\n return $columns;\n}\n\nadd_filter(\"manage_edit-faq_sortable_columns\", \"my_column_register_sortable\" );\n</code></pre>\n"
},
{
"answer_id": 395413,
"author": "Sergio Zaharchenko",
"author_id": 136533,
"author_profile": "https://wordpress.stackexchange.com/users/136533",
"pm_score": 0,
"selected": false,
"text": "<p>I've made a plugin that does exactly what you need without writing any line of code - Posts Columns Manager - <a href=\"https://wordpress.org/plugins/posts-columns-manager/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/posts-columns-manager/</a>.</p>\n<p>You can add any custom fields to your posts overview page just with a few clicks.</p>\n<p>It supports custom post types, any meta fields, and even fields generated by the ACF plugin.</p>\n"
}
] |
2015/08/07
|
[
"https://wordpress.stackexchange.com/questions/197001",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10692/"
] |
I've got a True/False value added to posts (Exclusive versus Curated) that was added via Advanced Custom Fields. How do I get that value to show up as a column on the Post list (/wp-admin/edit.php) to allow editors to quickly sort via that field?
I found this example (<http://code.tutsplus.com/articles/add-a-custom-column-in-posts-and-custom-post-types-admin-screen--wp-24934>) for adding the post thumbnail, but do not know how to adjust to pull and ACF field in instead.
Field name is company\_exclusive and type is True/False.
Any pointers would be appreciated.
Edit: I found this solution (<http://olliebarker.co.uk/articles/2014/06/displaying-custom-fields-wordpress-admin-post-lists/>), and adapted its code to my needs, but after creating this, I'm not seeing the fields in on wp-admin/edit.php screen (either in Screen options or visible). I'm adding it to my theme's functions.php. That is the right place, correct?
```
//Adds ACF fields to Post List
add_filter('posts_columns', 'custom_posts_table_head');
function custom_posts_table_head( $columns ) {
$columns['author_name'] = 'Author Name';
$columns['company_exclusive'] = 'Company Exclusive?';
$columns['region'] = 'Region';
$columns['article_excerpt_title'] = 'Article Excerpt Title';
return $columns;
}
add_action( 'posts_columns', 'custom_posts_table_content', 10, 2);
function bs_projects_table_content( $column_name, $post_id ) {
if( $column_name == 'author_name' ) {
$author_name = get_post_meta( $post_id, 'author_name', true );
echo $author_name;
}
if( $column_name == 'company_exclusive' ) {
$company_exclusive = get_post_meta( $post_id, 'company_exclusive', true );
if( $company_exclusive == '1' ) { echo 'Yes'; } else { echo 'No'; }
}
if( $column_name == 'region' ) {
$region = get_post_meta( $post_id, 'region', true );
echo $region;
}
if( $column_name == 'article_excerpt_title' ) {
$article_excerpt_title = get_post_meta( $post_id, 'article_excerpt_title', true );
echo $article_excerpt_title;
}
}
```
|
You've got your action/filter names slightly off:
```
// For registering the column
add_filter( 'manage_posts_columns', 'custom_posts_table_head' );
// For rendering the column
add_action( 'manage_posts_custom_column', 'custom_posts_table_content', 10, 2 );
```
|
197,011 |
<p>I'm attempting to <a href="https://wordpress.stackexchange.com/questions/87017/pulling-featured-images-in-to-a-wordpress-menu">add thumbnails to navigation items as per this question</a>. However, after adding the sample code to the top of my functions.php file nothing happens. I've whittled the code down in an attempt to get anything to happen. The code is now this:</p>
<pre><code>add_filter('wp_nav_menu_objects', 'ad_filter_menu', 10, 2);
function ad_filter_menu($sorted_menu_objects, $args) {
return '';
}
</code></pre>
<p>Still nothing is happening. The menu appears absolutely normally.</p>
<p>Heres the code thats generating the menu in header.php:</p>
<pre><code><?php wp_nav_menu( array( 'theme_location' => 'main-menu' ) ); ?>
</code></pre>
<p>What am I missing?</p>
|
[
{
"answer_id": 198528,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>You've got your action/filter names slightly off:</p>\n\n<pre><code>// For registering the column\nadd_filter( 'manage_posts_columns', 'custom_posts_table_head' );\n\n// For rendering the column\nadd_action( 'manage_posts_custom_column', 'custom_posts_table_content', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 205574,
"author": "Rijo",
"author_id": 81858,
"author_profile": "https://wordpress.stackexchange.com/users/81858",
"pm_score": 2,
"selected": false,
"text": "<p>I used following code to specify featured products in admin panel product list.</p>\n\n<pre><code>add_filter('manage_product_posts_columns', 'hs_product_table_head');\nfunction hs_product_table_head( $columns ) {\n $columns['product_featured'] = 'Featured';\n return $columns;\n\n}\nadd_action( 'manage_product_posts_custom_column', 'hs_product_table_content', 10, 2 );\n\nfunction hs_product_table_content( $column_name, $post_id ) {\n if( $column_name == 'product_featured' ) {\n $featured_product = get_post_meta( $post_id, 'featured_product', true );\n if($featured_product == 1) {\n echo \"Yes\";\n }\n }\n}\n</code></pre>\n\n<p>To use this for other post types - change the following code. For example - post type is \"portfolio\"</p>\n\n<pre><code>add_filter('manage_portfolio_posts_columns', 'hs_portfolio_table_head');\nadd_action( 'manage_portfolio_posts_custom_column', 'hs_portfolio_table_content', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 219665,
"author": "Julian Alvarado",
"author_id": 89951,
"author_profile": "https://wordpress.stackexchange.com/users/89951",
"pm_score": 1,
"selected": false,
"text": "<p>For Advanced Custom Fields, put this code in <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'manage_faq_posts_columns', 'set_custom_edit_faq_columns' ); \nadd_action( 'manage_faq_posts_custom_column' , 'custom_faq_column', 10, 2 );\n\nfunction set_custom_edit_faq_columns($columns) { \n unset( $columns['author'] );\n $columns['is_useful'] = 'Is Useful';\n $columns['is_unless'] = 'Is Unless';\n return $columns; \n}\n\nfunction custom_faq_column( $column, $post_id ) { \n global $post;\n switch ( $column ) {\n case 'is_useful' :\n if(get_field( \"is_useful\", $post_id )) {\n echo get_field( \"is_useful\", $post_id );\n } else {\n echo 0;\n }\n break;\n\n case 'is_unless' :\n if(get_field( \"is_unless\", $post_id )) {\n echo get_field( \"is_unless\", $post_id );\n } else {\n echo 0;\n }\n break; \n } \n}\n\nfunction my_column_register_sortable( $columns ) {\n $columns['is_useful'] = 'is_useful';\n $columns['is_unless'] = 'is_unless';\n return $columns;\n}\n\nadd_filter(\"manage_edit-faq_sortable_columns\", \"my_column_register_sortable\" );\n</code></pre>\n"
},
{
"answer_id": 395413,
"author": "Sergio Zaharchenko",
"author_id": 136533,
"author_profile": "https://wordpress.stackexchange.com/users/136533",
"pm_score": 0,
"selected": false,
"text": "<p>I've made a plugin that does exactly what you need without writing any line of code - Posts Columns Manager - <a href=\"https://wordpress.org/plugins/posts-columns-manager/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/posts-columns-manager/</a>.</p>\n<p>You can add any custom fields to your posts overview page just with a few clicks.</p>\n<p>It supports custom post types, any meta fields, and even fields generated by the ACF plugin.</p>\n"
}
] |
2015/08/07
|
[
"https://wordpress.stackexchange.com/questions/197011",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43552/"
] |
I'm attempting to [add thumbnails to navigation items as per this question](https://wordpress.stackexchange.com/questions/87017/pulling-featured-images-in-to-a-wordpress-menu). However, after adding the sample code to the top of my functions.php file nothing happens. I've whittled the code down in an attempt to get anything to happen. The code is now this:
```
add_filter('wp_nav_menu_objects', 'ad_filter_menu', 10, 2);
function ad_filter_menu($sorted_menu_objects, $args) {
return '';
}
```
Still nothing is happening. The menu appears absolutely normally.
Heres the code thats generating the menu in header.php:
```
<?php wp_nav_menu( array( 'theme_location' => 'main-menu' ) ); ?>
```
What am I missing?
|
You've got your action/filter names slightly off:
```
// For registering the column
add_filter( 'manage_posts_columns', 'custom_posts_table_head' );
// For rendering the column
add_action( 'manage_posts_custom_column', 'custom_posts_table_content', 10, 2 );
```
|
197,019 |
<p>I have searched Stack and the codex but can't find a simple solution for limiting the number of posts returned to one using the following:</p>
<pre><code><?php query_posts('cat=24'); ?>
<?php while (have_posts()) : the_post(); ?>
<?php the_field('alert'); ?>
<?php endwhile;?>
</code></pre>
|
[
{
"answer_id": 197022,
"author": "Dejo Dekic",
"author_id": 20941,
"author_profile": "https://wordpress.stackexchange.com/users/20941",
"pm_score": 2,
"selected": true,
"text": "<pre><code><?php query_posts('cat=24&posts_per_page=1'); ?>\n</code></pre>\n\n<p>But using query_posts is a <b><a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow\">very bad idea</a></b>.</p>\n\n<p>This is straigt from the Codex:</p>\n\n<p>For general post queries, use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">WP_Query</a> or <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow\">get_posts</a>.</p>\n\n<p>It is <strong>strongly</strong> recommended that you use the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\">pre_get_posts</a> filter instead, and alter the main query by checking <a href=\"https://codex.wordpress.org/Function_Reference/is_main_query\" rel=\"nofollow\">is_main_query</a>. </p>\n"
},
{
"answer_id": 197027,
"author": "forrest",
"author_id": 48611,
"author_profile": "https://wordpress.stackexchange.com/users/48611",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to Dejo for the correct answer on this. I just wanted to post what this would look like using the get_posts approach he mentions above:</p>\n\n<pre><code><?php \n$args = array( 'posts_per_page' => 1, 'offset'=> 0, 'category' => 24 );\n$myposts = get_posts( $args );\nforeach ( $myposts as $post ) : setup_postdata( $post ); ?>\n<?php the_field('alert'); ?>\n<?php endforeach; \nwp_reset_postdata();\n?>\n</code></pre>\n"
}
] |
2015/08/07
|
[
"https://wordpress.stackexchange.com/questions/197019",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48611/"
] |
I have searched Stack and the codex but can't find a simple solution for limiting the number of posts returned to one using the following:
```
<?php query_posts('cat=24'); ?>
<?php while (have_posts()) : the_post(); ?>
<?php the_field('alert'); ?>
<?php endwhile;?>
```
|
```
<?php query_posts('cat=24&posts_per_page=1'); ?>
```
But using query\_posts is a **[very bad idea](https://codex.wordpress.org/Function_Reference/query_posts)**.
This is straigt from the Codex:
For general post queries, use [WP\_Query](https://codex.wordpress.org/Class_Reference/WP_Query) or [get\_posts](https://codex.wordpress.org/Template_Tags/get_posts).
It is **strongly** recommended that you use the [pre\_get\_posts](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) filter instead, and alter the main query by checking [is\_main\_query](https://codex.wordpress.org/Function_Reference/is_main_query).
|
197,036 |
<p>i want code that show display some category and sort by acf field.</p>
<p>for example show all post from category 122,123,124 and sort all of them by acf (for example : lastname ). please write code for me. </p>
<p>my code is : </p>
<pre><code><?php
query_posts('cat=1,2&post_status=publish&posts_per_page=1');
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<a href="<?php the_permalink(); ?>"><?php the_title (); ?></a>
<?php
endwhile; else:
endif;
//Reset Query
wp_reset_query(); ?>
</code></pre>
<p>please help me. thanks</p>
|
[
{
"answer_id": 197022,
"author": "Dejo Dekic",
"author_id": 20941,
"author_profile": "https://wordpress.stackexchange.com/users/20941",
"pm_score": 2,
"selected": true,
"text": "<pre><code><?php query_posts('cat=24&posts_per_page=1'); ?>\n</code></pre>\n\n<p>But using query_posts is a <b><a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow\">very bad idea</a></b>.</p>\n\n<p>This is straigt from the Codex:</p>\n\n<p>For general post queries, use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">WP_Query</a> or <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow\">get_posts</a>.</p>\n\n<p>It is <strong>strongly</strong> recommended that you use the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\">pre_get_posts</a> filter instead, and alter the main query by checking <a href=\"https://codex.wordpress.org/Function_Reference/is_main_query\" rel=\"nofollow\">is_main_query</a>. </p>\n"
},
{
"answer_id": 197027,
"author": "forrest",
"author_id": 48611,
"author_profile": "https://wordpress.stackexchange.com/users/48611",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to Dejo for the correct answer on this. I just wanted to post what this would look like using the get_posts approach he mentions above:</p>\n\n<pre><code><?php \n$args = array( 'posts_per_page' => 1, 'offset'=> 0, 'category' => 24 );\n$myposts = get_posts( $args );\nforeach ( $myposts as $post ) : setup_postdata( $post ); ?>\n<?php the_field('alert'); ?>\n<?php endforeach; \nwp_reset_postdata();\n?>\n</code></pre>\n"
}
] |
2015/08/08
|
[
"https://wordpress.stackexchange.com/questions/197036",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77475/"
] |
i want code that show display some category and sort by acf field.
for example show all post from category 122,123,124 and sort all of them by acf (for example : lastname ). please write code for me.
my code is :
```
<?php
query_posts('cat=1,2&post_status=publish&posts_per_page=1');
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<a href="<?php the_permalink(); ?>"><?php the_title (); ?></a>
<?php
endwhile; else:
endif;
//Reset Query
wp_reset_query(); ?>
```
please help me. thanks
|
```
<?php query_posts('cat=24&posts_per_page=1'); ?>
```
But using query\_posts is a **[very bad idea](https://codex.wordpress.org/Function_Reference/query_posts)**.
This is straigt from the Codex:
For general post queries, use [WP\_Query](https://codex.wordpress.org/Class_Reference/WP_Query) or [get\_posts](https://codex.wordpress.org/Template_Tags/get_posts).
It is **strongly** recommended that you use the [pre\_get\_posts](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) filter instead, and alter the main query by checking [is\_main\_query](https://codex.wordpress.org/Function_Reference/is_main_query).
|
197,053 |
<p>how i can get posts via MYSQL from posts where language is 'en' and 'ru'</p>
<p>I have this query</p>
<pre><code>$sql = "SELECT p1.*, wm2.meta_value
FROM wp_posts p1
LEFT JOIN wp_postmeta wm1 ON ( wm1.post_id = p1.ID
AND wm1.meta_value IS NOT NULL
AND wm1.meta_key = '_thumbnail_id' )
LEFT JOIN wp_postmeta wm2 ON ( wm1.meta_value = wm2.post_id
AND wm2.meta_key = '_wp_attached_file'
AND wm2.meta_value IS NOT NULL )
WHERE p1.post_status= 'publish' AND p1.post_type='post' ORDER BY p1.post_date DESC Limit 3";
</code></pre>
<p>I use WPML plugin.</p>
|
[
{
"answer_id": 197055,
"author": "Valeriy Donika",
"author_id": 57628,
"author_profile": "https://wordpress.stackexchange.com/users/57628",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$sql = \"SELECT p1.*, wm2.meta_value \n FROM wp_posts p1 \n JOIN wp_icl_translations t\n ON p1.ID = t.element_id \n LEFT JOIN wp_postmeta wm1 ON ( wm1.post_id = p1.ID \n AND wm1.meta_value IS NOT NULL \n AND wm1.meta_key = '_thumbnail_id' ) \n LEFT JOIN wp_postmeta wm2 ON ( wm1.meta_value = wm2.post_id \n AND wm2.meta_key = '_wp_attached_file' \n AND wm2.meta_value IS NOT NULL ) \n WHERE p1.post_status= 'publish' \n AND p1.post_type='post' \n AND t.element_type='post_post'\n AND t.language_code='ru' \n ORDER BY p1.post_date DESC \n Limit 0, 3\";\n</code></pre>\n\n<p>get last 3 posts with thumb where lang is ru </p>\n"
},
{
"answer_id": 254906,
"author": "Jose Carlos Ramos Carmenates",
"author_id": 29090,
"author_profile": "https://wordpress.stackexchange.com/users/29090",
"pm_score": 1,
"selected": false,
"text": "<p>I resolved creating SQL query:</p>\n\n<pre><code>SELECT posts.post_title, posts.post_content, trans.element_type,\ntrans.language_code\nFROM wp_posts AS posts\n\nINNER JOIN wp_icl_translations AS trans\nON posts.ID = trans.element_id\n\nINNER JOIN wp_postmeta AS meta\nON posts.ID = meta.post_id\n\nWHERE trans.element_type = 'post_product'\nAND trans.language_code = 'de'\n</code></pre>\n\n<p>This is added only if you need something on post_meta:</p>\n\n<pre><code>...\nINNER JOIN wp_postmeta AS meta\nON posts.ID = meta.post_id\n...\n</code></pre>\n\n<p>It was my solutions to get all post by language <code>trans.language_code = 'de'</code>, <code>trans.language_code = 'es'</code>, <code>trans.language_code = 'en'</code> ...</p>\n"
}
] |
2015/08/08
|
[
"https://wordpress.stackexchange.com/questions/197053",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57628/"
] |
how i can get posts via MYSQL from posts where language is 'en' and 'ru'
I have this query
```
$sql = "SELECT p1.*, wm2.meta_value
FROM wp_posts p1
LEFT JOIN wp_postmeta wm1 ON ( wm1.post_id = p1.ID
AND wm1.meta_value IS NOT NULL
AND wm1.meta_key = '_thumbnail_id' )
LEFT JOIN wp_postmeta wm2 ON ( wm1.meta_value = wm2.post_id
AND wm2.meta_key = '_wp_attached_file'
AND wm2.meta_value IS NOT NULL )
WHERE p1.post_status= 'publish' AND p1.post_type='post' ORDER BY p1.post_date DESC Limit 3";
```
I use WPML plugin.
|
I resolved creating SQL query:
```
SELECT posts.post_title, posts.post_content, trans.element_type,
trans.language_code
FROM wp_posts AS posts
INNER JOIN wp_icl_translations AS trans
ON posts.ID = trans.element_id
INNER JOIN wp_postmeta AS meta
ON posts.ID = meta.post_id
WHERE trans.element_type = 'post_product'
AND trans.language_code = 'de'
```
This is added only if you need something on post\_meta:
```
...
INNER JOIN wp_postmeta AS meta
ON posts.ID = meta.post_id
...
```
It was my solutions to get all post by language `trans.language_code = 'de'`, `trans.language_code = 'es'`, `trans.language_code = 'en'` ...
|
198,075 |
<p>I have a plugin that prepends an upvote box to <code>the_content</code> of a single post, sends data via AJAX back to the main plugin PHP file and calls a function to update a database value on success.</p>
<p>Here is the PHP callback from the AJAX:</p>
<pre><code>function update_parlay_points() {
//Update Parlay Points field on database with points from Post request.
//global $post;
//$post_id = $post->ID;
$post_id = get_the_ID();
$points = $_POST['score'];
$update_points = "UPDATE wp_posts
SET parlay_points = '$points'
WHERE id = $post_id";
var_dump( $post_id );
echo $update_points;
global $mysqli;
$mysqli->query( $update_points ) or die( "Query failed" );
wp_die();
}
</code></pre>
<p>In Chrome's Developer tools, this gives me:</p>
<blockquote>
<p>bool(false) UPDATE wp_posts SET parlay_points = '26' WHERE id = Query
failed</p>
</blockquote>
<p>As you can see, I tried declaring the <code>$post</code> variable as global to account for failures due to being outside of the Loop. The content that triggers the AJAX request is prepended to <code>the_content</code>, so I am not sure if I need to "enter" the Loop again somehow. I tried <code>if ( have_posts() )</code> and <code>if ( is_single() )</code> before <code>get_the_ID()</code> with no success. The Loop, in general, really confuses me. </p>
<p>I have also tried accessing <code>$post->ID</code> from the action hook <code>the_post</code>. Strangely enough, I am able to successfully echo the current post's ID but cannot store it in a globally scoped variable. </p>
<pre><code>$post_id = Null;
add_action( 'the_post', 'wp_store_post_info' );
function wp_store_post_info() {
//Set current post as global variable.
global $post;
global $post_id;
$post_id = $post->ID;
echo $post_id;
}
function update_parlay_points() {
//...
global $post_id;
//Do stuff with the $post_id...
}
</code></pre>
<p>This does not work either:</p>
<pre><code>$GLOBALS['post_id'] = $post->ID;
</code></pre>
<p>I am certain that the above function is being called, because the correct <code>$post_id</code> is being echoed. However, when I click the upvote button I get:</p>
<blockquote>
<p>NULL UPDATE wp_posts SET parlay_points = '28' WHERE id = Failed Query</p>
</blockquote>
|
[
{
"answer_id": 198104,
"author": "Lasse M. Tvedt",
"author_id": 40819,
"author_profile": "https://wordpress.stackexchange.com/users/40819",
"pm_score": 0,
"selected": false,
"text": "<p>What about sending the post id of the single post trough ajax as well? So if you create a hidden input that contains the id, something like this: </p>\n\n<pre><code><input type=\"hidden\" id=\"post_id\" name=\"post_id\" value=\"<?php echo $post->ID; ?>\">\n</code></pre>\n\n<p>Then you can just pick the id and send it trough the ajax request, so your function will end up looking something like this: </p>\n\n<pre><code>function update_parlay_points() {\n\n //Update Parlay Points field on database with points from Post request. \n $post_id = $_POST['post_id'];\n $points = $_POST['score']; \n\n $update_points = \"UPDATE wp_posts \n SET parlay_points = '$points' \n WHERE id = $post_id\"; \n\n var_dump( $post_id );\n\n echo $update_points; \n\n global $mysqli;\n $mysqli->query( $update_points ) or die( \"Query failed\" );\n\n wp_die();\n} \n</code></pre>\n\n<p>I would also check out the <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow\">$wpdb Object</a>, insted of using $mysqli to handle the DB quieres.</p>\n"
},
{
"answer_id": 198106,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>As you can see, I tried declaring the $post variable as global to account for failures due to being outside of the Loop. </p>\n</blockquote>\n\n<p>The problem is <strong>not</strong> that the post is <em>\"outside of the loop\"</em>, problem is that AJAX request is a completely separate HTTP request.</p>\n\n<p>When you do an AJAX request, is just like you are opening a new window on browser and open the url in this separate window. It means that the script that handles the AJAX request knows <strong>nothing</strong> about the page that sent the request.</p>\n\n<p>If you need to process a specific post in the AJAX request, you need to send the post ID to process as part of the AJAX request data.</p>\n"
},
{
"answer_id": 198177,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 1,
"selected": false,
"text": "<p>My suggesion is to use <code>wp_localize_script()</code> to pass the post id to your AJAX calls.<br>\nSomething like this..</p>\n\n<pre><code>function my_script_enqueue() {\n global $post;\n\n $translations = array(\n 'postID' => $post->ID\n );\n\n wp_enqueue_script( 'myscript', '/url/to/your/script.js', array('jquery') );\n wp_localize_script( 'myscript', 'MyAJAX', $translations );\n}\nadd_action('wp_enqueue_scripts', 'my_script_enqueue')\n</code></pre>\n"
}
] |
2015/08/08
|
[
"https://wordpress.stackexchange.com/questions/198075",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77501/"
] |
I have a plugin that prepends an upvote box to `the_content` of a single post, sends data via AJAX back to the main plugin PHP file and calls a function to update a database value on success.
Here is the PHP callback from the AJAX:
```
function update_parlay_points() {
//Update Parlay Points field on database with points from Post request.
//global $post;
//$post_id = $post->ID;
$post_id = get_the_ID();
$points = $_POST['score'];
$update_points = "UPDATE wp_posts
SET parlay_points = '$points'
WHERE id = $post_id";
var_dump( $post_id );
echo $update_points;
global $mysqli;
$mysqli->query( $update_points ) or die( "Query failed" );
wp_die();
}
```
In Chrome's Developer tools, this gives me:
>
> bool(false) UPDATE wp\_posts SET parlay\_points = '26' WHERE id = Query
> failed
>
>
>
As you can see, I tried declaring the `$post` variable as global to account for failures due to being outside of the Loop. The content that triggers the AJAX request is prepended to `the_content`, so I am not sure if I need to "enter" the Loop again somehow. I tried `if ( have_posts() )` and `if ( is_single() )` before `get_the_ID()` with no success. The Loop, in general, really confuses me.
I have also tried accessing `$post->ID` from the action hook `the_post`. Strangely enough, I am able to successfully echo the current post's ID but cannot store it in a globally scoped variable.
```
$post_id = Null;
add_action( 'the_post', 'wp_store_post_info' );
function wp_store_post_info() {
//Set current post as global variable.
global $post;
global $post_id;
$post_id = $post->ID;
echo $post_id;
}
function update_parlay_points() {
//...
global $post_id;
//Do stuff with the $post_id...
}
```
This does not work either:
```
$GLOBALS['post_id'] = $post->ID;
```
I am certain that the above function is being called, because the correct `$post_id` is being echoed. However, when I click the upvote button I get:
>
> NULL UPDATE wp\_posts SET parlay\_points = '28' WHERE id = Failed Query
>
>
>
|
>
> As you can see, I tried declaring the $post variable as global to account for failures due to being outside of the Loop.
>
>
>
The problem is **not** that the post is *"outside of the loop"*, problem is that AJAX request is a completely separate HTTP request.
When you do an AJAX request, is just like you are opening a new window on browser and open the url in this separate window. It means that the script that handles the AJAX request knows **nothing** about the page that sent the request.
If you need to process a specific post in the AJAX request, you need to send the post ID to process as part of the AJAX request data.
|
198,114 |
<p>I'm overriding WooCommerce's default search query to include searching by SKU as well.</p>
<pre class="lang-php prettyprint-override"><code>// default search query
$query_default_search = new WP_Query(
array(
"post_type" => "product",
"s" => $search_query
)
);
// SKU query
$query_search_by_sku = new WP_Query(
array(
"post_type" => "product",
"meta_query" => array(
array(
"key" => "_sku",
"value" => $search_query,
"compare" => "LIKE"
)
)
)
);
</code></pre>
<p>If the default search query doesn't return any posts, I assume that an SKU has been entered and I run the SKU query. However, I want to merge both query arguments into one <code>WP_Query</code> call, rather than merging the results of both queries using <code>array_merge</code>.
If both queries had meta-query, I could use an OR relation, but this is different.</p>
<p>How can this be done?</p>
|
[
{
"answer_id": 198104,
"author": "Lasse M. Tvedt",
"author_id": 40819,
"author_profile": "https://wordpress.stackexchange.com/users/40819",
"pm_score": 0,
"selected": false,
"text": "<p>What about sending the post id of the single post trough ajax as well? So if you create a hidden input that contains the id, something like this: </p>\n\n<pre><code><input type=\"hidden\" id=\"post_id\" name=\"post_id\" value=\"<?php echo $post->ID; ?>\">\n</code></pre>\n\n<p>Then you can just pick the id and send it trough the ajax request, so your function will end up looking something like this: </p>\n\n<pre><code>function update_parlay_points() {\n\n //Update Parlay Points field on database with points from Post request. \n $post_id = $_POST['post_id'];\n $points = $_POST['score']; \n\n $update_points = \"UPDATE wp_posts \n SET parlay_points = '$points' \n WHERE id = $post_id\"; \n\n var_dump( $post_id );\n\n echo $update_points; \n\n global $mysqli;\n $mysqli->query( $update_points ) or die( \"Query failed\" );\n\n wp_die();\n} \n</code></pre>\n\n<p>I would also check out the <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow\">$wpdb Object</a>, insted of using $mysqli to handle the DB quieres.</p>\n"
},
{
"answer_id": 198106,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>As you can see, I tried declaring the $post variable as global to account for failures due to being outside of the Loop. </p>\n</blockquote>\n\n<p>The problem is <strong>not</strong> that the post is <em>\"outside of the loop\"</em>, problem is that AJAX request is a completely separate HTTP request.</p>\n\n<p>When you do an AJAX request, is just like you are opening a new window on browser and open the url in this separate window. It means that the script that handles the AJAX request knows <strong>nothing</strong> about the page that sent the request.</p>\n\n<p>If you need to process a specific post in the AJAX request, you need to send the post ID to process as part of the AJAX request data.</p>\n"
},
{
"answer_id": 198177,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 1,
"selected": false,
"text": "<p>My suggesion is to use <code>wp_localize_script()</code> to pass the post id to your AJAX calls.<br>\nSomething like this..</p>\n\n<pre><code>function my_script_enqueue() {\n global $post;\n\n $translations = array(\n 'postID' => $post->ID\n );\n\n wp_enqueue_script( 'myscript', '/url/to/your/script.js', array('jquery') );\n wp_localize_script( 'myscript', 'MyAJAX', $translations );\n}\nadd_action('wp_enqueue_scripts', 'my_script_enqueue')\n</code></pre>\n"
}
] |
2015/08/09
|
[
"https://wordpress.stackexchange.com/questions/198114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77533/"
] |
I'm overriding WooCommerce's default search query to include searching by SKU as well.
```php
// default search query
$query_default_search = new WP_Query(
array(
"post_type" => "product",
"s" => $search_query
)
);
// SKU query
$query_search_by_sku = new WP_Query(
array(
"post_type" => "product",
"meta_query" => array(
array(
"key" => "_sku",
"value" => $search_query,
"compare" => "LIKE"
)
)
)
);
```
If the default search query doesn't return any posts, I assume that an SKU has been entered and I run the SKU query. However, I want to merge both query arguments into one `WP_Query` call, rather than merging the results of both queries using `array_merge`.
If both queries had meta-query, I could use an OR relation, but this is different.
How can this be done?
|
>
> As you can see, I tried declaring the $post variable as global to account for failures due to being outside of the Loop.
>
>
>
The problem is **not** that the post is *"outside of the loop"*, problem is that AJAX request is a completely separate HTTP request.
When you do an AJAX request, is just like you are opening a new window on browser and open the url in this separate window. It means that the script that handles the AJAX request knows **nothing** about the page that sent the request.
If you need to process a specific post in the AJAX request, you need to send the post ID to process as part of the AJAX request data.
|
198,135 |
<p>I have been working with a front end upload and post creation script. For some reason calling the media_handle_upload function from my project-save.php file is returning as an undefined function. Is there something I a missing? Permissions, additional files, coffee?</p>
<p>Here is my function in functions.php</p>
<pre><code>function process_attachments() {
//Process Uploads
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES) {
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload( $file, $post_id );
}
}
//Attachment ID if set
if ($attach_id > 0){
//and if you want to set that image as Post then use:
return $attach_id;
}
}
</code></pre>
<p>And I call this from my project-save.php file like so (this is slimmed down, I didnt feel the need to show the post creation form data)</p>
<pre><code>$attach_id = process_attachments();
if($attach_id > 0) {
//and if you want to set that image as Post then use:
$whimkey->attach_id = $attach_id;
}
</code></pre>
<p>Since <code>media_handle_upload</code> is a <a href="https://codex.wordpress.org/Function_Reference/media_handle_upload" rel="nofollow">Wordpress function</a> how could it be undefined?</p>
|
[
{
"answer_id": 198136,
"author": "Derek",
"author_id": 20663,
"author_profile": "https://wordpress.stackexchange.com/users/20663",
"pm_score": 2,
"selected": false,
"text": "<p>So I dont know if its the best way but my problem was the if statement surrounding the require_once on the necessary files that contain the function. Commented out the IF statement and it did the trick. I'll go have that coffee now ;)</p>\n\n<pre><code>//if (!function_exists('wp_generate_attachment_metadata')){\n require_once(ABSPATH . 'wp-admin/includes/image.php');\n require_once(ABSPATH . 'wp-admin/includes/file.php');\n require_once(ABSPATH . 'wp-admin/includes/media.php');\n //}\n</code></pre>\n"
},
{
"answer_id": 198139,
"author": "Rituparna sonowal",
"author_id": 71232,
"author_profile": "https://wordpress.stackexchange.com/users/71232",
"pm_score": 1,
"selected": false,
"text": "<p>Based on your code, you have put the wrong condition within if statement. You can check the first example here:\n<a href=\"https://codex.wordpress.org/Function_Reference/media_handle_upload\" rel=\"nofollow\">Media handle upload</a></p>\n"
}
] |
2015/08/09
|
[
"https://wordpress.stackexchange.com/questions/198135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20663/"
] |
I have been working with a front end upload and post creation script. For some reason calling the media\_handle\_upload function from my project-save.php file is returning as an undefined function. Is there something I a missing? Permissions, additional files, coffee?
Here is my function in functions.php
```
function process_attachments() {
//Process Uploads
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES) {
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload( $file, $post_id );
}
}
//Attachment ID if set
if ($attach_id > 0){
//and if you want to set that image as Post then use:
return $attach_id;
}
}
```
And I call this from my project-save.php file like so (this is slimmed down, I didnt feel the need to show the post creation form data)
```
$attach_id = process_attachments();
if($attach_id > 0) {
//and if you want to set that image as Post then use:
$whimkey->attach_id = $attach_id;
}
```
Since `media_handle_upload` is a [Wordpress function](https://codex.wordpress.org/Function_Reference/media_handle_upload) how could it be undefined?
|
So I dont know if its the best way but my problem was the if statement surrounding the require\_once on the necessary files that contain the function. Commented out the IF statement and it did the trick. I'll go have that coffee now ;)
```
//if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
//}
```
|
198,143 |
<p>I'm looking for a way to get the list of all plugins listed in the <a href="https://wordpress.org/plugins/" rel="noreferrer">WordPress.org Plugin Directory</a>.</p>
<p>There is one other post I've <a href="https://wordpress.stackexchange.com/questions/95836/list-of-all-existing-wordpress-plugins">found on StackOverflow</a> regarding this which recommends <a href="http://plugins.svn.wordpress.org/" rel="noreferrer">using the subversion repository.</a></p>
<p>I'd like to do something that organizes them by number of downloads.</p>
<p>I think this is probably possible using the WordPress.org API, but I'm not positive. My attempts thus far have failed. Any ideas?</p>
|
[
{
"answer_id": 204266,
"author": "Burgi",
"author_id": 62753,
"author_profile": "https://wordpress.stackexchange.com/users/62753",
"pm_score": 2,
"selected": false,
"text": "<p>Without seeing some code or results it is difficult to advise beyond linking you to other tutorials on the web. A quick Google revealed these:</p>\n\n<ul>\n<li><a href=\"https://dd32.id.au/projects/wordpressorg-plugin-information-api-docs/\" rel=\"nofollow\">https://dd32.id.au/projects/wordpressorg-plugin-information-api-docs/</a></li>\n<li><a href=\"http://code.tutsplus.com/tutorials/communicating-with-the-wordpressorg-plugin-api--wp-33069\" rel=\"nofollow\">http://code.tutsplus.com/tutorials/communicating-with-the-wordpressorg-plugin-api--wp-33069</a></li>\n</ul>\n\n<p>As with a lot of the WP codex the official documentation is a little lacking.</p>\n"
},
{
"answer_id": 367621,
"author": "Michael Field",
"author_id": 188889,
"author_profile": "https://wordpress.stackexchange.com/users/188889",
"pm_score": 3,
"selected": false,
"text": "<p>You can start with something like this:</p>\n\n<pre><code>https://api.wordpress.org/plugins/info/1.2/?action=query_plugins&request[page]=1&request[per_page]=400\n</code></pre>\n\n<p>I think it's self-explanatory.</p>\n"
},
{
"answer_id": 369883,
"author": "zero",
"author_id": 49909,
"author_profile": "https://wordpress.stackexchange.com/users/49909",
"pm_score": 0,
"selected": false,
"text": "<p>good day dear Davemackey - hello Michael Field\nits been a long time that this has been asked - but anyway.. here my little idea that i can come up with..</p>\n<p>Not the best answer but I tried to solve my own problem the best way I could.</p>\n<h1>Getting a list of plugins</h1>\n<p>This will <strong>not</strong> return ALL plugins but it will return the <strong>top rated</strong> ones:</p>\n<pre><code>$plugins = plugins_api('query_plugins', array(\n 'per_page' => 100,\n 'browse' => 'top-rated',\n 'fields' =>\n array(\n 'short_description' => false,\n 'description' => false,\n 'sections' => false,\n 'tested' => false,\n 'requires' => false,\n 'rating' => false,\n 'ratings' => false,\n 'downloaded' => false,\n 'downloadlink' => false,\n 'last_updated' => false,\n 'added' => false,\n 'tags' => false,\n 'compatibility' => false,\n 'homepage' => false,\n 'versions' => false,\n 'donate_link' => false,\n 'reviews' => false,\n 'banners' => false,\n 'icons' => false,\n 'active_installs' => false,\n 'group' => false,\n 'contributors' => false\n )));\n</code></pre>\n<h1>Save the data as JSON</h1>\n<p>Since the data that we get is huge and it will be bad for performance, we try to get the <code>name</code> and the <code>slug</code> out of the array and then we write it in a JSON file:</p>\n<pre><code>$plugins_json = '{' . PHP_EOL;\n// Get only the name and the slug\nforeach ($plugins as $plugin) {\n foreach ($plugin as $key => $p) {\n if ($p->name != null) {\n // Let's beautify the JSON\n $plugins_json .= ' "'. $p->name . '": {' . PHP_EOL;\n $plugins_json .= ' "slug": "' . $p->slug . '"' . PHP_EOL;\n end($plugin);\n $plugins_json .= ($key !== key($plugin)) ? ' },' . PHP_EOL : ' }' . PHP_EOL;\n }\n }\n}\n$plugins_json .= '}';\nfile_put_contents('plugins.json', $plugins_json);\n</code></pre>\n<p>Now we have a slim JSON file with only the data that we need.</p>\n<p>To keep updating the JSON file, we run that script to create a JSON file every 24 hours by setting up a Cron Job.</p>\n"
}
] |
2015/08/10
|
[
"https://wordpress.stackexchange.com/questions/198143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43881/"
] |
I'm looking for a way to get the list of all plugins listed in the [WordPress.org Plugin Directory](https://wordpress.org/plugins/).
There is one other post I've [found on StackOverflow](https://wordpress.stackexchange.com/questions/95836/list-of-all-existing-wordpress-plugins) regarding this which recommends [using the subversion repository.](http://plugins.svn.wordpress.org/)
I'd like to do something that organizes them by number of downloads.
I think this is probably possible using the WordPress.org API, but I'm not positive. My attempts thus far have failed. Any ideas?
|
You can start with something like this:
```
https://api.wordpress.org/plugins/info/1.2/?action=query_plugins&request[page]=1&request[per_page]=400
```
I think it's self-explanatory.
|
198,171 |
<p>My application has >10 <code>user_roles</code>, each able to perform completely different tasks, provided with an custom backend and no access to <code>wp-admin</code>. </p>
<p>The extra functionality each <code>user_role</code> gets to use is handled via multiple plugins. Each <code>user_role</code> interacts on the same data (posts, taxonomies etc.)</p>
<p>The idea I had is to use a single installation per one or more <code>user_roles</code> connected to a single database to share users, posts etc but with different plugins loaded, so simply a separate <code>wp_options</code> table. </p>
<p>The goal is to provide independent login areas(e.g subdomains, I don't want partners to use the same login as customers), easier routing (different permalinks and rewrites for each role) and less time checking for permissions of logged in users on protected sections of the site. Also I could disable themes for the 'backend-only' roles and only load the plugins each role needs to perform their actions.</p>
<p>My guess is, that a nice side effect would be a significant speed boost since the main site for customers is powered by <code>woocommerce</code> and I wouldn't need to activate <code>woocommerce</code> on other instances or vice versa... custom plugins would not be loaded in the installation powering the user/customer frontend.</p>
<p>I considered the multisite functionality but this wouldn't be the right path, since each blog has it's own posts table, which is not practical since I need to have all users use the same data.</p>
<p>Wordpress provides these constants to set up a custom users table, to share users among multiple installs:</p>
<pre><code>define( 'CUSTOM_USER_TABLE', $table_prefix.'my_users' );
define( 'CUSTOM_USER_META_TABLE', $table_prefix.'my_usermeta' );
</code></pre>
<p>But it does not provide a method to define a custom options table, see this ticket <a href="https://core.trac.wordpress.org/ticket/7008" rel="nofollow noreferrer">https://core.trac.wordpress.org/ticket/7008</a></p>
<p>This thread provides a solution which is a bit of hacky but works fine in my initial test:
<a href="https://wordpress.stackexchange.com/a/175494/68858">https://wordpress.stackexchange.com/a/175494/68858</a> </p>
<p>TL;DR: Modify wpdb-class by copying the functionality of <code>CUSTOM_USER_TABLE</code> to use <code>CUSTOM_OPTION_TABLE</code> in <code>wp-config.php</code>.</p>
<p>Btw. he states, content of the second site would link to the first, which is just an estimate I guess... so no, it does not, it works completely fine.</p>
<p>My question now is, do you see any kind of problems I may face with this approach in general? (many installations, one database, same database tables and an individual options table or each install)</p>
<p>Would you suggest a different approach or would you stay with the default wordpress-way of doing things?</p>
<p>What would be a solution to keep the 'hack' of modifying wpdb.php persistent in case of core updates?</p>
<p>Any other drawbacks besides maintainability? (which I think I gain a lot of by doing this)</p>
<p>When this project was stared almost half of the requirements didn't exist and wordpress+woocommerce was chosen due to simplicity. Using wordpress as a application framework is far more difficult and limiting, than I thought.</p>
<p>Thanks in advance for your help!</p>
<p><strong>Update:</strong></p>
<p>The question how to keep the modified version of wpdb in case of updates, or how to use custom table names besides CUSTOM_USER_TABLE was answered in a wordpress support ticket.
The solution is to extend the wpdb-class, alter the table names in the <code>tables</code> function, save it as db.php to wp-content and use it as a drop-in. This way you can define custom names for all tables and avoid problems on updating core. (See: <a href="https://core.trac.wordpress.org/ticket/33320" rel="nofollow noreferrer">#33320</a>) </p>
|
[
{
"answer_id": 198175,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like you are trying hard to shot yourself and you will likely succeed. Every framework has its own assumptions and limitation so if the assumptions of wordpress do not fit your needs then just don't use wordpress for the project. </p>\n\n<p>If you (ok, probably the client) have decided that for reasons of cost, delivery time and maintainability wordpress should be used then you should strive to use the built-in wordpress tools instead of trying to go around them and re-inventing things just because if you were using framework X you would have done it that way. the more aligned you are with the wordpress core development practices the happier you will be (unless you are trying to ensure job security ;).</p>\n\n<p>Sorry for the very meta answer but from your description it sounds like you don't want to do this project in wordpress although I didn't read here anything which might be problematic in wordpress and there is no need doing all the hacks that you think you should do.</p>\n"
},
{
"answer_id": 373446,
"author": "RafaSashi",
"author_id": 37412,
"author_profile": "https://wordpress.stackexchange.com/users/37412",
"pm_score": 0,
"selected": false,
"text": "<p>This is a suggestion assuming the 3 following things:</p>\n<ul>\n<li><p>all sites are on the same database</p>\n</li>\n<li><p>each sites is previously installed with its own <strong>base_prefix</strong></p>\n</li>\n<li><p>the following filter must be called as soon as possible, in our case using <a href=\"https://wordpress.org/plugins/hyperdb/\" rel=\"nofollow noreferrer\">HyperDB</a> and dropping the filter in <strong>db-config.php</strong></p>\n<pre><code> add_filter('query', function ($query){\n\n global $wpdb;\n\n $content_prefix = 'main_'; //prefic of the main installation where all posts and terms are located\n\n $query = preg_replace('/' . $wpdb->base_prefix . '(?!options|users|usermeta)/i', $content_prefix, $query);\n\n return $query;\n });\n</code></pre>\n</li>\n</ul>\n<p>It is also recommended to share the same UPLOADS path together with an offloading plugin for the media and <a href=\"https://wordpress.org/support/topic/sync-user-table-across-multiple-sites/\" rel=\"nofollow noreferrer\">synch the user table</a> since the author info will need to be pulled on both sides.</p>\n<p>If the data is located in different dabases/servers, you can keep the same filter and <a href=\"https://uysalmustafa.com/2019/02/24/advanced-database-interactions-with-hyperdb/\" rel=\"nofollow noreferrer\">implement the HyperDB dataset methods</a>.</p>\n<p><strong>Alternatively</strong></p>\n<p>It is also possible to use the dataset without filtering the query but you will need to use the same prefix in different databases.</p>\n"
}
] |
2015/08/10
|
[
"https://wordpress.stackexchange.com/questions/198171",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68858/"
] |
My application has >10 `user_roles`, each able to perform completely different tasks, provided with an custom backend and no access to `wp-admin`.
The extra functionality each `user_role` gets to use is handled via multiple plugins. Each `user_role` interacts on the same data (posts, taxonomies etc.)
The idea I had is to use a single installation per one or more `user_roles` connected to a single database to share users, posts etc but with different plugins loaded, so simply a separate `wp_options` table.
The goal is to provide independent login areas(e.g subdomains, I don't want partners to use the same login as customers), easier routing (different permalinks and rewrites for each role) and less time checking for permissions of logged in users on protected sections of the site. Also I could disable themes for the 'backend-only' roles and only load the plugins each role needs to perform their actions.
My guess is, that a nice side effect would be a significant speed boost since the main site for customers is powered by `woocommerce` and I wouldn't need to activate `woocommerce` on other instances or vice versa... custom plugins would not be loaded in the installation powering the user/customer frontend.
I considered the multisite functionality but this wouldn't be the right path, since each blog has it's own posts table, which is not practical since I need to have all users use the same data.
Wordpress provides these constants to set up a custom users table, to share users among multiple installs:
```
define( 'CUSTOM_USER_TABLE', $table_prefix.'my_users' );
define( 'CUSTOM_USER_META_TABLE', $table_prefix.'my_usermeta' );
```
But it does not provide a method to define a custom options table, see this ticket <https://core.trac.wordpress.org/ticket/7008>
This thread provides a solution which is a bit of hacky but works fine in my initial test:
<https://wordpress.stackexchange.com/a/175494/68858>
TL;DR: Modify wpdb-class by copying the functionality of `CUSTOM_USER_TABLE` to use `CUSTOM_OPTION_TABLE` in `wp-config.php`.
Btw. he states, content of the second site would link to the first, which is just an estimate I guess... so no, it does not, it works completely fine.
My question now is, do you see any kind of problems I may face with this approach in general? (many installations, one database, same database tables and an individual options table or each install)
Would you suggest a different approach or would you stay with the default wordpress-way of doing things?
What would be a solution to keep the 'hack' of modifying wpdb.php persistent in case of core updates?
Any other drawbacks besides maintainability? (which I think I gain a lot of by doing this)
When this project was stared almost half of the requirements didn't exist and wordpress+woocommerce was chosen due to simplicity. Using wordpress as a application framework is far more difficult and limiting, than I thought.
Thanks in advance for your help!
**Update:**
The question how to keep the modified version of wpdb in case of updates, or how to use custom table names besides CUSTOM\_USER\_TABLE was answered in a wordpress support ticket.
The solution is to extend the wpdb-class, alter the table names in the `tables` function, save it as db.php to wp-content and use it as a drop-in. This way you can define custom names for all tables and avoid problems on updating core. (See: [#33320](https://core.trac.wordpress.org/ticket/33320))
|
Sounds like you are trying hard to shot yourself and you will likely succeed. Every framework has its own assumptions and limitation so if the assumptions of wordpress do not fit your needs then just don't use wordpress for the project.
If you (ok, probably the client) have decided that for reasons of cost, delivery time and maintainability wordpress should be used then you should strive to use the built-in wordpress tools instead of trying to go around them and re-inventing things just because if you were using framework X you would have done it that way. the more aligned you are with the wordpress core development practices the happier you will be (unless you are trying to ensure job security ;).
Sorry for the very meta answer but from your description it sounds like you don't want to do this project in wordpress although I didn't read here anything which might be problematic in wordpress and there is no need doing all the hacks that you think you should do.
|
198,185 |
<p>During the vanilla WP core load the current user is being set up in <code>$wp-init()</code> which is after theme load and before <code>init</code> hook. This is in line with good practice of functionality getting hooked to <code>init</code> or later.</p>
<p>However it is also common practice to call related functions, such as <code>current_user_can()</code> <em>earlier</em> than that. It is by definition required for plugins that work with earlier stages of load process (my Toolbar Theme Switcher plugin would be an example).</p>
<p>Documentation makes no claims for or against this practice (that I could find).</p>
<p>However some plugins seem to hook into user–related functionality and expect the post–<code>init</code> state at all times.</p>
<p>For example bbPress throws following notice:</p>
<pre><code>// If the current user is being setup before the "init" action has fired,
// strange (and difficult to debug) role/capability issues will occur.
if ( ! did_action( 'after_setup_theme' ) ) {
_doing_it_wrong( __FUNCTION__, __( 'The current user is being initialized without using $wp->init().', 'bbpress' ), '2.3' );
}
</code></pre>
<p>For quick demonstration throw this into core's definition of <code>current_user_can()</code>:</p>
<pre><code>function current_user_can( $capability ) {
if ( ! did_action('after_setup_theme') ) {
echo wp_debug_backtrace_summary();
}
</code></pre>
<p>Who is “right” in this situation? Is there a canonical determination about allowed / forbidden usage of user–related functions before <code>init</code> ?</p>
|
[
{
"answer_id": 198190,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": false,
"text": "<p>The only prerequisite for <code>current_user_can()</code> is an existing <code>wp_get_current_user()</code>. The latter is defined in <code>pluggable.php</code>, so you can use it after <code>plugins_loaded</code>.</p>\n\n<p>The <code>_doing_it_wrong()</code> call you are citing in your question is wrong for itself. My guess is that you took that from BuddyPress or bbPress. Both are running into a recursion if they don't wait that long. There are other, better ways to prevent the recursion.</p>\n\n<p>In some cases, like <a href=\"https://github.com/inpsyde/multilingual-press/issues/88\">changing the locale</a>, you <em>have</em> to access the current user object earlier, so waiting for <code>after_setup_theme</code> isn't even an option.</p>\n"
},
{
"answer_id": 198196,
"author": "bobbingwide",
"author_id": 77573,
"author_profile": "https://wordpress.stackexchange.com/users/77573",
"pm_score": 1,
"selected": false,
"text": "<p>I'm inclined to think that BuddyPress and bbPress should be checking something else before issuing the <code>_doing_it_wrong</code> message</p>\n\n<p>I changed both routines to also check the actual setting of $current_user.</p>\n\n<pre><code>global $current_user; \nif ( is_null( $current_user ) ) {\n _doing_it_wrong( ... );\n}\n</code></pre>\n\n<p>The Notices were no longer displayed. </p>\n\n<p>The testing for <code>did_action( \"after_setup_theme\" )</code> becomes the braces to go with the belt.</p>\n"
},
{
"answer_id": 198222,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 2,
"selected": false,
"text": "<p>If you check user capability before <code>init</code> means there're chances <em>you</em> are the responsible for the setting of the current user object.</p>\n\n<p>If you access user <em>after</em> <code>init</code>, then you are sure that <em>something else</em> already setup the user, most the times core itself.</p>\n\n<p>This is why accessing user after <code>init</code> is considered <em>safe</em>.</p>\n\n<p>In fact, early access may possibly break some filter running on <code>determine_current_user</code>.</p>\n\n<p>It worth saying that one is a \"fragile\" hook, because there're chances it never runs, being fired only in pluggable functions. </p>\n\n<p>However, there are cases (like <strong>@toscho</strong> said) where you <em>can't</em> wait until init, in those cases you have no choice.</p>\n\n<p>Only way to solve any incompatibility is case by case, if you have will.</p>\n\n<p>A solution that <em>may</em> work in most cases (including bbPress / BuddyPress) is to use following function instead of <code>current_user_can</code>:</p>\n\n<pre><code>function compat_current_user_can( $capability )\n{\n if ( did_action( 'init' ) ) {\n return current_user_can( $capability );\n }\n\n $user_id = apply_filters( 'determine_current_user', false );\n\n return user_can( $user_id, $capability );\n}\n</code></pre>\n\n<p>This allows to check current user capability early without setting global user, so <em>in theory</em> safe to be run before <code>init</code>.</p>\n\n<p>Problem is that, as said above, any code that overrides pluggable functions and not fires <code>determine_current_user</code> breaks it.</p>\n"
}
] |
2015/08/10
|
[
"https://wordpress.stackexchange.com/questions/198185",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/847/"
] |
During the vanilla WP core load the current user is being set up in `$wp-init()` which is after theme load and before `init` hook. This is in line with good practice of functionality getting hooked to `init` or later.
However it is also common practice to call related functions, such as `current_user_can()` *earlier* than that. It is by definition required for plugins that work with earlier stages of load process (my Toolbar Theme Switcher plugin would be an example).
Documentation makes no claims for or against this practice (that I could find).
However some plugins seem to hook into user–related functionality and expect the post–`init` state at all times.
For example bbPress throws following notice:
```
// If the current user is being setup before the "init" action has fired,
// strange (and difficult to debug) role/capability issues will occur.
if ( ! did_action( 'after_setup_theme' ) ) {
_doing_it_wrong( __FUNCTION__, __( 'The current user is being initialized without using $wp->init().', 'bbpress' ), '2.3' );
}
```
For quick demonstration throw this into core's definition of `current_user_can()`:
```
function current_user_can( $capability ) {
if ( ! did_action('after_setup_theme') ) {
echo wp_debug_backtrace_summary();
}
```
Who is “right” in this situation? Is there a canonical determination about allowed / forbidden usage of user–related functions before `init` ?
|
The only prerequisite for `current_user_can()` is an existing `wp_get_current_user()`. The latter is defined in `pluggable.php`, so you can use it after `plugins_loaded`.
The `_doing_it_wrong()` call you are citing in your question is wrong for itself. My guess is that you took that from BuddyPress or bbPress. Both are running into a recursion if they don't wait that long. There are other, better ways to prevent the recursion.
In some cases, like [changing the locale](https://github.com/inpsyde/multilingual-press/issues/88), you *have* to access the current user object earlier, so waiting for `after_setup_theme` isn't even an option.
|
198,217 |
<p>I need to display the total number of votes that have been made for a specific custom post type. Here's an example of how the <code>wp_postmeta</code> table looks for these keys/values:</p>
<pre><code>meta_id post_id meta_key meta_value
22 4 vote 4
26 6 vote 0
27 7 vote 1
32 10 vote 10
</code></pre>
<p>Suppose the first and last rows are <code>wp_postmeta</code> rows for the custom post type <code>movies</code>. How can I get the total of 14?</p>
<p>Here's the code I've tried, but it's not working. It seems to be adding up the values of all post types and not just for the specified custom post type.</p>
<pre><code>function meta_val( $key = '', $type = 'post', $status = 'publish' ) {
global $wpdb;
$r = $wpdb->get_col( $wpdb->prepare( "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status, $type ) );
return $r;
}
function total_votes( $post_type ) {
$votes = meta_val( 'vote', 'movies' );
$sum = array_sum( $votes );
return $sum;
}
</code></pre>
|
[
{
"answer_id": 198221,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 2,
"selected": false,
"text": "<p>Try this, should get you started.. (not tested though) </p>\n\n<pre><code>function count_total_vote() {\n $args = array(\n 'post_type' => 'post', // Your post type\n 'status' => 'publish',\n 'meta_key' => 'vote', // Meta Key\n );\n\n $total = 0;\n $votes = new WP_Query( $args );\n if ( $votes->have_posts() ) {\n while ( $votes->have_posts() ) {\n $votes->the_post();\n $total += get_post_meta( get_the_ID(), 'vote', true );\n }\n }\n\n echo $total;\n\n} \n</code></pre>\n\n<p>No need for a custom query to database.</p>\n"
},
{
"answer_id": 198226,
"author": "Eric Holmes",
"author_id": 23454,
"author_profile": "https://wordpress.stackexchange.com/users/23454",
"pm_score": 2,
"selected": true,
"text": "<p>There may not be a need for a custom query, but I'd recommend it rather than hitting the database:\n - once for the WP_Query\n - once more for each post entry</p>\n\n<p>And then manually working out the math in PHP. Do it all at once with one MySQL statement.</p>\n\n<pre><code>select sum(PM.meta_value) from wp_postmeta PM\njoin wp_posts P on P.ID = PM.post_id\nwhere P.post_type='page'\n and PM.meta_key='test'\n</code></pre>\n\n<p>With your code above, replace the <code>$r=...</code> line with this:</p>\n\n<pre><code>$r = $wpdb->get_results( $wpdb->prepare( \"\n SELECT SUM(pm.meta_value) FROM {$wpdb->postmeta} pm\n LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id\n WHERE pm.meta_key = '%s' \n AND p.post_status = '%s' \n AND p.post_type = '%s'\n \", $key, $status, $type ) );\n</code></pre>\n\n<p><code>$r[0]</code> should be your total. :)</p>\n"
}
] |
2015/08/10
|
[
"https://wordpress.stackexchange.com/questions/198217",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1462/"
] |
I need to display the total number of votes that have been made for a specific custom post type. Here's an example of how the `wp_postmeta` table looks for these keys/values:
```
meta_id post_id meta_key meta_value
22 4 vote 4
26 6 vote 0
27 7 vote 1
32 10 vote 10
```
Suppose the first and last rows are `wp_postmeta` rows for the custom post type `movies`. How can I get the total of 14?
Here's the code I've tried, but it's not working. It seems to be adding up the values of all post types and not just for the specified custom post type.
```
function meta_val( $key = '', $type = 'post', $status = 'publish' ) {
global $wpdb;
$r = $wpdb->get_col( $wpdb->prepare( "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status, $type ) );
return $r;
}
function total_votes( $post_type ) {
$votes = meta_val( 'vote', 'movies' );
$sum = array_sum( $votes );
return $sum;
}
```
|
There may not be a need for a custom query, but I'd recommend it rather than hitting the database:
- once for the WP\_Query
- once more for each post entry
And then manually working out the math in PHP. Do it all at once with one MySQL statement.
```
select sum(PM.meta_value) from wp_postmeta PM
join wp_posts P on P.ID = PM.post_id
where P.post_type='page'
and PM.meta_key='test'
```
With your code above, replace the `$r=...` line with this:
```
$r = $wpdb->get_results( $wpdb->prepare( "
SELECT SUM(pm.meta_value) FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status, $type ) );
```
`$r[0]` should be your total. :)
|
198,233 |
<p>firstly i know i have to add some code explaining what i have done before.</p>
<p>But honestly i had tried more than ten tutorial concerning wordpress post slider based on flexslider or bxslider or other trics with jquery but seriously guys I don't where is the problem, i can't show slider the best thingi show is a list of post image and content vertically.</p>
<p>So my question is how to create a wordpress post slider?</p>
<p>PS. i had some linked jquery , those files could interrupt the slider. post</p>
|
[
{
"answer_id": 198221,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 2,
"selected": false,
"text": "<p>Try this, should get you started.. (not tested though) </p>\n\n<pre><code>function count_total_vote() {\n $args = array(\n 'post_type' => 'post', // Your post type\n 'status' => 'publish',\n 'meta_key' => 'vote', // Meta Key\n );\n\n $total = 0;\n $votes = new WP_Query( $args );\n if ( $votes->have_posts() ) {\n while ( $votes->have_posts() ) {\n $votes->the_post();\n $total += get_post_meta( get_the_ID(), 'vote', true );\n }\n }\n\n echo $total;\n\n} \n</code></pre>\n\n<p>No need for a custom query to database.</p>\n"
},
{
"answer_id": 198226,
"author": "Eric Holmes",
"author_id": 23454,
"author_profile": "https://wordpress.stackexchange.com/users/23454",
"pm_score": 2,
"selected": true,
"text": "<p>There may not be a need for a custom query, but I'd recommend it rather than hitting the database:\n - once for the WP_Query\n - once more for each post entry</p>\n\n<p>And then manually working out the math in PHP. Do it all at once with one MySQL statement.</p>\n\n<pre><code>select sum(PM.meta_value) from wp_postmeta PM\njoin wp_posts P on P.ID = PM.post_id\nwhere P.post_type='page'\n and PM.meta_key='test'\n</code></pre>\n\n<p>With your code above, replace the <code>$r=...</code> line with this:</p>\n\n<pre><code>$r = $wpdb->get_results( $wpdb->prepare( \"\n SELECT SUM(pm.meta_value) FROM {$wpdb->postmeta} pm\n LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id\n WHERE pm.meta_key = '%s' \n AND p.post_status = '%s' \n AND p.post_type = '%s'\n \", $key, $status, $type ) );\n</code></pre>\n\n<p><code>$r[0]</code> should be your total. :)</p>\n"
}
] |
2015/08/10
|
[
"https://wordpress.stackexchange.com/questions/198233",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69413/"
] |
firstly i know i have to add some code explaining what i have done before.
But honestly i had tried more than ten tutorial concerning wordpress post slider based on flexslider or bxslider or other trics with jquery but seriously guys I don't where is the problem, i can't show slider the best thingi show is a list of post image and content vertically.
So my question is how to create a wordpress post slider?
PS. i had some linked jquery , those files could interrupt the slider. post
|
There may not be a need for a custom query, but I'd recommend it rather than hitting the database:
- once for the WP\_Query
- once more for each post entry
And then manually working out the math in PHP. Do it all at once with one MySQL statement.
```
select sum(PM.meta_value) from wp_postmeta PM
join wp_posts P on P.ID = PM.post_id
where P.post_type='page'
and PM.meta_key='test'
```
With your code above, replace the `$r=...` line with this:
```
$r = $wpdb->get_results( $wpdb->prepare( "
SELECT SUM(pm.meta_value) FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status, $type ) );
```
`$r[0]` should be your total. :)
|
198,256 |
<p>I have done this so many times but facing problems with meta boxes and wp_editor these days, lot of notices, errors and strange behaviour.</p>
<p>I have been able to solve problem with meta boxes notices and save . The main problem was nonce. The nonce i was using was for plugin usage. But my code is inside the theme so now i am unable to save the value in metabox and no more notices for metaboxes.</p>
<p>But now i get notice <code>Notice: Undefined variable: main_detail</code> in for wp_editor.
And it doesn't save the value after i hit publish/update</p>
<pre><code> <?php
function wpt_performer_posttype() {
register_post_type( 'performer',
array(
'labels' => array(
'name' => __( 'Performer' ),
'singular_name' => __( 'performer' ),
'add_new' => __( 'Add New performer' ),
'add_new_item' => __( 'Add New performer' ),
'edit_item' => __( 'Edit performer' ),
'new_item' => __( 'Add New performer' ),
'view_item' => __( 'View performer' ),
'search_items' => __( 'Search performer' ),
'not_found' => __( 'No performer found' ),
'not_found_in_trash' => __( 'No performer found in trash' )
),
'public' => true,
'supports' => array( 'title','thumbnail','page-attributes' ),
'capability_type' => 'post',
'rewrite' => array("slug" => "performer"), // Permalinks format
'menu_position' => 6,
'show_ui'=>true,
'query_var'=>true,
'register_meta_box_cb' => 'add_performer_metaboxes'
)
);
}
add_action( 'init', 'wpt_performer_posttype' );
/*Add featured thumbnails to the custom post type*/
add_theme_support( 'post-thumbnails' );
/*Now we add the meta boxes to the performer*/
// add_action('add_meta_boxes', 'add_performer_metaboxes');
function add_performer_metaboxes() {
add_meta_box('wpt_performer_lines', __('Extra fields'), 'wpt_performer_lines', 'performer', 'normal', 'high');
}
function wpt_performer_lines(){
global $post;
wp_nonce_field( 'my_meta_box', 'performermeta_noncename' );
$short_description = get_post_meta($post->ID, '_short_description', true);
echo '<label >';?><?php _e( 'short description:' );?></label>
<?php echo '<br><textarea name="_short_description" rows="1" cols="90">'.$short_description.'</textarea>';?>
<?php wp_editor( $main_detail, 'main_detail', array( 'textarea_name' => '_main_detail', 'textarea_rows' =>5, 'media_buttons' => false ) );
}
function wpt_save_performer_meta($post_id, $post) {
if ( ! isset( $_POST['performermeta_noncename'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['performermeta_noncename'], 'my_meta_box' ) ) {
return;
}
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
$performer_meta['_short_description'] = trim($_POST['_short_description']);
foreach ($performer_meta as $key => $value) { // Cycle through the $performer_meta array!
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}
}
add_action('save_post', 'wpt_save_performer_meta', 1, 2); // save the custom fields
?>
</code></pre>
|
[
{
"answer_id": 198258,
"author": "Marek",
"author_id": 54031,
"author_profile": "https://wordpress.stackexchange.com/users/54031",
"pm_score": 1,
"selected": false,
"text": "<p>In your <code>wpt_save_performer_meta()</code> function you are iterating through <code>$performer_meta</code> array and saving its values. But it has only one manually set key (<code>_short_description</code>) ... and its value is result of <code>isset($_POST['_short_description'])</code>, which is probablay always <code>true</code>, and saved (or displayed) as <code>1</code>.</p>\n\n<p>So it should be like this:</p>\n\n<pre><code>$performer_meta['_short_description'] = trim($_POST['_short_description']);\n</code></pre>\n\n<p>But your code will not save <code>_main_detail</code> editor field, because its key does not exist in <code>$performer_meta</code> array.</p>\n\n<p><strong>Edit:</strong> <code>Notice: Undefined variable: main_detail</code> ... is there because the variable <code>$main_detail</code> is missing, but you are using it in <code>wp_editor()</code>.</p>\n"
},
{
"answer_id": 198267,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 1,
"selected": true,
"text": "<p>You forgot to declare the variable <code>$main_detail</code>. Since it's a meta field you need to retrieve it first before you add it.</p>\n\n<pre><code>$main_detail = get_post_meta($post->ID, '_main_detail', true); \n</code></pre>\n\n<p>Also, I can see that some errors in your code. </p>\n\n<pre><code>echo '<label >';?><?php _e( 'short description:' );?></label>\n</code></pre>\n\n<p>Should be.. </p>\n\n<pre><code>echo '<label >' . _e( \"short description:\" ) . '</label>';\n</code></pre>\n\n<p>And, you also need to add the key <code>_main_detail</code> in your <code>$performer_meta</code> array in order to save it.</p>\n"
}
] |
2015/08/11
|
[
"https://wordpress.stackexchange.com/questions/198256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55034/"
] |
I have done this so many times but facing problems with meta boxes and wp\_editor these days, lot of notices, errors and strange behaviour.
I have been able to solve problem with meta boxes notices and save . The main problem was nonce. The nonce i was using was for plugin usage. But my code is inside the theme so now i am unable to save the value in metabox and no more notices for metaboxes.
But now i get notice `Notice: Undefined variable: main_detail` in for wp\_editor.
And it doesn't save the value after i hit publish/update
```
<?php
function wpt_performer_posttype() {
register_post_type( 'performer',
array(
'labels' => array(
'name' => __( 'Performer' ),
'singular_name' => __( 'performer' ),
'add_new' => __( 'Add New performer' ),
'add_new_item' => __( 'Add New performer' ),
'edit_item' => __( 'Edit performer' ),
'new_item' => __( 'Add New performer' ),
'view_item' => __( 'View performer' ),
'search_items' => __( 'Search performer' ),
'not_found' => __( 'No performer found' ),
'not_found_in_trash' => __( 'No performer found in trash' )
),
'public' => true,
'supports' => array( 'title','thumbnail','page-attributes' ),
'capability_type' => 'post',
'rewrite' => array("slug" => "performer"), // Permalinks format
'menu_position' => 6,
'show_ui'=>true,
'query_var'=>true,
'register_meta_box_cb' => 'add_performer_metaboxes'
)
);
}
add_action( 'init', 'wpt_performer_posttype' );
/*Add featured thumbnails to the custom post type*/
add_theme_support( 'post-thumbnails' );
/*Now we add the meta boxes to the performer*/
// add_action('add_meta_boxes', 'add_performer_metaboxes');
function add_performer_metaboxes() {
add_meta_box('wpt_performer_lines', __('Extra fields'), 'wpt_performer_lines', 'performer', 'normal', 'high');
}
function wpt_performer_lines(){
global $post;
wp_nonce_field( 'my_meta_box', 'performermeta_noncename' );
$short_description = get_post_meta($post->ID, '_short_description', true);
echo '<label >';?><?php _e( 'short description:' );?></label>
<?php echo '<br><textarea name="_short_description" rows="1" cols="90">'.$short_description.'</textarea>';?>
<?php wp_editor( $main_detail, 'main_detail', array( 'textarea_name' => '_main_detail', 'textarea_rows' =>5, 'media_buttons' => false ) );
}
function wpt_save_performer_meta($post_id, $post) {
if ( ! isset( $_POST['performermeta_noncename'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['performermeta_noncename'], 'my_meta_box' ) ) {
return;
}
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
$performer_meta['_short_description'] = trim($_POST['_short_description']);
foreach ($performer_meta as $key => $value) { // Cycle through the $performer_meta array!
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}
}
add_action('save_post', 'wpt_save_performer_meta', 1, 2); // save the custom fields
?>
```
|
You forgot to declare the variable `$main_detail`. Since it's a meta field you need to retrieve it first before you add it.
```
$main_detail = get_post_meta($post->ID, '_main_detail', true);
```
Also, I can see that some errors in your code.
```
echo '<label >';?><?php _e( 'short description:' );?></label>
```
Should be..
```
echo '<label >' . _e( "short description:" ) . '</label>';
```
And, you also need to add the key `_main_detail` in your `$performer_meta` array in order to save it.
|
198,266 |
<p>I have a situation where i have about 5000 imported records in a custom post type (travel) with a taxonomy category (country). Since i import from several different locations and each source seems to use a different description for some countries i want to update the term reference of that post to a uniform description.</p>
<p>So say the taxonomy 'country' has, amongst others, these values:</p>
<pre><code>
+---------+-------------+
| term_id | name |
+---------+-------------+
| 1248 | Zuid Afrika |
+---------+-------------+
| 3845 | zuid-afrika |
+---------+-------------+
</code></pre>
<p>I want to update the term reference to 'country' that has a duplicate in each 'travel' post to a new defined id. </p>
<pre><code>
$terms = array(
'3845' => '1248'
);
$args = array(
'posts_per_page' => -1,
'post_type' => 'travel',
'post_status' => 'publish'
);
global $post;
$my_query = new WP_Query($args);
if($my_query->have_posts()){
while ($my_query->have_posts()) : $my_query->the_post();
/*
This is the part where i get lost, what i want is something like this, but this doesn't work
*/
if(in_array($post->term_id,$terms){
update term reference with value $terms[$post->term_id];
}
}
endwhile;
wp_reset_query();
}
</code></pre>
<p>Any help would be really appreciated because i'm pretty much stuck right now</p>
<p><strong>Edit:</strong>
I don't want to delete the taxonomy categories because this scripts will run after the imports so if the duplicates are deleted they will be imported straight back but with a different term id</p>
|
[
{
"answer_id": 198946,
"author": "webtoure",
"author_id": 72992,
"author_profile": "https://wordpress.stackexchange.com/users/72992",
"pm_score": 1,
"selected": false,
"text": "<p>There are quite a few steps involved here and also, with that 5000 posts figure you are mentioning, this will be an expensive task to do it through WordPress itself. However, here is what I came up with (<strong>I haven't tested this so you may wish to use it on a backup first and see if it works</strong>):</p>\n\n<pre><code>global $wpdb;\n\n/* The ( 'from_term_id', 'to_term_id' ) map. */\n$terms_map = array(\n '3845' => '1248',\n /* ... The rest of your mapping */\n);\n\n$taxonomy = 'country';\n$obj_terms = wp_get_object_terms( $post->ID, $taxonomy );\n\n/* Loop through each object term */\nforeach ( $obj_terms as $term ) {\n /* See if the obj term_id is a key in $terms_map */\n if ( isset( $terms_map[$term->term_id] ) ) {\n /* We have a valid key. We now need the term_taxonomy_ids */\n /* for both 'from_term_id' and 'to_term_id' */\n $to_term = get_term( $terms_map[$term->term_id], $taxonomy );\n\n $from_term_tax_id = $term->term_taxonomy_id;\n $to_term_tax_id = $to_term->term_taxonomy_id;\n\n /* Update the '{prefix}_term_relationships' table */\n $update_res = $wpdb->update( \n $wpdb->term_relationships, /* The table to update */\n array( 'term_taxonomy_id' => $to_term_tax_id ), /* Data to be updated */\n array( 'object_id' => $post->ID, 'term_taxonomy_id' => $from_term_tax_id ), /* Where clause */\n array( '%d' ), /* Format of the data is int */\n array( '%d', '%d' ) /* Format of the where clause is int */\n );\n\n /* Finally, you may wish to update the term count for each term */\n wp_update_term_count( array( $from_term_tax_id, $to_term_tax_id ), $taxonomy );\n }\n}\n</code></pre>\n\n<p>Like I've mentioned though this may prove to be too expensive in which case you will have to write a separate PHP script and work directly on the database.</p>\n"
},
{
"answer_id": 198989,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 0,
"selected": false,
"text": "<p>If I'm understanding your requirement correctly, then the least painful way to do this is with the <a href=\"https://wordpress.org/plugins/term-management-tools/\" rel=\"nofollow\">Term Management Tools</a> plugin. You can reorganize your terms in the admin interface once imported.</p>\n\n<p>EDIT: turns out I didn't understand your requirements correctly :)</p>\n"
},
{
"answer_id": 199646,
"author": "Maurice",
"author_id": 77252,
"author_profile": "https://wordpress.stackexchange.com/users/77252",
"pm_score": 1,
"selected": true,
"text": "<p>Unfortunately webtoure's solution didn't work so i decided to dive into Wordpress's database structure and came up with the following working code:</p>\n\n<pre><code>\nglobal $wpdb;\n$taxonomy = 'country';\n$environment = 0;\n\nfunction _get_term_taxonomy_id($term_id){\n global $wpdb;\n $results = $wpdb->get_results(\"\n SELECT tt.term_taxonomy_id\n FROM wp_term_taxonomy AS tt\n LEFT JOIN wp_terms AS t ON t.term_id = tt.term_id\n WHERE t.term_id = '$term_id'\n \");\n foreach($results as $result){\n return $result->term_taxonomy_id;\n }\n}\n\n/* MERGE */\nforeach($merge_map as $from => $to){\n $from_id = _get_term_taxonomy_id($from);\n $to_id = _get_term_taxonomy_id($to);\n if($environment == 1){\n $wpdb->update( \n 'wp_term_relationships', \n array( \n 'term_taxonomy_id' => $to_id\n ), \n array( 'term_taxonomy_id' => $from_id )\n );\n echo 'UPDATE '.$from_id.' with '.$to_id.' DONE\n';\n }\n}\n\n/* UPDATE PARENT */\nforeach($parent_map as $term_id => $parent_id){\n if($environment == 1){\n $wpdb->update( \n 'wp_term_taxonomy', \n array( \n 'parent' => $parent_id\n ), \n array( 'term_id' => $term_id )\n );\n echo 'UPDATE parent of '.$term_id.' with '.$parent_id.' DONE\n';\n }\n}\n</code></pre>\n"
}
] |
2015/08/11
|
[
"https://wordpress.stackexchange.com/questions/198266",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77252/"
] |
I have a situation where i have about 5000 imported records in a custom post type (travel) with a taxonomy category (country). Since i import from several different locations and each source seems to use a different description for some countries i want to update the term reference of that post to a uniform description.
So say the taxonomy 'country' has, amongst others, these values:
```
+---------+-------------+
| term_id | name |
+---------+-------------+
| 1248 | Zuid Afrika |
+---------+-------------+
| 3845 | zuid-afrika |
+---------+-------------+
```
I want to update the term reference to 'country' that has a duplicate in each 'travel' post to a new defined id.
```
$terms = array(
'3845' => '1248'
);
$args = array(
'posts_per_page' => -1,
'post_type' => 'travel',
'post_status' => 'publish'
);
global $post;
$my_query = new WP_Query($args);
if($my_query->have_posts()){
while ($my_query->have_posts()) : $my_query->the_post();
/*
This is the part where i get lost, what i want is something like this, but this doesn't work
*/
if(in_array($post->term_id,$terms){
update term reference with value $terms[$post->term_id];
}
}
endwhile;
wp_reset_query();
}
```
Any help would be really appreciated because i'm pretty much stuck right now
**Edit:**
I don't want to delete the taxonomy categories because this scripts will run after the imports so if the duplicates are deleted they will be imported straight back but with a different term id
|
Unfortunately webtoure's solution didn't work so i decided to dive into Wordpress's database structure and came up with the following working code:
```
global $wpdb;
$taxonomy = 'country';
$environment = 0;
function _get_term_taxonomy_id($term_id){
global $wpdb;
$results = $wpdb->get_results("
SELECT tt.term_taxonomy_id
FROM wp_term_taxonomy AS tt
LEFT JOIN wp_terms AS t ON t.term_id = tt.term_id
WHERE t.term_id = '$term_id'
");
foreach($results as $result){
return $result->term_taxonomy_id;
}
}
/* MERGE */
foreach($merge_map as $from => $to){
$from_id = _get_term_taxonomy_id($from);
$to_id = _get_term_taxonomy_id($to);
if($environment == 1){
$wpdb->update(
'wp_term_relationships',
array(
'term_taxonomy_id' => $to_id
),
array( 'term_taxonomy_id' => $from_id )
);
echo 'UPDATE '.$from_id.' with '.$to_id.' DONE
';
}
}
/* UPDATE PARENT */
foreach($parent_map as $term_id => $parent_id){
if($environment == 1){
$wpdb->update(
'wp_term_taxonomy',
array(
'parent' => $parent_id
),
array( 'term_id' => $term_id )
);
echo 'UPDATE parent of '.$term_id.' with '.$parent_id.' DONE
';
}
}
```
|
198,283 |
<p>I am using a custom post type that uses two taxonomies "colour" and "style". I have a script (<a href="https://stackoverflow.com/questions/31672345/sorting-custom-taxonomy-term-page-in-wordpress/">from this thread</a>) which groups them together so when you are on a colour taxonomy page they are grouped by style like this:</p>
<h2>Blue > Style 1</h2>
<ul>
<li>Product 1 </li>
<li>Product 2 </li>
<li>Product 3 </li>
<li>Product 4 </li>
<li>Product 5</li>
</ul>
<h2>Blue > Style 2</h2>
<ul>
<li>Product 1 </li>
<li>Product 2 </li>
<li>Product 3 </li>
<li>Product 4 </li>
<li>Product 5</li>
</ul>
<p>Now this all works great but it returns EVERY post. I want to limit it to the first three posts for each style. I know I can do something like the following but it limits posts for the whole page not per style. Any help? :)</p>
<pre><code>//limit to three per style
add_action('pre_get_posts', 'change_tax_num_of_posts' );
function change_tax_num_of_posts( $wp_query ) {
if( is_tax('colour') && is_main_query() ) {
$wp_query->set('posts_per_page', 3);
}
}
</code></pre>
|
[
{
"answer_id": 198348,
"author": "caffeinehigh",
"author_id": 77625,
"author_profile": "https://wordpress.stackexchange.com/users/77625",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, I think I have found a way of doing this. Although I must say I haven't tested it out yet and it's probably not the best way. So happy to see any other solutions.</p>\n\n<p>What I have done is created a meta box in my custom post with a radio button that has options \"featured\" and \"not featured\". I set the three custom posts of each group I want to show and then filter the main query with the meta key that matches. Like so:</p>\n\n<pre><code>function colour_tax_featured($query) {\n\nif( is_tax('colour') && $query->is_main_query() ) {\n\n $query->set('meta_key', 'meta_box_featured_colour');\n $query->set('meta_value', 'featured_colour');\n return $query;\n}\n\n }\n\n add_action('pre_get_posts', 'colour_tax_featured' );\n</code></pre>\n"
},
{
"answer_id": 198448,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": true,
"text": "<p>As I have stated in comments, this will take some work. In short, you will need the following:</p>\n\n<ul>\n<li><p>Get all the terms from the <code>style</code> taxonomy. Here we would only want the term ids</p></li>\n<li><p>Get the current <code>tax_query</code> from the <code>colour</code> taxonomy. Use each term from the <code>style</code> taxonomy and create a new <code>tax_query</code> to get posts from the current page's term and the term being looped over from the <code>style</code> taxonomy</p></li>\n<li><p>Run a custom query on each term from the <code>style</code> taxonomy to get an array of post ids from each term. Here you would want to add all your custom parameters. We will use the order from this custom queries as post order</p></li>\n<li><p>Pass the array of post ids to the main query. Here you would not want to add custom sorting etc. We will use the sequence of the post ids in the post id array for sorting</p></li>\n</ul>\n\n<h2>FEW NOTES BEFORE THE CODE:</h2>\n\n<ul>\n<li><p>The code requires PHP 5.4+ due to the use of short array syntax (<code>[]</code>). You should also not be using any version older than PHP5.4. If you however do, just change the short array syntax to the old array syntax (<code>array()</code>). For example, <code>get_terms( $taxonomy, ['fields' => 'ids'] )</code> should become <code>get_terms( $taxonomy, array( 'fields' => 'ids' ) )</code></p></li>\n<li><p>I have build in a transient system to reduce the extra strain coming from all the extra work that we need to do. This transient is set to expire in a week, you can adjust this to be longer or shorter. The transient will be automatically deleted when a new post is published, deleted, undeleted or updated</p></li>\n<li><p>I have commented the code very well so you can follow and make some kind of sense from what I was doing as I went along</p></li>\n<li><p>You can extend and modify as needed. Make sure to check out my comments</p></li>\n<li><p>With this new code, you can scrap my complete idea of sorting as described in <a href=\"https://stackoverflow.com/a/31705710/1908141\">my linked answer on SO</a>. The code given in this answer should take care of this sorting. Any adjustments that you would want to make should be done in the custom queries and <code>get_terms</code> calls. Just remember to flush your transients after each modification, or better, uncomment the transient calls and return to normal once you are happy with all your modifications</p></li>\n</ul>\n\n<h2>THE CODE:</h2>\n\n<p>As always, we will be using <code>pre_get_posts</code> to alter the main query as needed</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{ \n if ( !is_admin() // Targets only front end queries\n && $q->is_main_query() // Targets only main query\n && $q->is_tax( 'colour' ) // Targets only taxonomy pages\n ) {\n\n /** \n * To save on the extra work that we need to do to get our results,\n * lets save everything in a transient. We will save the string of post ids\n * in the transient. \n *\n * We will only delete and recreate this transient when a new post is published,\n * deleted, undeleted or updated. This will save us a lot of extra hard work\n * on every page load\n *\n * @link https://codex.wordpress.org/Transients_API\n */\n $queried_object = get_queried_object(); // Get the current queried object to build a unique transient name\n /**\n * Use md5 to build a unique transient name to avoid any conflicts\n * The code below will create a unique transient name which will look like this\n * \"colourtax_1ac37e97ee207e952dfc2b8f7eef110f\"\n *\n * Note, this should NOT be longer that 45 characters else the transient will be regenerated\n * on each page load. Transients are expensive to create, so don't want to recreate this on every\n * page load due to a name being to long. As a quick guide the md5 part generate a 32 character string,\n * so the \"colourtax_\" part should be a maximum of 13 characters\n */\n $unique_transient_name = 'colourtax_' . md5( $queried_object->taxonomy . $queried_object->slug . $queried_object->term_id );\n if ( false === ( $post_ids_array = get_transient( $unique_transient_name ) ) ) {\n\n // Gets the current tax_query\n $tax_query = $q->tax_query->queries; \n // Choose the taxonomy to sort by\n $taxonomy = 'style'; \n // Set the variable to hold the sorted post ids according to terms\n $post_ids_array = [];\n\n /**\n * Get all the terms from the selected taxonomy to sort by. Just get term ids\n * Add additional arguments here as needed\n * \n * @link https://codex.wordpress.org/Function_Reference/get_terms\n */\n $terms = get_terms( $taxonomy, ['fields' => 'ids'] ); \n if ( $terms // Check if the array has valid terms, not empty\n && !is_wp_error( $terms ) // Check that we do not have any error\n ) { \n // Define a variable to hold all post ID\n $posts_ids = '';\n foreach ( $terms as $term ) {\n /**\n * NOTE: You would want to do everything here\n *\n * Build our query args, add all your relevant arguments here\n * You should extend this to include your custom parameter values\n * like meta_queries en sorting order.\n * Do a var_dump( $wp_query ) and use the relevant arguments from\n * there to make this dynamic\n */\n $args = [\n 'post_type' => 'any',\n 'posts_per_page' => 3, // Get only 3 posts per term\n 'fields' => 'ids', // Only get post ids to make query faster and more lean\n // Build a tax_query to add additional terms from selected taxonomy to sort by \n 'tax_query' => [ \n $tax_query, // Our default tax_query from the taxonomy page\n [\n 'taxonomy' => $taxonomy,\n 'terms' => $term,\n 'include_children' => false,\n ],\n ],\n ];\n // Return an array of post ids only\n $posts_array = get_posts( $args );\n // First check if we have posts to avoid bugs in our code\n if ( $posts_array ) {\n // Break the ids array up into a string for later processing\n foreach ( $posts_array as $v )\n $posts_ids .= ' ' . $v;\n unset( $v ); \n } //endif $posts_array\n\n } //endforeach $terms\n unset( $term );\n\n // ADDITIONAL, CAN DELETE THE FOLLOWING SECTION IF YOU WANT TO. READ COMMENTS BELOW\n\n /**\n * You can remove the following section. The idea here is as follow:\n * Any post without a term in the style taxonomy will not be displayed on\n * a colour taxonomy term page. To avoid this, we will need to get all posts\n * that does not have a post in style taxonomy. This posts will be displayed last\n * on the page\n *\n * If you are very sure that all posts are tagged in a colour AND style taxonomy\n * term, then you can remove this section, this is really just a fall back\n */\n $args_additional = [\n 'post_type' => 'any',\n 'posts_per_page' => 3, // Get only 3 posts without style taxonomy term, adjust as needed\n 'fields' => 'ids', // Only get post ids to make query faster and more lean\n // Build a tax_query to get posts that is not tagged in style taxonomy \n 'tax_query' => [ \n $tax_query, // Our default tax_query from the taxonomy page\n [\n 'taxonomy' => $taxonomy,\n 'terms' => $terms,\n 'include_children' => false,\n 'operator' => 'NOT IN', // Posts should not have these terms from style taxonomy\n ],\n ],\n ];\n // Return an array of post ids only\n $posts_array_2 = get_posts( $args_additional );\n // First check if we have posts to avoid bugs in our code\n if ( $posts_array_2 ) {\n // Break the ids array up into a string for later processing\n foreach ( $posts_array_2 as $v )\n $posts_ids .= ' ' . $v;\n unset( $v ); \n } //endif $posts_array\n\n // STOP DELETING HERE!!\n\n // Create an array of post ids from the $posts_ids string\n $post_ids_array = explode( ' ', ltrim( $posts_ids ) );\n\n } //endif $terms\n\n /**\n * Set the transient if it does not exist. \n * NOTE: We will choose a week for expiry date, set as needed\n *\n * @link https://codex.wordpress.org/Transients_API#Using_Time_Constants\n */ \n set_transient( $unique_transient_name, $post_ids_array, 7 * DAY_IN_SECONDS ); \n } // endif transient check\n\n /**\n * Check if we have an array of post ID's before changing anything on the tax page\n *\n * Here we will alter the main query. You do not want to add or remove anything\n * here. Any custom parameters like sorting should be done in the custom queries\n * above\n *\n * DO NOT CHANGE ANYTHING IN THE CODE BELOW EXCEPT posts_per_page\n */\n if ( !empty( $post_ids_array ) ) {\n $q->set( 'post__in', $post_ids_array ); // Posts to get as set in our array, max of 3 posts per term\n $q->set( 'orderby', 'post_in' ); // Sort our posts in the order it is passed in the post__in array\n $q->set( 'order', 'ASC' );\n $q->set( 'posts_per_page', -1 ); // You can change this, if I remember, you need all posts on one page\n }\n\n } //endif conditional checks for query\n});\n</code></pre>\n\n<p>This will take care of everything except the flushing of the transients on post publish, delete, etc</p>\n\n<p>The following code will take care of this. Everytime a post is updated, published, trashed or untrashed, the <code>transition_post_status</code> hook fires, so we will use that logic to delete all our transients which contains part of the <code>colourtax_</code> name</p>\n\n<pre><code>add_action( 'transition_post_status', function ()\n{\n global $wpdb;\n $wpdb->query( \"DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_colourtax_%')\" );\n $wpdb->query( \"DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_colourtax_%')\" );\n});\n</code></pre>\n"
}
] |
2015/08/11
|
[
"https://wordpress.stackexchange.com/questions/198283",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77625/"
] |
I am using a custom post type that uses two taxonomies "colour" and "style". I have a script ([from this thread](https://stackoverflow.com/questions/31672345/sorting-custom-taxonomy-term-page-in-wordpress/)) which groups them together so when you are on a colour taxonomy page they are grouped by style like this:
Blue > Style 1
--------------
* Product 1
* Product 2
* Product 3
* Product 4
* Product 5
Blue > Style 2
--------------
* Product 1
* Product 2
* Product 3
* Product 4
* Product 5
Now this all works great but it returns EVERY post. I want to limit it to the first three posts for each style. I know I can do something like the following but it limits posts for the whole page not per style. Any help? :)
```
//limit to three per style
add_action('pre_get_posts', 'change_tax_num_of_posts' );
function change_tax_num_of_posts( $wp_query ) {
if( is_tax('colour') && is_main_query() ) {
$wp_query->set('posts_per_page', 3);
}
}
```
|
As I have stated in comments, this will take some work. In short, you will need the following:
* Get all the terms from the `style` taxonomy. Here we would only want the term ids
* Get the current `tax_query` from the `colour` taxonomy. Use each term from the `style` taxonomy and create a new `tax_query` to get posts from the current page's term and the term being looped over from the `style` taxonomy
* Run a custom query on each term from the `style` taxonomy to get an array of post ids from each term. Here you would want to add all your custom parameters. We will use the order from this custom queries as post order
* Pass the array of post ids to the main query. Here you would not want to add custom sorting etc. We will use the sequence of the post ids in the post id array for sorting
FEW NOTES BEFORE THE CODE:
--------------------------
* The code requires PHP 5.4+ due to the use of short array syntax (`[]`). You should also not be using any version older than PHP5.4. If you however do, just change the short array syntax to the old array syntax (`array()`). For example, `get_terms( $taxonomy, ['fields' => 'ids'] )` should become `get_terms( $taxonomy, array( 'fields' => 'ids' ) )`
* I have build in a transient system to reduce the extra strain coming from all the extra work that we need to do. This transient is set to expire in a week, you can adjust this to be longer or shorter. The transient will be automatically deleted when a new post is published, deleted, undeleted or updated
* I have commented the code very well so you can follow and make some kind of sense from what I was doing as I went along
* You can extend and modify as needed. Make sure to check out my comments
* With this new code, you can scrap my complete idea of sorting as described in [my linked answer on SO](https://stackoverflow.com/a/31705710/1908141). The code given in this answer should take care of this sorting. Any adjustments that you would want to make should be done in the custom queries and `get_terms` calls. Just remember to flush your transients after each modification, or better, uncomment the transient calls and return to normal once you are happy with all your modifications
THE CODE:
---------
As always, we will be using `pre_get_posts` to alter the main query as needed
```
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() // Targets only front end queries
&& $q->is_main_query() // Targets only main query
&& $q->is_tax( 'colour' ) // Targets only taxonomy pages
) {
/**
* To save on the extra work that we need to do to get our results,
* lets save everything in a transient. We will save the string of post ids
* in the transient.
*
* We will only delete and recreate this transient when a new post is published,
* deleted, undeleted or updated. This will save us a lot of extra hard work
* on every page load
*
* @link https://codex.wordpress.org/Transients_API
*/
$queried_object = get_queried_object(); // Get the current queried object to build a unique transient name
/**
* Use md5 to build a unique transient name to avoid any conflicts
* The code below will create a unique transient name which will look like this
* "colourtax_1ac37e97ee207e952dfc2b8f7eef110f"
*
* Note, this should NOT be longer that 45 characters else the transient will be regenerated
* on each page load. Transients are expensive to create, so don't want to recreate this on every
* page load due to a name being to long. As a quick guide the md5 part generate a 32 character string,
* so the "colourtax_" part should be a maximum of 13 characters
*/
$unique_transient_name = 'colourtax_' . md5( $queried_object->taxonomy . $queried_object->slug . $queried_object->term_id );
if ( false === ( $post_ids_array = get_transient( $unique_transient_name ) ) ) {
// Gets the current tax_query
$tax_query = $q->tax_query->queries;
// Choose the taxonomy to sort by
$taxonomy = 'style';
// Set the variable to hold the sorted post ids according to terms
$post_ids_array = [];
/**
* Get all the terms from the selected taxonomy to sort by. Just get term ids
* Add additional arguments here as needed
*
* @link https://codex.wordpress.org/Function_Reference/get_terms
*/
$terms = get_terms( $taxonomy, ['fields' => 'ids'] );
if ( $terms // Check if the array has valid terms, not empty
&& !is_wp_error( $terms ) // Check that we do not have any error
) {
// Define a variable to hold all post ID
$posts_ids = '';
foreach ( $terms as $term ) {
/**
* NOTE: You would want to do everything here
*
* Build our query args, add all your relevant arguments here
* You should extend this to include your custom parameter values
* like meta_queries en sorting order.
* Do a var_dump( $wp_query ) and use the relevant arguments from
* there to make this dynamic
*/
$args = [
'post_type' => 'any',
'posts_per_page' => 3, // Get only 3 posts per term
'fields' => 'ids', // Only get post ids to make query faster and more lean
// Build a tax_query to add additional terms from selected taxonomy to sort by
'tax_query' => [
$tax_query, // Our default tax_query from the taxonomy page
[
'taxonomy' => $taxonomy,
'terms' => $term,
'include_children' => false,
],
],
];
// Return an array of post ids only
$posts_array = get_posts( $args );
// First check if we have posts to avoid bugs in our code
if ( $posts_array ) {
// Break the ids array up into a string for later processing
foreach ( $posts_array as $v )
$posts_ids .= ' ' . $v;
unset( $v );
} //endif $posts_array
} //endforeach $terms
unset( $term );
// ADDITIONAL, CAN DELETE THE FOLLOWING SECTION IF YOU WANT TO. READ COMMENTS BELOW
/**
* You can remove the following section. The idea here is as follow:
* Any post without a term in the style taxonomy will not be displayed on
* a colour taxonomy term page. To avoid this, we will need to get all posts
* that does not have a post in style taxonomy. This posts will be displayed last
* on the page
*
* If you are very sure that all posts are tagged in a colour AND style taxonomy
* term, then you can remove this section, this is really just a fall back
*/
$args_additional = [
'post_type' => 'any',
'posts_per_page' => 3, // Get only 3 posts without style taxonomy term, adjust as needed
'fields' => 'ids', // Only get post ids to make query faster and more lean
// Build a tax_query to get posts that is not tagged in style taxonomy
'tax_query' => [
$tax_query, // Our default tax_query from the taxonomy page
[
'taxonomy' => $taxonomy,
'terms' => $terms,
'include_children' => false,
'operator' => 'NOT IN', // Posts should not have these terms from style taxonomy
],
],
];
// Return an array of post ids only
$posts_array_2 = get_posts( $args_additional );
// First check if we have posts to avoid bugs in our code
if ( $posts_array_2 ) {
// Break the ids array up into a string for later processing
foreach ( $posts_array_2 as $v )
$posts_ids .= ' ' . $v;
unset( $v );
} //endif $posts_array
// STOP DELETING HERE!!
// Create an array of post ids from the $posts_ids string
$post_ids_array = explode( ' ', ltrim( $posts_ids ) );
} //endif $terms
/**
* Set the transient if it does not exist.
* NOTE: We will choose a week for expiry date, set as needed
*
* @link https://codex.wordpress.org/Transients_API#Using_Time_Constants
*/
set_transient( $unique_transient_name, $post_ids_array, 7 * DAY_IN_SECONDS );
} // endif transient check
/**
* Check if we have an array of post ID's before changing anything on the tax page
*
* Here we will alter the main query. You do not want to add or remove anything
* here. Any custom parameters like sorting should be done in the custom queries
* above
*
* DO NOT CHANGE ANYTHING IN THE CODE BELOW EXCEPT posts_per_page
*/
if ( !empty( $post_ids_array ) ) {
$q->set( 'post__in', $post_ids_array ); // Posts to get as set in our array, max of 3 posts per term
$q->set( 'orderby', 'post_in' ); // Sort our posts in the order it is passed in the post__in array
$q->set( 'order', 'ASC' );
$q->set( 'posts_per_page', -1 ); // You can change this, if I remember, you need all posts on one page
}
} //endif conditional checks for query
});
```
This will take care of everything except the flushing of the transients on post publish, delete, etc
The following code will take care of this. Everytime a post is updated, published, trashed or untrashed, the `transition_post_status` hook fires, so we will use that logic to delete all our transients which contains part of the `colourtax_` name
```
add_action( 'transition_post_status', function ()
{
global $wpdb;
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_colourtax_%')" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_colourtax_%')" );
});
```
|
198,343 |
<p>For each post, I want to send an email once it has been published. The email address is stored in a custom field.</p>
<p>I have added a custom field . I have got <code>your_email</code> for the 'name'and the value is my email address (as a test).</p>
<p>I have got the following code in functions.php :</p>
<pre><code>function ik_send_email($post_id){
$email_address = get_post_meta($post_id, 'your_email', true);
$subject = "Your Subject Here!";
$body = "Thank you for your submission! Your story has been approved!";
$headers = 'From: From Address <[email protected]>' . "\r\n";
if(wp_mail($email_address, $subject, $body, $headers)){
//mail sent!
} else {
//failure!
}
}
add_action('publish_post','ik_send_email');
</code></pre>
<p>So once I click 'published' it should send an email to the address entered in the custom field, but I'm not getting an email? Any tips someone can give please?</p>
|
[
{
"answer_id": 198346,
"author": "Emetrop",
"author_id": 64623,
"author_profile": "https://wordpress.stackexchange.com/users/64623",
"pm_score": 0,
"selected": false,
"text": "<p>Your code looks good. I'd bet with you that it's a problem with configuration of email sending server. Maybe you haven't configured sendmail on your hosting. You can make it works easily if you send emails via a SMTP server (ie. gmail). You can do it easily with WP Mail SMTP plugin. Or just write to your hosting provider to make it working.</p>\n"
},
{
"answer_id": 198347,
"author": "Kevin Fodness",
"author_id": 77460,
"author_profile": "https://wordpress.stackexchange.com/users/77460",
"pm_score": 2,
"selected": true,
"text": "<p>Try logging out of the site and going to /wp-admin (to get to the login screen). Click on the Forgot Password link and enter your username. Did you get an email with password reset instructions? If not, that means that the email configuration (as Emetrop has suggested) may not be correct for the server.</p>\n"
}
] |
2015/08/11
|
[
"https://wordpress.stackexchange.com/questions/198343",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
For each post, I want to send an email once it has been published. The email address is stored in a custom field.
I have added a custom field . I have got `your_email` for the 'name'and the value is my email address (as a test).
I have got the following code in functions.php :
```
function ik_send_email($post_id){
$email_address = get_post_meta($post_id, 'your_email', true);
$subject = "Your Subject Here!";
$body = "Thank you for your submission! Your story has been approved!";
$headers = 'From: From Address <[email protected]>' . "\r\n";
if(wp_mail($email_address, $subject, $body, $headers)){
//mail sent!
} else {
//failure!
}
}
add_action('publish_post','ik_send_email');
```
So once I click 'published' it should send an email to the address entered in the custom field, but I'm not getting an email? Any tips someone can give please?
|
Try logging out of the site and going to /wp-admin (to get to the login screen). Click on the Forgot Password link and enter your username. Did you get an email with password reset instructions? If not, that means that the email configuration (as Emetrop has suggested) may not be correct for the server.
|
198,362 |
<p>I've got my custom post type 'event'. I got tne next code in single-event.php:</p>
<pre><code>get_header();
the_post();
echo '<pre>';
echo "$post->ID\n";
var_dump(get_post_meta($post->ID));
echo '</pre>';
</code></pre>
<p>When I open my event page by normal URI /event/slug/, I got this:</p>
<pre><code>22681
array(17) {
["_edit_lock"]=>
array(1) {
[0]=>
string(13) "1439329938:36"
}
["_edit_last"]=>
array(1) {
[0]=>
string(2) "36"
}
...
}
</code></pre>
<p>When I open it for preview, like /event/slug/?preview=true&preview_id=22681&preview_nonce=XXXXXXXXXXXXX , I got only this:</p>
<pre><code>22681
string(0) ""
</code></pre>
<p>(where first line is a correct post ID and is the same as preview_id param)</p>
<p>What am I doing wrong? And why <code>string(0)</code>, and not <code>array(0)</code>?</p>
|
[
{
"answer_id": 198346,
"author": "Emetrop",
"author_id": 64623,
"author_profile": "https://wordpress.stackexchange.com/users/64623",
"pm_score": 0,
"selected": false,
"text": "<p>Your code looks good. I'd bet with you that it's a problem with configuration of email sending server. Maybe you haven't configured sendmail on your hosting. You can make it works easily if you send emails via a SMTP server (ie. gmail). You can do it easily with WP Mail SMTP plugin. Or just write to your hosting provider to make it working.</p>\n"
},
{
"answer_id": 198347,
"author": "Kevin Fodness",
"author_id": 77460,
"author_profile": "https://wordpress.stackexchange.com/users/77460",
"pm_score": 2,
"selected": true,
"text": "<p>Try logging out of the site and going to /wp-admin (to get to the login screen). Click on the Forgot Password link and enter your username. Did you get an email with password reset instructions? If not, that means that the email configuration (as Emetrop has suggested) may not be correct for the server.</p>\n"
}
] |
2015/08/11
|
[
"https://wordpress.stackexchange.com/questions/198362",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56959/"
] |
I've got my custom post type 'event'. I got tne next code in single-event.php:
```
get_header();
the_post();
echo '<pre>';
echo "$post->ID\n";
var_dump(get_post_meta($post->ID));
echo '</pre>';
```
When I open my event page by normal URI /event/slug/, I got this:
```
22681
array(17) {
["_edit_lock"]=>
array(1) {
[0]=>
string(13) "1439329938:36"
}
["_edit_last"]=>
array(1) {
[0]=>
string(2) "36"
}
...
}
```
When I open it for preview, like /event/slug/?preview=true&preview\_id=22681&preview\_nonce=XXXXXXXXXXXXX , I got only this:
```
22681
string(0) ""
```
(where first line is a correct post ID and is the same as preview\_id param)
What am I doing wrong? And why `string(0)`, and not `array(0)`?
|
Try logging out of the site and going to /wp-admin (to get to the login screen). Click on the Forgot Password link and enter your username. Did you get an email with password reset instructions? If not, that means that the email configuration (as Emetrop has suggested) may not be correct for the server.
|
198,422 |
<p>If I am on a product archive page then how can I get current product category ID in product archive page. I am using this but no result:</p>
<pre><code>global $wp_query;
$category_name = $wp_query->query_vars['product_cat'];
$category_object = get_term_by('name', $category_name, 'product_cat');
$category_id = $category_object->term_id;
</code></pre>
|
[
{
"answer_id": 198425,
"author": "Exclutips",
"author_id": 74748,
"author_profile": "https://wordpress.stackexchange.com/users/74748",
"pm_score": 5,
"selected": false,
"text": "<p>I solve This To get the current category ID.</p>\n\n<pre><code>$cate = get_queried_object();\n$cateID = $cate->term_id;\necho $cateID;\n</code></pre>\n\n<p>and it works like a charm.</p>\n"
},
{
"answer_id": 304299,
"author": "Alex Marques",
"author_id": 144169,
"author_profile": "https://wordpress.stackexchange.com/users/144169",
"pm_score": -1,
"selected": false,
"text": "<p>Funciona perfeitamente!</p>\n\n<pre><code> <?php\nglobal $post;\n$terms = get_the_terms( $post->ID, 'product_cat' );\nforeach ( $terms as $term ) {\n $product_cat_id = $term->term_id;\n if( $term = get_term_by( 'id', $product_cat_id, 'product_cat' ) ){echo $term->name;}\n break;\n}?>\n</code></pre>\n"
}
] |
2015/08/12
|
[
"https://wordpress.stackexchange.com/questions/198422",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74748/"
] |
If I am on a product archive page then how can I get current product category ID in product archive page. I am using this but no result:
```
global $wp_query;
$category_name = $wp_query->query_vars['product_cat'];
$category_object = get_term_by('name', $category_name, 'product_cat');
$category_id = $category_object->term_id;
```
|
I solve This To get the current category ID.
```
$cate = get_queried_object();
$cateID = $cate->term_id;
echo $cateID;
```
and it works like a charm.
|
198,435 |
<p>I need to use PHP's <code>DateTime()</code>. It's currently displaying GMT time instead of the time that's set for the timezone setting (EST) in the WordPress Admin.</p>
<p>How can this be converted to show the the time base</p>
<pre><code>$time = new DateTime();
echo $time->format("Y-m-d h:i:s");
// 2015-08-12 04:35:34 (gmt)
// 2015-08-12 12:35:34 (what i want -- EST)
</code></pre>
|
[
{
"answer_id": 198438,
"author": "EliasNS",
"author_id": 40743,
"author_profile": "https://wordpress.stackexchange.com/users/40743",
"pm_score": -1,
"selected": false,
"text": "<p><code>DateTime</code> aceppts a <code>DateTimeZone</code> parameter, that you can get from WordPress options. Something like:</p>\n\n<pre><code>$time = new DateTime(NULL, get_option('gmt_offset'));\n</code></pre>\n\n<ul>\n<li><a href=\"http://es1.php.net/manual/en/class.datetimezone.php\" rel=\"nofollow noreferrer\">DateTime</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/8400/how-to-get-wordpress-time-zone-setting\">WordPress TimeZone</a></li>\n</ul>\n\n<p>Hope this helps.</p>\n\n<p>Edit: I'm testing it and I get an error. I don't know how to convert the <code>timezone string</code> to a <code>DateTimeZone</code> object, but that is the way.</p>\n"
},
{
"answer_id": 198453,
"author": "Stephen Harris",
"author_id": 9364,
"author_profile": "https://wordpress.stackexchange.com/users/9364",
"pm_score": 4,
"selected": true,
"text": "<p>I'm not sure why EliasNS' answer is marked correct, as far as I'm aware (and from the <a href=\"http://es1.php.net/manual/en/datetime.construct.php\" rel=\"nofollow noreferrer\">documentation</a>), the second parameter of <code>DateTime::__construct()</code>, if provided, should be a <code>DateTimeZone</code> instance.</p>\n\n<p>The problem then becomes, how we do we create a <code>DateTimeZone</code> instance. This is easy if the user has selected a city as their timezone, but we can work around it if they have set an offset by using the (deprecated) Etc/GMT timezones.</p>\n\n<pre><code>/**\n * Returns the blog timezone\n *\n * Gets timezone settings from the db. If a timezone identifier is used just turns\n * it into a DateTimeZone. If an offset is used, it tries to find a suitable timezone.\n * If all else fails it uses UTC.\n *\n * @return DateTimeZone The blog timezone\n */\nfunction wpse198435_get_blog_timezone() {\n\n $tzstring = get_option( 'timezone_string' );\n $offset = get_option( 'gmt_offset' );\n\n //Manual offset...\n //@see http://us.php.net/manual/en/timezones.others.php\n //@see https://bugs.php.net/bug.php?id=45543\n //@see https://bugs.php.net/bug.php?id=45528\n //IANA timezone database that provides PHP's timezone support uses POSIX (i.e. reversed) style signs\n if( empty( $tzstring ) && 0 != $offset && floor( $offset ) == $offset ){\n $offset_st = $offset > 0 ? \"-$offset\" : '+'.absint( $offset );\n $tzstring = 'Etc/GMT'.$offset_st;\n }\n\n //Issue with the timezone selected, set to 'UTC'\n if( empty( $tzstring ) ){\n $tzstring = 'UTC';\n }\n\n $timezone = new DateTimeZone( $tzstring );\n return $timezone; \n}\n</code></pre>\n\n<p>Then you can use it as follows:</p>\n\n<pre><code>$time = new DateTime( null, wpse198435_get_blog_timezone() );\n</code></pre>\n"
},
{
"answer_id": 265805,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>I had developed a method in my lib to retrieve current WP’s time zone as proper object: <a href=\"https://github.com/Rarst/wpdatetime/blob/master/src/WpDateTimeZone.php\" rel=\"nofollow noreferrer\"><code>WpDateTimeZone::getWpTimezone()</code></a>.</p>\n\n<p>While <code>timezone_string</code> is straightforward (it is already a valid time zone name), <code>gmt_offset</code> case is nasty. Best I could come up with is converting it into a <code>+00:00</code> format:</p>\n\n<pre><code>$offset = get_option( 'gmt_offset' );\n$hours = (int) $offset;\n$minutes = ( $offset - floor( $offset ) ) * 60;\n$offset = sprintf( '%+03d:%02d', $hours, $minutes )\n</code></pre>\n"
}
] |
2015/08/12
|
[
"https://wordpress.stackexchange.com/questions/198435",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1462/"
] |
I need to use PHP's `DateTime()`. It's currently displaying GMT time instead of the time that's set for the timezone setting (EST) in the WordPress Admin.
How can this be converted to show the the time base
```
$time = new DateTime();
echo $time->format("Y-m-d h:i:s");
// 2015-08-12 04:35:34 (gmt)
// 2015-08-12 12:35:34 (what i want -- EST)
```
|
I'm not sure why EliasNS' answer is marked correct, as far as I'm aware (and from the [documentation](http://es1.php.net/manual/en/datetime.construct.php)), the second parameter of `DateTime::__construct()`, if provided, should be a `DateTimeZone` instance.
The problem then becomes, how we do we create a `DateTimeZone` instance. This is easy if the user has selected a city as their timezone, but we can work around it if they have set an offset by using the (deprecated) Etc/GMT timezones.
```
/**
* Returns the blog timezone
*
* Gets timezone settings from the db. If a timezone identifier is used just turns
* it into a DateTimeZone. If an offset is used, it tries to find a suitable timezone.
* If all else fails it uses UTC.
*
* @return DateTimeZone The blog timezone
*/
function wpse198435_get_blog_timezone() {
$tzstring = get_option( 'timezone_string' );
$offset = get_option( 'gmt_offset' );
//Manual offset...
//@see http://us.php.net/manual/en/timezones.others.php
//@see https://bugs.php.net/bug.php?id=45543
//@see https://bugs.php.net/bug.php?id=45528
//IANA timezone database that provides PHP's timezone support uses POSIX (i.e. reversed) style signs
if( empty( $tzstring ) && 0 != $offset && floor( $offset ) == $offset ){
$offset_st = $offset > 0 ? "-$offset" : '+'.absint( $offset );
$tzstring = 'Etc/GMT'.$offset_st;
}
//Issue with the timezone selected, set to 'UTC'
if( empty( $tzstring ) ){
$tzstring = 'UTC';
}
$timezone = new DateTimeZone( $tzstring );
return $timezone;
}
```
Then you can use it as follows:
```
$time = new DateTime( null, wpse198435_get_blog_timezone() );
```
|
198,447 |
<p>Within the WooCommerce template file "content-product.php", I'm trying to overwrite the following action hook:</p>
<pre><code>/**
* woocommerce_shop_loop_item_title hook
*
* @hooked woocommerce_template_loop_product_title - 10
*/
do_action( 'woocommerce_shop_loop_item_title' );
</code></pre>
<p>To overwrite this hook, I have added the following to my functions.php file:</p>
<p>add_action('woocommerce_shop_loop_item_title', 'change_product_title');</p>
<pre><code>function change_product_title() {
echo'<header class="entry-header"><h1 class="entry-title">'.get_the_title().'</h1></header>';
}
</code></pre>
<p>This only adds to the hook. How do I completly replace the hook with my own code? I have checked the WooCommerce documentation, but it doesn't give you a great deal to go on.</p>
|
[
{
"answer_id": 198449,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>in WordPress, you cannot just \"overwrite\" a hook (that's works only for pluggable functions)</p>\n\n<p>but, you can add new fonction to the same hook and remove an action.</p>\n\n<p>try something like this : </p>\n\n<pre><code>add_action(\"init\", function () {\n // removing the woocommerce hook\n remove_action('woocommerce_shop_loop_item_title', 'change_product_title');\n});\n\n// add a new fonction to the hook\nadd_action(\"woocommerce_shop_loop_item_title\", function () {\n\n echo \"my new action\";\n\n});\n</code></pre>\n"
},
{
"answer_id": 198472,
"author": "Chris",
"author_id": 77693,
"author_profile": "https://wordpress.stackexchange.com/users/77693",
"pm_score": 4,
"selected": true,
"text": "<p>It's actually pretty simple to change the title in content-product.php, but you won't be able to do it with a hook. Near the top of the file, you should see this line:</p>\n\n<pre><code>Override this template by copying it to yourtheme/woocommerce/content-product.php\n</code></pre>\n\n<p>All you have to do is copy the file to the above directory, replacing \"yourtheme\" with your theme's actual folder name, and make your desired edits to the new file.</p>\n\n<p><strong>A little more background on hooks</strong></p>\n\n<p>The title in the default content-product.php template file is outputted like this, which is defined in wc-template-functions.php if you search for woocommerce_template_loop_product_title() it echos the below title:</p>\n\n<pre><code><h3><?php the_title(); ?></h3>\n</code></pre>\n\n<p>In order to change the title with a hook, you'd need to change the above line to this, but you can't do this without changing the wc-template-functions.php file. So what you can do is comment out the action in the content-product.php file:</p>\n\n<pre><code>//do_action( 'woocommerce_shop_loop_item_title' );\n</code></pre>\n\n<p>and then add the below line:</p>\n\n<pre><code>?><h3><?php echo apply_filters( 'my_filter_name', get_the_title() ); ?></h3><?php\n</code></pre>\n\n<p>so the saved version looks like this:</p>\n\n<pre><code>//do_action( 'woocommerce_shop_loop_item_title' );\n?><h3><?php echo apply_filters( 'my_filter_name', get_the_title() ); ?></h3><?php\n</code></pre>\n\n<p>Then, you would need to add the following to your theme's functions.php file which will pass the contents of get_the_title() to the $title parameter, which you can then change any way you wish, but in the below case will change every title to say \"Custom Title\":</p>\n\n<pre><code>add_filter( 'my_filter_name', 'my_custom_function' );\n\nfunction my_custom_function( $title ) {\n return 'Custom Title';\n}\n</code></pre>\n\n<p>For more information, see the following:</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/apply_filters\" rel=\"noreferrer\">http://codex.wordpress.org/Function_Reference/apply_filters</a></p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/add_filter\" rel=\"noreferrer\">http://codex.wordpress.org/Function_Reference/add_filter</a></p>\n"
}
] |
2015/08/12
|
[
"https://wordpress.stackexchange.com/questions/198447",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37548/"
] |
Within the WooCommerce template file "content-product.php", I'm trying to overwrite the following action hook:
```
/**
* woocommerce_shop_loop_item_title hook
*
* @hooked woocommerce_template_loop_product_title - 10
*/
do_action( 'woocommerce_shop_loop_item_title' );
```
To overwrite this hook, I have added the following to my functions.php file:
add\_action('woocommerce\_shop\_loop\_item\_title', 'change\_product\_title');
```
function change_product_title() {
echo'<header class="entry-header"><h1 class="entry-title">'.get_the_title().'</h1></header>';
}
```
This only adds to the hook. How do I completly replace the hook with my own code? I have checked the WooCommerce documentation, but it doesn't give you a great deal to go on.
|
It's actually pretty simple to change the title in content-product.php, but you won't be able to do it with a hook. Near the top of the file, you should see this line:
```
Override this template by copying it to yourtheme/woocommerce/content-product.php
```
All you have to do is copy the file to the above directory, replacing "yourtheme" with your theme's actual folder name, and make your desired edits to the new file.
**A little more background on hooks**
The title in the default content-product.php template file is outputted like this, which is defined in wc-template-functions.php if you search for woocommerce\_template\_loop\_product\_title() it echos the below title:
```
<h3><?php the_title(); ?></h3>
```
In order to change the title with a hook, you'd need to change the above line to this, but you can't do this without changing the wc-template-functions.php file. So what you can do is comment out the action in the content-product.php file:
```
//do_action( 'woocommerce_shop_loop_item_title' );
```
and then add the below line:
```
?><h3><?php echo apply_filters( 'my_filter_name', get_the_title() ); ?></h3><?php
```
so the saved version looks like this:
```
//do_action( 'woocommerce_shop_loop_item_title' );
?><h3><?php echo apply_filters( 'my_filter_name', get_the_title() ); ?></h3><?php
```
Then, you would need to add the following to your theme's functions.php file which will pass the contents of get\_the\_title() to the $title parameter, which you can then change any way you wish, but in the below case will change every title to say "Custom Title":
```
add_filter( 'my_filter_name', 'my_custom_function' );
function my_custom_function( $title ) {
return 'Custom Title';
}
```
For more information, see the following:
<http://codex.wordpress.org/Function_Reference/apply_filters>
<http://codex.wordpress.org/Function_Reference/add_filter>
|
198,461 |
<p>I created a WordPress plugin using OOP. If the plugin hasn't been activated and a method is called in a theme file, it throws the PHP fatal error "call to undefined function".</p>
<p>What is the correct way of doing this in the event the plugin hasn't been enabled?</p>
<p>Should a check be made in every file where it's used within the theme directory to see if the class exists? Or should the error just be left as is and the user will know they have to enable the plugin based on the function name?</p>
<p>Here's what I would like to do:</p>
<pre><code>if ( mypluginname_is_event_active() ) {
echo 'it is!';
}
</code></pre>
<p>However, the code above triggers the PHP fatal error if the plugin hasn't been activated.</p>
<p>The code below prevents the error from appearing, but it seems really clunky. Especially if it has to be done in every file where it's used under themes:</p>
<pre><code>// begin top of file
$is_event_live = false;
if ( class_exists( 'MyPluginName' ) ) {
$is_event_live = mypluginname_is_event_active();
}
// end top of file
if ( $is_event_live ) {
echo 'it is!';
}
</code></pre>
|
[
{
"answer_id": 198449,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>in WordPress, you cannot just \"overwrite\" a hook (that's works only for pluggable functions)</p>\n\n<p>but, you can add new fonction to the same hook and remove an action.</p>\n\n<p>try something like this : </p>\n\n<pre><code>add_action(\"init\", function () {\n // removing the woocommerce hook\n remove_action('woocommerce_shop_loop_item_title', 'change_product_title');\n});\n\n// add a new fonction to the hook\nadd_action(\"woocommerce_shop_loop_item_title\", function () {\n\n echo \"my new action\";\n\n});\n</code></pre>\n"
},
{
"answer_id": 198472,
"author": "Chris",
"author_id": 77693,
"author_profile": "https://wordpress.stackexchange.com/users/77693",
"pm_score": 4,
"selected": true,
"text": "<p>It's actually pretty simple to change the title in content-product.php, but you won't be able to do it with a hook. Near the top of the file, you should see this line:</p>\n\n<pre><code>Override this template by copying it to yourtheme/woocommerce/content-product.php\n</code></pre>\n\n<p>All you have to do is copy the file to the above directory, replacing \"yourtheme\" with your theme's actual folder name, and make your desired edits to the new file.</p>\n\n<p><strong>A little more background on hooks</strong></p>\n\n<p>The title in the default content-product.php template file is outputted like this, which is defined in wc-template-functions.php if you search for woocommerce_template_loop_product_title() it echos the below title:</p>\n\n<pre><code><h3><?php the_title(); ?></h3>\n</code></pre>\n\n<p>In order to change the title with a hook, you'd need to change the above line to this, but you can't do this without changing the wc-template-functions.php file. So what you can do is comment out the action in the content-product.php file:</p>\n\n<pre><code>//do_action( 'woocommerce_shop_loop_item_title' );\n</code></pre>\n\n<p>and then add the below line:</p>\n\n<pre><code>?><h3><?php echo apply_filters( 'my_filter_name', get_the_title() ); ?></h3><?php\n</code></pre>\n\n<p>so the saved version looks like this:</p>\n\n<pre><code>//do_action( 'woocommerce_shop_loop_item_title' );\n?><h3><?php echo apply_filters( 'my_filter_name', get_the_title() ); ?></h3><?php\n</code></pre>\n\n<p>Then, you would need to add the following to your theme's functions.php file which will pass the contents of get_the_title() to the $title parameter, which you can then change any way you wish, but in the below case will change every title to say \"Custom Title\":</p>\n\n<pre><code>add_filter( 'my_filter_name', 'my_custom_function' );\n\nfunction my_custom_function( $title ) {\n return 'Custom Title';\n}\n</code></pre>\n\n<p>For more information, see the following:</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/apply_filters\" rel=\"noreferrer\">http://codex.wordpress.org/Function_Reference/apply_filters</a></p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/add_filter\" rel=\"noreferrer\">http://codex.wordpress.org/Function_Reference/add_filter</a></p>\n"
}
] |
2015/08/12
|
[
"https://wordpress.stackexchange.com/questions/198461",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1462/"
] |
I created a WordPress plugin using OOP. If the plugin hasn't been activated and a method is called in a theme file, it throws the PHP fatal error "call to undefined function".
What is the correct way of doing this in the event the plugin hasn't been enabled?
Should a check be made in every file where it's used within the theme directory to see if the class exists? Or should the error just be left as is and the user will know they have to enable the plugin based on the function name?
Here's what I would like to do:
```
if ( mypluginname_is_event_active() ) {
echo 'it is!';
}
```
However, the code above triggers the PHP fatal error if the plugin hasn't been activated.
The code below prevents the error from appearing, but it seems really clunky. Especially if it has to be done in every file where it's used under themes:
```
// begin top of file
$is_event_live = false;
if ( class_exists( 'MyPluginName' ) ) {
$is_event_live = mypluginname_is_event_active();
}
// end top of file
if ( $is_event_live ) {
echo 'it is!';
}
```
|
It's actually pretty simple to change the title in content-product.php, but you won't be able to do it with a hook. Near the top of the file, you should see this line:
```
Override this template by copying it to yourtheme/woocommerce/content-product.php
```
All you have to do is copy the file to the above directory, replacing "yourtheme" with your theme's actual folder name, and make your desired edits to the new file.
**A little more background on hooks**
The title in the default content-product.php template file is outputted like this, which is defined in wc-template-functions.php if you search for woocommerce\_template\_loop\_product\_title() it echos the below title:
```
<h3><?php the_title(); ?></h3>
```
In order to change the title with a hook, you'd need to change the above line to this, but you can't do this without changing the wc-template-functions.php file. So what you can do is comment out the action in the content-product.php file:
```
//do_action( 'woocommerce_shop_loop_item_title' );
```
and then add the below line:
```
?><h3><?php echo apply_filters( 'my_filter_name', get_the_title() ); ?></h3><?php
```
so the saved version looks like this:
```
//do_action( 'woocommerce_shop_loop_item_title' );
?><h3><?php echo apply_filters( 'my_filter_name', get_the_title() ); ?></h3><?php
```
Then, you would need to add the following to your theme's functions.php file which will pass the contents of get\_the\_title() to the $title parameter, which you can then change any way you wish, but in the below case will change every title to say "Custom Title":
```
add_filter( 'my_filter_name', 'my_custom_function' );
function my_custom_function( $title ) {
return 'Custom Title';
}
```
For more information, see the following:
<http://codex.wordpress.org/Function_Reference/apply_filters>
<http://codex.wordpress.org/Function_Reference/add_filter>
|
198,500 |
<p>I've been trying around a lot to get this working, however every method I tried just didn't want to do as I wanted it to. So here I am.</p>
<p>I have a login-Mask that's only visible if the user is not logged in but it's permanently visible and covers some important areas. So here's my idea: hide it via toggle.</p>
<p>I know it's gonna take HTML, CSS and Javascript, so let's do this.</p>
<p>Here's a visual representation of where I'm at:
<a href="https://i.stack.imgur.com/WtGk6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WtGk6.jpg" alt="the framework"></a></p>
<p>Now I want the <strong>Login-Widget to only show AFTER you click the "Login" text</strong> up top.</p>
<ol>
<li>Div is hidden by default - CSS: display:none;</li>
<li>Text is <code><a></code>-Element with <code>href="#"</code></li>
</ol>
<p>So if you click the Text "Login", the Login-Mask appears and if you click it again, it disappears. Just normal toggle.</p>
<p>I guess the best idea is to use <code>div.toggleClass("open")</code> or something similar.</p>
<p><strong>Any help is appreciated!</strong></p>
<p><strong>edit01:</strong>
Here's my idea: functions.php</p>
<pre><code><script>
$( "a.toggle").click(function() {
$("div.log_forms").toggleClass( "open" );
});
</script>
</code></pre>
<p><strong>edit02:</strong></p>
<ol>
<li>jQuery is implemented as seen here
<a href="https://i.stack.imgur.com/uasY4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uasY4.png" alt="jQuery, check"></a></li>
<li>The site is loading JavaScript as seen in the other lines in the head-section</li>
<li>The code is correct as I've had it work on another site before (tried both # and .)</li>
<li>Heck, the script even gets loaded, as seen here
<a href="https://i.stack.imgur.com/oNpwR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oNpwR.png" alt="script here"></a></li>
</ol>
|
[
{
"answer_id": 198595,
"author": "junkrig",
"author_id": 54989,
"author_profile": "https://wordpress.stackexchange.com/users/54989",
"pm_score": 0,
"selected": false,
"text": "<p>I think you are pretty much there. In your JavaScript you are referencing log_forms as a class, but in your HTML it looks like log_forms is an ID. So you would need:</p>\n\n<pre><code>$( \"a.toggle\").click(function() {\n $(\"#log_forms\").toggleClass( \"open\" );\n});\n</code></pre>\n\n<p>Then the css would be:</p>\n\n<pre><code>#log_forms{\n display: none;\n}\n\n#log_forms.open{\n display: block;\n}\n</code></pre>\n\n<p>Example: <a href=\"https://jsfiddle.net/diywordpress/nsdbvc4h/9/\" rel=\"nofollow\">http://jsfiddle.net/diywordpress/nsdbvc4h/9/</a></p>\n"
},
{
"answer_id": 198614,
"author": "webtoure",
"author_id": 72992,
"author_profile": "https://wordpress.stackexchange.com/users/72992",
"pm_score": 2,
"selected": true,
"text": "<p>You are calling jQuery wrong by the shorthand <code>$</code>. If you will look in your console you will see an error that <code>$</code> is not a function / undeclared etc (this is due to jQuery's conflict mode if I am not wrong).</p>\n\n<p>Your code should look something like this:</p>\n\n<pre><code><script type=\"text/javascript\">\njQuery(function($) {\n $( \"a.toggle\").click(function() {\n $(\"#log_forms\").toggleClass( \"open\" );\n });\n});\n</script>\n</code></pre>\n"
}
] |
2015/08/13
|
[
"https://wordpress.stackexchange.com/questions/198500",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63130/"
] |
I've been trying around a lot to get this working, however every method I tried just didn't want to do as I wanted it to. So here I am.
I have a login-Mask that's only visible if the user is not logged in but it's permanently visible and covers some important areas. So here's my idea: hide it via toggle.
I know it's gonna take HTML, CSS and Javascript, so let's do this.
Here's a visual representation of where I'm at:
[](https://i.stack.imgur.com/WtGk6.jpg)
Now I want the **Login-Widget to only show AFTER you click the "Login" text** up top.
1. Div is hidden by default - CSS: display:none;
2. Text is `<a>`-Element with `href="#"`
So if you click the Text "Login", the Login-Mask appears and if you click it again, it disappears. Just normal toggle.
I guess the best idea is to use `div.toggleClass("open")` or something similar.
**Any help is appreciated!**
**edit01:**
Here's my idea: functions.php
```
<script>
$( "a.toggle").click(function() {
$("div.log_forms").toggleClass( "open" );
});
</script>
```
**edit02:**
1. jQuery is implemented as seen here
[](https://i.stack.imgur.com/uasY4.png)
2. The site is loading JavaScript as seen in the other lines in the head-section
3. The code is correct as I've had it work on another site before (tried both # and .)
4. Heck, the script even gets loaded, as seen here
[](https://i.stack.imgur.com/oNpwR.png)
|
You are calling jQuery wrong by the shorthand `$`. If you will look in your console you will see an error that `$` is not a function / undeclared etc (this is due to jQuery's conflict mode if I am not wrong).
Your code should look something like this:
```
<script type="text/javascript">
jQuery(function($) {
$( "a.toggle").click(function() {
$("#log_forms").toggleClass( "open" );
});
});
</script>
```
|
198,502 |
<p>I'm trying to make a query for users using <code>WP_User_Query()</code>
I need to filter users by role <code>shop_manager</code> and custom taxonomy called <code>shop-category</code> and current taxonomy term ID.</p>
<p>The code I have so far:</p>
<pre><code><?php
// WP_User_Query arguments
$args = array (
'role' => 'shop_manager',
'order' => 'DESC',
'orderby' => 'user_registered',
'tax_query' => array(
array('taxonomy' =>
'shop-category',
'field' => 'id',
'terms' => $term_id ) )
);
// The User Query
$user_query = new WP_User_Query( $args );
// The User Loop
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
echo '<li><span>' . esc_html( $user->shop_name ) . '</span></li>';
}
} else {
// no users found
}
?>
</code></pre>
<p>To get term ID I was using this code</p>
<pre><code><?php $queried_object = get_queried_object();
$term_id = $queried_object->term_id;
echo 'ID = '. $term_id;?>
</code></pre>
<p>Now it's showing all users with <code>shop_manager</code> role. Looks like taxonomy doesn't work.</p>
|
[
{
"answer_id": 198510,
"author": "webtoure",
"author_id": 72992,
"author_profile": "https://wordpress.stackexchange.com/users/72992",
"pm_score": 2,
"selected": false,
"text": "<p>There is no <code>tax_query</code> parameter for the <code>WP_User_Query</code> class. Since you've tagged the question with <code>user-meta</code> I can only assume you store the <code>ID</code> (or even the term name itself?) of a particular <code>shop-category</code> term as a user meta entry.</p>\n\n<p>In this case you would need something like this:</p>\n\n<pre><code>// The 'WP_User_Query' arguments array\n$args = array(\n 'role' => 'shop_manager',\n 'order' => 'DESC',\n 'orderby' => 'user_registered',\n 'meta_key' => 'shop_name', // Is this the meta key you are using?\n 'meta_value' => 'the_term_name_or_term_id', // Based on however you store your meta data\n 'meta_compare' => '=',\n);\n</code></pre>\n"
},
{
"answer_id": 246148,
"author": "RafaSashi",
"author_id": 37412,
"author_profile": "https://wordpress.stackexchange.com/users/37412",
"pm_score": 3,
"selected": false,
"text": "<p>Apparently there is no core implementation of <code>'tax_query'</code> in <code>WP_User_Query</code> yet.</p>\n\n<p>Check the ticket here for more info --> <a href=\"https://core.trac.wordpress.org/ticket/31383\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/31383</a></p>\n\n<p>Nevertheless there is an alternative way using <code>get_objects_in_term</code></p>\n\n<pre><code>$taxonomy = 'shop-category';\n$users = get_objects_in_term( $term_id, $taxonomy ); \n\nif(!empty($users)){\n\n // WP_User_Query arguments\n $args = array (\n 'role' => 'shop_manager',\n 'order' => 'DESC',\n 'orderby' => 'user_registered',\n 'include' => $users\n );\n\n // The User Query\n $user_query = new WP_User_Query( $args );\n\n // The User Loop\n if ( ! empty( $user_query->results ) ) {\n foreach ( $user_query->results as $user ) {\n echo '<li><span>' . esc_html( $user->shop_name ) . '</span></li>';\n }\n } \n else {\n // no shop_manager found \n }\n}\nelse {\n // no users found\n}\n</code></pre>\n"
}
] |
2015/08/13
|
[
"https://wordpress.stackexchange.com/questions/198502",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77725/"
] |
I'm trying to make a query for users using `WP_User_Query()`
I need to filter users by role `shop_manager` and custom taxonomy called `shop-category` and current taxonomy term ID.
The code I have so far:
```
<?php
// WP_User_Query arguments
$args = array (
'role' => 'shop_manager',
'order' => 'DESC',
'orderby' => 'user_registered',
'tax_query' => array(
array('taxonomy' =>
'shop-category',
'field' => 'id',
'terms' => $term_id ) )
);
// The User Query
$user_query = new WP_User_Query( $args );
// The User Loop
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
echo '<li><span>' . esc_html( $user->shop_name ) . '</span></li>';
}
} else {
// no users found
}
?>
```
To get term ID I was using this code
```
<?php $queried_object = get_queried_object();
$term_id = $queried_object->term_id;
echo 'ID = '. $term_id;?>
```
Now it's showing all users with `shop_manager` role. Looks like taxonomy doesn't work.
|
Apparently there is no core implementation of `'tax_query'` in `WP_User_Query` yet.
Check the ticket here for more info --> <https://core.trac.wordpress.org/ticket/31383>
Nevertheless there is an alternative way using `get_objects_in_term`
```
$taxonomy = 'shop-category';
$users = get_objects_in_term( $term_id, $taxonomy );
if(!empty($users)){
// WP_User_Query arguments
$args = array (
'role' => 'shop_manager',
'order' => 'DESC',
'orderby' => 'user_registered',
'include' => $users
);
// The User Query
$user_query = new WP_User_Query( $args );
// The User Loop
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
echo '<li><span>' . esc_html( $user->shop_name ) . '</span></li>';
}
}
else {
// no shop_manager found
}
}
else {
// no users found
}
```
|
198,560 |
<p>I have a page called "News", and I have created a custom post type for news. In "News" page I need to show all news custom posts and they need to be clickable. "News" page url is <a href="http://example.com/media/lajmet" rel="nofollow">http://example.com/media/lajmet</a>. When I click on news it goes on url "<a href="http://example.com/news/article1" rel="nofollow">http://example.com/news/article1</a>". How to rewrite URL on custom post click to go in "<a href="http://example.com/media/lajmet/article1" rel="nofollow">http://example.com/media/lajmet/article1</a>" ? Also I am using polylang for languages.</p>
<p>This is how I have create custom post type for news:</p>
<pre><code>function news_custom_post() {
$labels = array(
'name' => _x( 'News', 'post type general name' ),
'singular_name' => _x( 'News', 'post type singular name' ),
'add_new' => _x( 'Add new', 'news' ),
'add_new_item' => __( 'Add new news' ),
'edit_item' => __( 'Edit news' ),
'new_item' => __( 'New news' ),
'all_items' => __( 'All news' ),
'view_item' => __( 'View news' ),
'search_items' => __( 'Search news' ),
'not_found' => __( 'No news found' ),
'not_found_in_trash' => __( 'No news found in the Trash' ),
'parent_item_colon' => '',
'menu_name' => 'News'
);
$args = array(
'labels' => $labels,
'description' => 'Holds our media news data',
'public' => true,
'menu_position' => 6,
'supports' => array( 'title', 'editor', 'page-attributes', 'thumbnail'),
'has_archive' => true
);
register_post_type( 'news', $args );
}
add_action( 'init', 'news_custom_post' );
</code></pre>
|
[
{
"answer_id": 198566,
"author": "Kevin Fodness",
"author_id": 77460,
"author_profile": "https://wordpress.stackexchange.com/users/77460",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it, but it's not straightforward. When you register a custom post type in WordPress, the first argument of <code>register_post_type</code> is the slug that you use. This slug can only be for one URL segment. If you changed it to <code>media</code> then all of your articles would take the form <code>/media/article-slug-here</code>.</p>\n\n<p>If you want to nest it deeper, you will have to register a rewrite rule to listen for the extra segment: <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow\">https://codex.wordpress.org/Rewrite_API/add_rewrite_rule</a></p>\n\n<p>Your add_rewrite_rule call would likely take a format similar to this:</p>\n\n<pre><code>add_rewrite_rule('^media/lajmet/(.*+)/?', 'index.php?post_type=news&p=$matches[1]', 'top');\n</code></pre>\n"
},
{
"answer_id": 198569,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>You can set the <code>rewrite</code> <code>slug</code> when you <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow\">register your post type</a>:</p>\n\n<pre><code>$args = array(\n 'rewrite' => array( 'slug' => 'media/lajmet' )\n // other args...\n);\n</code></pre>\n"
}
] |
2015/08/13
|
[
"https://wordpress.stackexchange.com/questions/198560",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44921/"
] |
I have a page called "News", and I have created a custom post type for news. In "News" page I need to show all news custom posts and they need to be clickable. "News" page url is <http://example.com/media/lajmet>. When I click on news it goes on url "<http://example.com/news/article1>". How to rewrite URL on custom post click to go in "<http://example.com/media/lajmet/article1>" ? Also I am using polylang for languages.
This is how I have create custom post type for news:
```
function news_custom_post() {
$labels = array(
'name' => _x( 'News', 'post type general name' ),
'singular_name' => _x( 'News', 'post type singular name' ),
'add_new' => _x( 'Add new', 'news' ),
'add_new_item' => __( 'Add new news' ),
'edit_item' => __( 'Edit news' ),
'new_item' => __( 'New news' ),
'all_items' => __( 'All news' ),
'view_item' => __( 'View news' ),
'search_items' => __( 'Search news' ),
'not_found' => __( 'No news found' ),
'not_found_in_trash' => __( 'No news found in the Trash' ),
'parent_item_colon' => '',
'menu_name' => 'News'
);
$args = array(
'labels' => $labels,
'description' => 'Holds our media news data',
'public' => true,
'menu_position' => 6,
'supports' => array( 'title', 'editor', 'page-attributes', 'thumbnail'),
'has_archive' => true
);
register_post_type( 'news', $args );
}
add_action( 'init', 'news_custom_post' );
```
|
You can set the `rewrite` `slug` when you [register your post type](https://codex.wordpress.org/Function_Reference/register_post_type):
```
$args = array(
'rewrite' => array( 'slug' => 'media/lajmet' )
// other args...
);
```
|
198,563 |
<p>I have a wierd problem.
If I inspect my WP pages using chrome element inspector I see two body tags thus:</p>
<pre><code><body cz-shortcut-listen="true">
<body>
</code></pre>
<p>This bit is to do with colorzilla (cz-shortcut-listen="true") in firebug it disappears. you have just 2 body tags with no classes.</p>
<p>The issue is not about the cz-shortcut-listen="true" bit coming from colorzilla. It is about the extra tag.</p>
<p>This duplication is causing styling and JS problems.
If I view source then just a single </p>
<pre><code><body>
</code></pre>
<p>is displayed with no classes.</p>
<p>No classes from body_class() are displayed in either view but I can echo them out into the source quite happily when they are not within this line in header.php </p>
<pre><code> <body <?php body_class();?>>
</code></pre>
<p>simply adding</p>
<pre><code><?php body_class();?>
</code></pre>
<p>above or below the line that renders the body tag displays all the body classes quite happily so they are being set.</p>
<p>If I comment out the line that renders the body tag in header.php using php commenting this body tag is still rendered </p>
<pre><code><body cz-shortcut-listen="true">
</code></pre>
<p>This happens with all themes and also to users outside of my local network and in chrome AND firefox so it seems not to be a theme or local browser issue. (See also UPDATE 2 below)</p>
<p>Has anyone any idea what it might be, it is a major headache and I'm quite stumped as to what it could be or how to even go about working out what the problem is.</p>
<p><strong>Staging site displaying the problem here:</strong>
<a href="http://eco.clearintent.co.uk/" rel="nofollow noreferrer">http://eco.clearintent.co.uk/</a></p>
<p><strong>UPDATE:</strong>
This is happening on every WP installation on the server so is not wp install or theme specific.</p>
<p>Running wordpress 4.2.4
Server is running Apache/2.2.29
PHP/5.3.29
Amazon Linux on an EC2 m3.medium instance.</p>
<p><strong>UPDATE 2:</strong>
Tried installing a vanilla wordpress on a new ec2 instance running apache 2.4 and php 5.6 just to see and it has the same issue!
Doesn't affect non-wordpress websites.
Happens across browsers and networks so not specific to my local setup.</p>
<p><strong>UPDATE 3</strong>:
Getting the site using wget from command line <strong>delivers the correct code WITH the body classes in the single body tag</strong>. - I wondered if (as suggested below) this indicated that javascript was to blame but when Iaccessed the site in chrome with javascript disabled the issue didn't resolve so that seems to mean javascript isn't the issue.</p>
<p><strong>UPDATE 4</strong>
As per the answer below the issue does lies in the strange character present in the body tag however, deleting and replacing this line doesn't work.
The only thing that seems to work is surrounding the first line in html comments and having an identical uncommented line below, thus:</p>
<pre><code><!--<body <?php body_class(); ?>>-->
<body <?php body_class(); ?>>-->
</code></pre>
<p>If I remove the top commented line then the error re-occurs on the newly typed body tag.<br>
If I remove the body tag from the commented line but still have an empty comment thus:</p>
<pre><code><!-- -->
<body <?php body_class(); ?>>-->
</code></pre>
<p>Or I include the body_class function in the comment thus:</p>
<pre><code><!--<?php body_class(); ?>-->
<body <?php body_class(); ?>>-->
</code></pre>
<p>The behaviour reappears so the first body tag (even though commented) has to be present for the new one to render properly.</p>
<p>I have checked the Apache and php utf-8 encodings are in place. I checked in the browser that the page was seen as utf8 which it is. On the server</p>
<pre><code> file -bi header.php
</code></pre>
<p>displays the file as ascii.</p>
<p>This gets wierder and wierder, I have a hack to get things working but not an understanding of what is happening.</p>
<p>Any thoughts on how to debug this would be very very gratefully received.</p>
<p>Thanks,</p>
<p>Paul</p>
<p>SOLUTION: see below. I added a separate answer for clarity. </p>
|
[
{
"answer_id": 198649,
"author": "Kevin Fodness",
"author_id": 77460,
"author_profile": "https://wordpress.stackexchange.com/users/77460",
"pm_score": 1,
"selected": true,
"text": "<p>I think this is the browser modifying the DOM due to a weird character you have in your body tag. When I view source in Firefox, I'm seeing the \"character not recognized\" box next to the body tag. This is also visible in Firefox inspector.</p>\n\n<p>Modern browsers automatically fix issues in your HTML for you when rendering the page. For example, if you have a <code><table></code> without a <code><tbody></code>, the browser will add the <code><tbody></code> section for you, even though it isn't in your markup. What I think is happening here is that the browser is seeing a tag that is <code><bodyX></code> where <code>X</code> is a bad unicode character, and it's not recognizing it as a body tag, so it wraps the remainder of the content in a proper body tag, causing the duplication. This explains why it is not visible in view source (because view source is the literal source, not the modified source, which is visible in the inspector) and wget would produce the same behavior.</p>\n\n<p>Try going into your theme's head file and deleting the body tag, then re-typing it, to remove any strange additional characters.</p>\n\n<p>If that doesn't work, it is possible that there is something on the server that is incorrectly modifying the content of the body tag on the way out.</p>\n"
},
{
"answer_id": 198793,
"author": "Tofuwarrior",
"author_id": 77748,
"author_profile": "https://wordpress.stackexchange.com/users/77748",
"pm_score": 0,
"selected": false,
"text": "<p>I have posted an answer so this is more concise but have marked the helpful answer as accepted.</p>\n\n<p>The initial issue was as @Kevin Fodness pointed out, the browser failing to see the <code><body</code> tag as a body tag because of the strange 'character' inside it.</p>\n\n<p>The strange character in the <code><body</code> tag made me think. I had already investigated an exploit but had seen no exploited code BUT when I scanned with wordfence it identified some files as exploited. When I opened these - no exploited code visible.\nHmmmm.\nUNTIL</p>\n\n<p>I opened them in vi.\nThen a massive chunk of exploit was visible.</p>\n\n<p>I'm guessing that the behaviour above (UPDATE 4) was because the exploit didn't detect that I had surrounded the first <code><body></code> tag in <code><!-- --></code> and so rendered it's nasty payload leaving my second <code><body></code> intact. Naturally, if I deleted the first then the first <code><body</code> tag it detected was my new one so it dumped its filth in there.</p>\n\n<p>Now that I have cleaned this exploit from all of the wp sites, the <code><body></code> renders fine. </p>\n\n<p>What appeared to be a single character narfing the <code><body></code> was in fact a whole chunk of obfuscated code.\nI'm just very lucky I thought to use vi to open the file else I doubt I would have worked this out; I had no idea code could be obfuscated from nano in this way. Lesson - don't shy away from vi!</p>\n"
},
{
"answer_id": 296258,
"author": "Aaron Joseph",
"author_id": 138269,
"author_profile": "https://wordpress.stackexchange.com/users/138269",
"pm_score": -1,
"selected": false,
"text": "<p>I was having the same issue.</p>\n\n<p>I had</p>\n\n<p><code><body <?php body_class(); ?>></code></p>\n\n<p>with a space between \"body\" and the opening php tag. Removing the space fixed the issue:</p>\n\n<p><code><body<?php body_class(); ?>></code></p>\n"
}
] |
2015/08/13
|
[
"https://wordpress.stackexchange.com/questions/198563",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77748/"
] |
I have a wierd problem.
If I inspect my WP pages using chrome element inspector I see two body tags thus:
```
<body cz-shortcut-listen="true">
<body>
```
This bit is to do with colorzilla (cz-shortcut-listen="true") in firebug it disappears. you have just 2 body tags with no classes.
The issue is not about the cz-shortcut-listen="true" bit coming from colorzilla. It is about the extra tag.
This duplication is causing styling and JS problems.
If I view source then just a single
```
<body>
```
is displayed with no classes.
No classes from body\_class() are displayed in either view but I can echo them out into the source quite happily when they are not within this line in header.php
```
<body <?php body_class();?>>
```
simply adding
```
<?php body_class();?>
```
above or below the line that renders the body tag displays all the body classes quite happily so they are being set.
If I comment out the line that renders the body tag in header.php using php commenting this body tag is still rendered
```
<body cz-shortcut-listen="true">
```
This happens with all themes and also to users outside of my local network and in chrome AND firefox so it seems not to be a theme or local browser issue. (See also UPDATE 2 below)
Has anyone any idea what it might be, it is a major headache and I'm quite stumped as to what it could be or how to even go about working out what the problem is.
**Staging site displaying the problem here:**
<http://eco.clearintent.co.uk/>
**UPDATE:**
This is happening on every WP installation on the server so is not wp install or theme specific.
Running wordpress 4.2.4
Server is running Apache/2.2.29
PHP/5.3.29
Amazon Linux on an EC2 m3.medium instance.
**UPDATE 2:**
Tried installing a vanilla wordpress on a new ec2 instance running apache 2.4 and php 5.6 just to see and it has the same issue!
Doesn't affect non-wordpress websites.
Happens across browsers and networks so not specific to my local setup.
**UPDATE 3**:
Getting the site using wget from command line **delivers the correct code WITH the body classes in the single body tag**. - I wondered if (as suggested below) this indicated that javascript was to blame but when Iaccessed the site in chrome with javascript disabled the issue didn't resolve so that seems to mean javascript isn't the issue.
**UPDATE 4**
As per the answer below the issue does lies in the strange character present in the body tag however, deleting and replacing this line doesn't work.
The only thing that seems to work is surrounding the first line in html comments and having an identical uncommented line below, thus:
```
<!--<body <?php body_class(); ?>>-->
<body <?php body_class(); ?>>-->
```
If I remove the top commented line then the error re-occurs on the newly typed body tag.
If I remove the body tag from the commented line but still have an empty comment thus:
```
<!-- -->
<body <?php body_class(); ?>>-->
```
Or I include the body\_class function in the comment thus:
```
<!--<?php body_class(); ?>-->
<body <?php body_class(); ?>>-->
```
The behaviour reappears so the first body tag (even though commented) has to be present for the new one to render properly.
I have checked the Apache and php utf-8 encodings are in place. I checked in the browser that the page was seen as utf8 which it is. On the server
```
file -bi header.php
```
displays the file as ascii.
This gets wierder and wierder, I have a hack to get things working but not an understanding of what is happening.
Any thoughts on how to debug this would be very very gratefully received.
Thanks,
Paul
SOLUTION: see below. I added a separate answer for clarity.
|
I think this is the browser modifying the DOM due to a weird character you have in your body tag. When I view source in Firefox, I'm seeing the "character not recognized" box next to the body tag. This is also visible in Firefox inspector.
Modern browsers automatically fix issues in your HTML for you when rendering the page. For example, if you have a `<table>` without a `<tbody>`, the browser will add the `<tbody>` section for you, even though it isn't in your markup. What I think is happening here is that the browser is seeing a tag that is `<bodyX>` where `X` is a bad unicode character, and it's not recognizing it as a body tag, so it wraps the remainder of the content in a proper body tag, causing the duplication. This explains why it is not visible in view source (because view source is the literal source, not the modified source, which is visible in the inspector) and wget would produce the same behavior.
Try going into your theme's head file and deleting the body tag, then re-typing it, to remove any strange additional characters.
If that doesn't work, it is possible that there is something on the server that is incorrectly modifying the content of the body tag on the way out.
|
198,598 |
<p>I am looking to echo the most recent post in the loop of content. Only 1 post.</p>
<p>Do I need to put some sort of parameter on the following code:</p>
<pre><code>if (have_posts()) :
while (have_posts()) :
the_post();
the_content();
endwhile;
endif;
</code></pre>
<p>How could I do this?</p>
|
[
{
"answer_id": 198649,
"author": "Kevin Fodness",
"author_id": 77460,
"author_profile": "https://wordpress.stackexchange.com/users/77460",
"pm_score": 1,
"selected": true,
"text": "<p>I think this is the browser modifying the DOM due to a weird character you have in your body tag. When I view source in Firefox, I'm seeing the \"character not recognized\" box next to the body tag. This is also visible in Firefox inspector.</p>\n\n<p>Modern browsers automatically fix issues in your HTML for you when rendering the page. For example, if you have a <code><table></code> without a <code><tbody></code>, the browser will add the <code><tbody></code> section for you, even though it isn't in your markup. What I think is happening here is that the browser is seeing a tag that is <code><bodyX></code> where <code>X</code> is a bad unicode character, and it's not recognizing it as a body tag, so it wraps the remainder of the content in a proper body tag, causing the duplication. This explains why it is not visible in view source (because view source is the literal source, not the modified source, which is visible in the inspector) and wget would produce the same behavior.</p>\n\n<p>Try going into your theme's head file and deleting the body tag, then re-typing it, to remove any strange additional characters.</p>\n\n<p>If that doesn't work, it is possible that there is something on the server that is incorrectly modifying the content of the body tag on the way out.</p>\n"
},
{
"answer_id": 198793,
"author": "Tofuwarrior",
"author_id": 77748,
"author_profile": "https://wordpress.stackexchange.com/users/77748",
"pm_score": 0,
"selected": false,
"text": "<p>I have posted an answer so this is more concise but have marked the helpful answer as accepted.</p>\n\n<p>The initial issue was as @Kevin Fodness pointed out, the browser failing to see the <code><body</code> tag as a body tag because of the strange 'character' inside it.</p>\n\n<p>The strange character in the <code><body</code> tag made me think. I had already investigated an exploit but had seen no exploited code BUT when I scanned with wordfence it identified some files as exploited. When I opened these - no exploited code visible.\nHmmmm.\nUNTIL</p>\n\n<p>I opened them in vi.\nThen a massive chunk of exploit was visible.</p>\n\n<p>I'm guessing that the behaviour above (UPDATE 4) was because the exploit didn't detect that I had surrounded the first <code><body></code> tag in <code><!-- --></code> and so rendered it's nasty payload leaving my second <code><body></code> intact. Naturally, if I deleted the first then the first <code><body</code> tag it detected was my new one so it dumped its filth in there.</p>\n\n<p>Now that I have cleaned this exploit from all of the wp sites, the <code><body></code> renders fine. </p>\n\n<p>What appeared to be a single character narfing the <code><body></code> was in fact a whole chunk of obfuscated code.\nI'm just very lucky I thought to use vi to open the file else I doubt I would have worked this out; I had no idea code could be obfuscated from nano in this way. Lesson - don't shy away from vi!</p>\n"
},
{
"answer_id": 296258,
"author": "Aaron Joseph",
"author_id": 138269,
"author_profile": "https://wordpress.stackexchange.com/users/138269",
"pm_score": -1,
"selected": false,
"text": "<p>I was having the same issue.</p>\n\n<p>I had</p>\n\n<p><code><body <?php body_class(); ?>></code></p>\n\n<p>with a space between \"body\" and the opening php tag. Removing the space fixed the issue:</p>\n\n<p><code><body<?php body_class(); ?>></code></p>\n"
}
] |
2015/08/14
|
[
"https://wordpress.stackexchange.com/questions/198598",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58657/"
] |
I am looking to echo the most recent post in the loop of content. Only 1 post.
Do I need to put some sort of parameter on the following code:
```
if (have_posts()) :
while (have_posts()) :
the_post();
the_content();
endwhile;
endif;
```
How could I do this?
|
I think this is the browser modifying the DOM due to a weird character you have in your body tag. When I view source in Firefox, I'm seeing the "character not recognized" box next to the body tag. This is also visible in Firefox inspector.
Modern browsers automatically fix issues in your HTML for you when rendering the page. For example, if you have a `<table>` without a `<tbody>`, the browser will add the `<tbody>` section for you, even though it isn't in your markup. What I think is happening here is that the browser is seeing a tag that is `<bodyX>` where `X` is a bad unicode character, and it's not recognizing it as a body tag, so it wraps the remainder of the content in a proper body tag, causing the duplication. This explains why it is not visible in view source (because view source is the literal source, not the modified source, which is visible in the inspector) and wget would produce the same behavior.
Try going into your theme's head file and deleting the body tag, then re-typing it, to remove any strange additional characters.
If that doesn't work, it is possible that there is something on the server that is incorrectly modifying the content of the body tag on the way out.
|
198,601 |
<p>Is there any way to style the message delivered by wp_debug?</p>
<p>Whenever I set WP_Debug to true, it pushes all my content down the page. While I admit it's easy to just set it back to false after using it, it can be somewhat tedious switching it on and off when it's needed.</p>
<p>Is there a way to style the message it creates, so that I'm then able to prevent it from moving content around?</p>
<p>I imagine I'd do something like this:</p>
<pre><code>#error
{
position: fixed;
top: 0px;
width: 100%;
z-index: 2;
}
</code></pre>
<p>etc.</p>
|
[
{
"answer_id": 198604,
"author": "Charles",
"author_id": 15605,
"author_profile": "https://wordpress.stackexchange.com/users/15605",
"pm_score": 2,
"selected": false,
"text": "<p>You could add following code (if not done already) in <code>wp-config.php</code> (please make a backup first of this file):<br /></p>\n\n<pre><code>define('WP_DEBUG', true);\ndefine( 'WP_DEBUG_LOG', true );\ndefine( 'WP_DEBUG_DISPLAY', false );\n</code></pre>\n\n<p>This way <code>debug</code> is activated but the results (if have errors/notices) will not be shown but will be saved in a <code>logfile</code> which you can find then in <code>wp-content</code> folder. THe file which 'collects' all is <code>debug.log</code>.</p>\n\n<blockquote>\n <p>See the <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow\">Codex</a> for further explanations</p>\n</blockquote>\n\n<p><em>Side note: (I know I should not do it but...) you also can look for a plugin (as addon to make it yourself easier during your work) named <code>debug-bar</code> and or others.</em></p>\n"
},
{
"answer_id": 198605,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 1,
"selected": false,
"text": "<p>Reference : <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow\">Debugging in wordpress</a></p>\n\n<p>If you are looking for style these debug message then you should have these class for style. Set style as you wish by class that you need.</p>\n\n<p>And if you don't want show these wording but continue debug then you need to use WP_DEBUG_LOG and WP_DEBUG_DISPLAY. Below point that you need to perform to achieve debug log file.</p>\n\n<blockquote>\n <ol>\n <li>Enable WP_DEBUG mode</li>\n <li>Enable Debug logging to the /wp-content/debug.log file</li>\n <li>Disable display of errors and warnings</li>\n </ol>\n</blockquote>\n\n<p>WP_DEBUG_LOG is a companion to WP_DEBUG that causes all errors to also be saved to a debug.log log file inside the /wp-content/ directory. This is useful if you want to review all notices later or need to view notices generated off-screen.</p>\n\n<pre><code>define('WP_DEBUG_LOG', true);\n</code></pre>\n\n<p>WP_DEBUG_LOG to do anything, WP_DEBUG must be enabled (true). Remember you can turn off WP_DEBUG_DISPLAY independently. </p>\n\n<p>WP_DEBUG_DISPLAY is another companion to WP_DEBUG that controls whether debug messages are shown inside the HTML of pages or not.</p>\n\n<pre><code>define('WP_DEBUG_DISPLAY', false);\n</code></pre>\n\n<p>WP_DEBUG_DISPLAY to do anything, WP_DEBUG must be enabled (true). Remember you can control WP_DEBUG_LOG independently.</p>\n\n<p>Finally your wp-config.php file have below lines for above solution.</p>\n\n<pre><code>define('WP_DEBUG', true);//Enable WP_DEBUG mode\ndefine( 'WP_DEBUG_LOG', true );//Enable Debug logging to the /wp-content/debug.log file\ndefine( 'WP_DEBUG_DISPLAY', false );//Disable display of errors and warnings\n</code></pre>\n\n<p>Let me know if you have any query regarding this.</p>\n"
}
] |
2015/08/14
|
[
"https://wordpress.stackexchange.com/questions/198601",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64387/"
] |
Is there any way to style the message delivered by wp\_debug?
Whenever I set WP\_Debug to true, it pushes all my content down the page. While I admit it's easy to just set it back to false after using it, it can be somewhat tedious switching it on and off when it's needed.
Is there a way to style the message it creates, so that I'm then able to prevent it from moving content around?
I imagine I'd do something like this:
```
#error
{
position: fixed;
top: 0px;
width: 100%;
z-index: 2;
}
```
etc.
|
You could add following code (if not done already) in `wp-config.php` (please make a backup first of this file):
```
define('WP_DEBUG', true);
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
```
This way `debug` is activated but the results (if have errors/notices) will not be shown but will be saved in a `logfile` which you can find then in `wp-content` folder. THe file which 'collects' all is `debug.log`.
>
> See the [Codex](https://codex.wordpress.org/Debugging_in_WordPress) for further explanations
>
>
>
*Side note: (I know I should not do it but...) you also can look for a plugin (as addon to make it yourself easier during your work) named `debug-bar` and or others.*
|
198,610 |
<p>I have a custom post type (speaker) and I would like to load the list of speakers sorted by last name. I can't seem to figure it out. I tried the code from this post: <a href="https://stackoverflow.com/questions/16416217/wordpress-orderby-last-word-in-title">https://stackoverflow.com/questions/16416217/wordpress-orderby-last-word-in-title</a></p>
<p>but it didn't seem to work.</p>
<pre><code>add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'event',
array(
'labels' => array(
'name' => __( 'Conferences' ),
'singular_name' => __( 'Conference' )
),
'public' => true,
'has_archive' => true,
'supports' => array('title','editor','thumbnail'),
)
);
register_post_type( 'speaker',
array(
'labels' => array(
'name' => __( 'Speakers' ),
'singular_name' => __( 'Speaker' )
),
'public' => true,
'has_archive' => true,
'supports' => array('title','editor','thumbnail'),
)
);
register_post_type( 'sponsor',
array(
'labels' => array(
'name' => __( 'Sponsors' ),
'singular_name' => __( 'Sponsor' )
),
'public' => true,
'has_archive' => true,
'supports' => array('title','editor','thumbnail'),
)
);
register_post_type( 'venue',
array(
'labels' => array(
'name' => __( 'Venues' ),
'singular_name' => __( 'Venue' )
),
'public' => true,
'has_archive' => true,
'supports' => array('title','editor','thumbnail'),
)
);
register_post_type( 'session',
array(
'labels' => array(
'name' => __( 'Sessions' ),
'singular_name' => __( 'Session' )
),
'public' => true,
'has_archive' => true,
'supports' => array('title','editor','thumbnail'),
)
);
}
</code></pre>
<p>The code i'm calling the custom post type is:</p>
<pre><code><?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'speaker',
'meta_key' => 'speaker-front-page',
'meta_value' => '1',
'orderby' => 'speaker_last_name',
'order' => 'ASC'
);
// query
add_filter( 'posts_orderby' , 'posts_orderby_lastname' );
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?> <div id="speakerrow"><h1>SPEAKERS<h1><hr>
<?php while( $the_query->have_posts() ) : $the_query->the_post();
echo '<div class="flex_column av_one_third flex_column_div">';
echo do_shortcode("[av_image src='". get_field('speaker-photo')."' attachment='' attachment_size='full' align='center' animation='pop-up' styling='' hover='av-hover-grow' link='".get_the_permalink()."' target='' caption='' font_size='' appearance='' overlay_opacity='0.4' overlay_color='#000000' overlay_text_color='#ffffff'][/av_image]" );
echo do_shortcode("[av_heading tag='h2' padding='10' heading='". get_the_title()."' color='' style='blockquote modern-quote modern-centered' subheading_active='subheading_below' subheading_size='15']". get_field('speaker-company')."[/av_heading]");
echo '</div>';
?>
</code></pre>
<p>the best i could think was to add a custom metafield called last name and am sorting by that, I like not having to type the speakers last name 2 times if possible.</p>
<p>how do i add the order by field to sort by the 2nd (and last) word in the post title?</p>
|
[
{
"answer_id": 198624,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<h2>Order by the last word in the post title</h2>\n\n<p>To order by the <em>speaker's last name</em>, you can use the following setup (PHP 5.4+):</p>\n\n<pre><code>// args \n$args = [\n 'posts_per_page' => 10,\n 'post_type' => 'speaker',\n 'meta_key' => 'speaker-front-page',\n 'meta_value' => '1',\n 'orderby' => 'wpse_last_word', //<-- Our custom ordering!\n 'order' => 'ASC'\n];\n\n// query\n$the_query = new WP_Query( $args );\n</code></pre>\n\n<p>where the <code>'wpse_last_word'</code> input is supported by the following:</p>\n\n<pre><code>/**\n * Order posts by the last word in the post_title. \n * Activated when orderby is 'wpse_last_word' \n * @link https://wordpress.stackexchange.com/a/198624/26350\n */\nadd_filter( 'posts_orderby', function( $orderby, \\WP_Query $q )\n{\n if( 'wpse_last_word' === $q->get( 'orderby' ) && $get_order = $q->get( 'order' ) )\n {\n if( in_array( strtoupper( $get_order ), ['ASC', 'DESC'] ) )\n {\n global $wpdb;\n $orderby = \" SUBSTRING_INDEX( {$wpdb->posts}.post_title, ' ', -1 ) \" . $get_order;\n }\n }\n return $orderby;\n}, PHP_INT_MAX, 2 );\n</code></pre>\n\n<p>This is based on <a href=\"https://wordpress.stackexchange.com/questions/195034/taxonomy-terms-sort-by-last-name/195039#195039\">my answer here</a> on ordering terms by the last word.</p>\n"
},
{
"answer_id": 267057,
"author": "Dalin",
"author_id": 119794,
"author_profile": "https://wordpress.stackexchange.com/users/119794",
"pm_score": 2,
"selected": false,
"text": "<p>The accepted answer is pretty brittle and won't be able to handle the many variations of the <a href=\"https://codex.wordpress.org/Function_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">order by parameters</a>.</p>\n\n<p>Here's a filter that should be a little more robust:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Order posts by the last word in the post_title.\n * Activated when orderby is 'wpse_last_word'\n * @link http://wordpress.stackexchange.com/a/198624/26350\n */\nadd_filter('posts_orderby', function($orderby_sql, \\WP_Query $q) {\n $orderbys = $q->get('orderby');\n if (!$orderbys) {\n return;\n }\n if ($orderby_sql) {\n $orderby_sql_array = [$orderby_sql];\n }\n else {\n $orderby_sql_array = [];\n }\n if (!is_array($orderbys)) {\n $words = explode(' ', $orderbys);\n $orderbys = [];\n foreach ($words as $word) {\n $orderbys[$word] = $q->get('order');\n }\n }\n global $wpdb;\n foreach ($orderbys as $orderby => $direction) {\n if ($orderby == 'wpse_last_word') {\n if (!$direction || !in_array(strtoupper($direction), ['ASC', 'DESC'])) {\n $direction = 'DESC';\n }\n $orderby_sql_array[] = \"SUBSTRING_INDEX({$wpdb->posts}.post_title, ' ', -1) $direction\";\n }\n }\n return implode(', ', $orderby_sql_array);\n}, 100, 2);\n</code></pre>\n\n<p>The basic usage is (but it will accept more complex variations of the <a href=\"https://codex.wordpress.org/Function_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">order by parameters</a>):</p>\n\n<pre><code>$args = [\n 'posts_per_page' => 10,\n 'post_type' => 'speaker',\n 'meta_key' => 'speaker-front-page',\n 'meta_value' => '1',\n 'orderby' => 'wpse_last_word',\n 'order' => 'ASC'\n];\n\n$the_query = new WP_Query( $args );\n</code></pre>\n"
},
{
"answer_id": 385932,
"author": "Jaska",
"author_id": 199175,
"author_profile": "https://wordpress.stackexchange.com/users/199175",
"pm_score": 1,
"selected": false,
"text": "<p>The accepted answer worked fine except it messed up the ordering of Scandic (finnish / swedish…) characters. The letters Å Ä Ö should be at the end.</p>\n<p>Here's how it works with Scandic alphabet.</p>\n<pre><code>add_filter( 'posts_orderby',\n function( $orderby, \\WP_Query $q )\n {\n if ( 'wpse_last_word' === $q->get( 'orderby' ) ) {\n $get_order = $q->get( 'order' );\n if ( in_array( strtoupper( $get_order ), [ 'ASC', 'DESC' ], true ) ) {\n global $wpdb;\n $orderby = " SUBSTRING_INDEX( {$wpdb->posts}.post_title, ' ', -1 ) COLLATE utf8mb4_swedish_ci " . $get_order . ", SUBSTRING_INDEX( {$wpdb->posts}.post_title, ' ', 1 ) COLLATE utf8mb4_swedish_ci " . $get_order . ';';\n }\n }\n return $orderby;\n },\n PHP_INT_MAX,\n2 );\n</code></pre>\n"
}
] |
2015/08/14
|
[
"https://wordpress.stackexchange.com/questions/198610",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77767/"
] |
I have a custom post type (speaker) and I would like to load the list of speakers sorted by last name. I can't seem to figure it out. I tried the code from this post: <https://stackoverflow.com/questions/16416217/wordpress-orderby-last-word-in-title>
but it didn't seem to work.
```
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'event',
array(
'labels' => array(
'name' => __( 'Conferences' ),
'singular_name' => __( 'Conference' )
),
'public' => true,
'has_archive' => true,
'supports' => array('title','editor','thumbnail'),
)
);
register_post_type( 'speaker',
array(
'labels' => array(
'name' => __( 'Speakers' ),
'singular_name' => __( 'Speaker' )
),
'public' => true,
'has_archive' => true,
'supports' => array('title','editor','thumbnail'),
)
);
register_post_type( 'sponsor',
array(
'labels' => array(
'name' => __( 'Sponsors' ),
'singular_name' => __( 'Sponsor' )
),
'public' => true,
'has_archive' => true,
'supports' => array('title','editor','thumbnail'),
)
);
register_post_type( 'venue',
array(
'labels' => array(
'name' => __( 'Venues' ),
'singular_name' => __( 'Venue' )
),
'public' => true,
'has_archive' => true,
'supports' => array('title','editor','thumbnail'),
)
);
register_post_type( 'session',
array(
'labels' => array(
'name' => __( 'Sessions' ),
'singular_name' => __( 'Session' )
),
'public' => true,
'has_archive' => true,
'supports' => array('title','editor','thumbnail'),
)
);
}
```
The code i'm calling the custom post type is:
```
<?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'speaker',
'meta_key' => 'speaker-front-page',
'meta_value' => '1',
'orderby' => 'speaker_last_name',
'order' => 'ASC'
);
// query
add_filter( 'posts_orderby' , 'posts_orderby_lastname' );
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?> <div id="speakerrow"><h1>SPEAKERS<h1><hr>
<?php while( $the_query->have_posts() ) : $the_query->the_post();
echo '<div class="flex_column av_one_third flex_column_div">';
echo do_shortcode("[av_image src='". get_field('speaker-photo')."' attachment='' attachment_size='full' align='center' animation='pop-up' styling='' hover='av-hover-grow' link='".get_the_permalink()."' target='' caption='' font_size='' appearance='' overlay_opacity='0.4' overlay_color='#000000' overlay_text_color='#ffffff'][/av_image]" );
echo do_shortcode("[av_heading tag='h2' padding='10' heading='". get_the_title()."' color='' style='blockquote modern-quote modern-centered' subheading_active='subheading_below' subheading_size='15']". get_field('speaker-company')."[/av_heading]");
echo '</div>';
?>
```
the best i could think was to add a custom metafield called last name and am sorting by that, I like not having to type the speakers last name 2 times if possible.
how do i add the order by field to sort by the 2nd (and last) word in the post title?
|
Order by the last word in the post title
----------------------------------------
To order by the *speaker's last name*, you can use the following setup (PHP 5.4+):
```
// args
$args = [
'posts_per_page' => 10,
'post_type' => 'speaker',
'meta_key' => 'speaker-front-page',
'meta_value' => '1',
'orderby' => 'wpse_last_word', //<-- Our custom ordering!
'order' => 'ASC'
];
// query
$the_query = new WP_Query( $args );
```
where the `'wpse_last_word'` input is supported by the following:
```
/**
* Order posts by the last word in the post_title.
* Activated when orderby is 'wpse_last_word'
* @link https://wordpress.stackexchange.com/a/198624/26350
*/
add_filter( 'posts_orderby', function( $orderby, \WP_Query $q )
{
if( 'wpse_last_word' === $q->get( 'orderby' ) && $get_order = $q->get( 'order' ) )
{
if( in_array( strtoupper( $get_order ), ['ASC', 'DESC'] ) )
{
global $wpdb;
$orderby = " SUBSTRING_INDEX( {$wpdb->posts}.post_title, ' ', -1 ) " . $get_order;
}
}
return $orderby;
}, PHP_INT_MAX, 2 );
```
This is based on [my answer here](https://wordpress.stackexchange.com/questions/195034/taxonomy-terms-sort-by-last-name/195039#195039) on ordering terms by the last word.
|
198,620 |
<p>I tried to add arrow down when the menu has a sub-menus. But the down arrow not showing up. Please help me.</p>
<p>Here's the link: <a href="http://bit.ly/1UH4FlT" rel="nofollow">http://bit.ly/1UH4FlT</a></p>
<p>Currently using this script that I found somewhere.</p>
<pre><code>function add_menu_parent_class( $items ) {
$parents = array();
foreach ( $items as $item ) {
if ( $item->current_page_ancestor && $item-> current_page_ancestor> 0 ) {
$parents[] = $item->current_page_ancestor;
}
}
foreach ( $items as $item ) {
if ( in_array( $item->ID, $parents ) ) {
$item->classes[] = 'menu-item-has-children';
}
}
return $items;
}
add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );
</code></pre>
<p>And I added this css</p>
<pre><code>#site-navigation .menu > ul > li.menu-item-has-children > a:before {
color: #fff;
content: "\f107";
font-family:FontAwesome;
font-size: 10px;
vertical-align: 1px;
}
#site-navigation .menu > ul > li > li.menu-item-has-children > a:after {
color: #222;
content: ""\f105"";
font-family:FontAwesome;
font-size: 10px;
vertical-align: 1px;
}
</code></pre>
|
[
{
"answer_id": 198631,
"author": "vivek mengu",
"author_id": 77782,
"author_profile": "https://wordpress.stackexchange.com/users/77782",
"pm_score": 3,
"selected": true,
"text": "<p>Add below code</p>\n\n<pre><code>#site-navigation .menu > ul > li.menu-item-has-children > a::after {\ncontent: '\\f107';\nfont-family: FontAwesome;\nfont-size: 10px;\nmargin-left: 10px;\nvertical-align: 1px;\n}\n\n\n#site-navigation .menu > ul > li > ul > li.menu-item-has-children > a::after {\ncolor: rgb(34, 34, 34);\ncontent: '\\f105';\nfont-family: FontAwesome;\nfont-size: 10px;\nvertical-align: 1px;\nfloat: right;\n}\n</code></pre>\n\n<p>Add 3rd level navigation.\nIf you face any issues, reply.</p>\n"
},
{
"answer_id": 198646,
"author": "user1903471",
"author_id": 71602,
"author_profile": "https://wordpress.stackexchange.com/users/71602",
"pm_score": 1,
"selected": false,
"text": "<p>You Add Two time (\"\") Quote in you css see below</p>\n\n<p>Replace </p>\n\n<p>content: \"\"\\f105\"\";</p>\n\n<p>To</p>\n\n<p>content: \"\\f105\";</p>\n\n<p>And Check Again</p>\n"
},
{
"answer_id": 198679,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>you can add a arrow next to the menu label with the free plugin \"Menu Icons\".\ngo in \"extensions\" -> \"add new\" and search \"Menu Icons\"</p>\n\n<p>after activating this plugin, go to the menu editor and at each menu element you can choose a icon</p>\n"
}
] |
2015/08/14
|
[
"https://wordpress.stackexchange.com/questions/198620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62417/"
] |
I tried to add arrow down when the menu has a sub-menus. But the down arrow not showing up. Please help me.
Here's the link: <http://bit.ly/1UH4FlT>
Currently using this script that I found somewhere.
```
function add_menu_parent_class( $items ) {
$parents = array();
foreach ( $items as $item ) {
if ( $item->current_page_ancestor && $item-> current_page_ancestor> 0 ) {
$parents[] = $item->current_page_ancestor;
}
}
foreach ( $items as $item ) {
if ( in_array( $item->ID, $parents ) ) {
$item->classes[] = 'menu-item-has-children';
}
}
return $items;
}
add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );
```
And I added this css
```
#site-navigation .menu > ul > li.menu-item-has-children > a:before {
color: #fff;
content: "\f107";
font-family:FontAwesome;
font-size: 10px;
vertical-align: 1px;
}
#site-navigation .menu > ul > li > li.menu-item-has-children > a:after {
color: #222;
content: ""\f105"";
font-family:FontAwesome;
font-size: 10px;
vertical-align: 1px;
}
```
|
Add below code
```
#site-navigation .menu > ul > li.menu-item-has-children > a::after {
content: '\f107';
font-family: FontAwesome;
font-size: 10px;
margin-left: 10px;
vertical-align: 1px;
}
#site-navigation .menu > ul > li > ul > li.menu-item-has-children > a::after {
color: rgb(34, 34, 34);
content: '\f105';
font-family: FontAwesome;
font-size: 10px;
vertical-align: 1px;
float: right;
}
```
Add 3rd level navigation.
If you face any issues, reply.
|
198,634 |
<p>I have a very simple WordPress plugin that shows a menu/admin page. The page contains Glyphicons - Font Awesome.</p>
<p>These glyphicons are never showing. I cannot figure out why because I know the font-awesome css file is being loaded correctly and I know that the admin pages HTML works fine outside of a wordpress plugin and shows the Glyphs.</p>
<p>What could possibly be going wrong?</p>
<pre><code><?php
/**
* Plugin Name: TEST Use FA Icons
* Plugin URI:
* Description: Test Development Plugin
* Version: 1.0.0
* Author:
* Author URI:
* License: GPL2
*/
class TEST_Use_FA_Icons_Admin
{
public function __construct() {
add_action('admin_menu', array($this, 'admin_menu'));
}
public function admin_menu() {
wp_enqueue_style( "font-awesome", plugin_dir_url( __FILE__ ) . 'css/font-awesome.min.css', array(), false, 'all' );
add_menu_page('TEST_DEV', 'TEST_DEV', 'administrator', 'TEST_DEV_SLUG',
array($this, 'show_TEST_page'),
plugins_url('images/help.png', __FILE__));
}
public function show_TEST_page() {
?>
<div class="wrap">
<div class="container">
<div class="col-md-12">
<h1>Test</h1>
<i class="fa fa-camera-retro fa-lg"></i> fa-lg
<i class="fa fa-camera-retro fa-2x"></i> fa-2x
<i class="fa fa-camera-retro fa-3x"></i> fa-3x
<i class="fa fa-camera-retro fa-4x"></i> fa-4x
<i class="fa fa-camera-retro fa-5x"></i> fa-5x
</div>
</div>
</div>
<?php
}
}
$test_TEST_Use_FA_Icons_Admin_admin = new TEST_Use_FA_Icons_Admin();
?>
</code></pre>
|
[
{
"answer_id": 198631,
"author": "vivek mengu",
"author_id": 77782,
"author_profile": "https://wordpress.stackexchange.com/users/77782",
"pm_score": 3,
"selected": true,
"text": "<p>Add below code</p>\n\n<pre><code>#site-navigation .menu > ul > li.menu-item-has-children > a::after {\ncontent: '\\f107';\nfont-family: FontAwesome;\nfont-size: 10px;\nmargin-left: 10px;\nvertical-align: 1px;\n}\n\n\n#site-navigation .menu > ul > li > ul > li.menu-item-has-children > a::after {\ncolor: rgb(34, 34, 34);\ncontent: '\\f105';\nfont-family: FontAwesome;\nfont-size: 10px;\nvertical-align: 1px;\nfloat: right;\n}\n</code></pre>\n\n<p>Add 3rd level navigation.\nIf you face any issues, reply.</p>\n"
},
{
"answer_id": 198646,
"author": "user1903471",
"author_id": 71602,
"author_profile": "https://wordpress.stackexchange.com/users/71602",
"pm_score": 1,
"selected": false,
"text": "<p>You Add Two time (\"\") Quote in you css see below</p>\n\n<p>Replace </p>\n\n<p>content: \"\"\\f105\"\";</p>\n\n<p>To</p>\n\n<p>content: \"\\f105\";</p>\n\n<p>And Check Again</p>\n"
},
{
"answer_id": 198679,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>you can add a arrow next to the menu label with the free plugin \"Menu Icons\".\ngo in \"extensions\" -> \"add new\" and search \"Menu Icons\"</p>\n\n<p>after activating this plugin, go to the menu editor and at each menu element you can choose a icon</p>\n"
}
] |
2015/08/14
|
[
"https://wordpress.stackexchange.com/questions/198634",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75260/"
] |
I have a very simple WordPress plugin that shows a menu/admin page. The page contains Glyphicons - Font Awesome.
These glyphicons are never showing. I cannot figure out why because I know the font-awesome css file is being loaded correctly and I know that the admin pages HTML works fine outside of a wordpress plugin and shows the Glyphs.
What could possibly be going wrong?
```
<?php
/**
* Plugin Name: TEST Use FA Icons
* Plugin URI:
* Description: Test Development Plugin
* Version: 1.0.0
* Author:
* Author URI:
* License: GPL2
*/
class TEST_Use_FA_Icons_Admin
{
public function __construct() {
add_action('admin_menu', array($this, 'admin_menu'));
}
public function admin_menu() {
wp_enqueue_style( "font-awesome", plugin_dir_url( __FILE__ ) . 'css/font-awesome.min.css', array(), false, 'all' );
add_menu_page('TEST_DEV', 'TEST_DEV', 'administrator', 'TEST_DEV_SLUG',
array($this, 'show_TEST_page'),
plugins_url('images/help.png', __FILE__));
}
public function show_TEST_page() {
?>
<div class="wrap">
<div class="container">
<div class="col-md-12">
<h1>Test</h1>
<i class="fa fa-camera-retro fa-lg"></i> fa-lg
<i class="fa fa-camera-retro fa-2x"></i> fa-2x
<i class="fa fa-camera-retro fa-3x"></i> fa-3x
<i class="fa fa-camera-retro fa-4x"></i> fa-4x
<i class="fa fa-camera-retro fa-5x"></i> fa-5x
</div>
</div>
</div>
<?php
}
}
$test_TEST_Use_FA_Icons_Admin_admin = new TEST_Use_FA_Icons_Admin();
?>
```
|
Add below code
```
#site-navigation .menu > ul > li.menu-item-has-children > a::after {
content: '\f107';
font-family: FontAwesome;
font-size: 10px;
margin-left: 10px;
vertical-align: 1px;
}
#site-navigation .menu > ul > li > ul > li.menu-item-has-children > a::after {
color: rgb(34, 34, 34);
content: '\f105';
font-family: FontAwesome;
font-size: 10px;
vertical-align: 1px;
float: right;
}
```
Add 3rd level navigation.
If you face any issues, reply.
|
198,655 |
<p>I'm having an issue with me rewrite rule works fine here:</p>
<p>example.com/resources/<br>
example.com/resources/articles/</p>
<p>but when i use pagination to the next page i get a 404 here:</p>
<p>example.com//resources/articles/page/2/<br>
example.com//resources/articles/page/3/<br>
example.com//resources/articles/page/4/</p>
<p>I was able to write two rewrite rules but now instead of getting a 404 page, the page refreshes with same content but URL changes here is my rewrite rules hopefully some one can help?</p>
<pre><code>add_rewrite_rule( 'resources/([^/]+)/([^/]+)/?', 'index.php?taxonomy=res_category&term=$matches[1]&post_type=$matches[2]', 'top');
//added for page turn on pagination
add_rewrite_rule('resources/([^/]+)/([^/]+)/page/([0-9]{1,})/?', 'index.php?taxonomy=res_category&term=$matches[1]&post_type=$matches[2]&paged=$matches[3]', 'top');
</code></pre>
<p>thank you ahead for any help.</p>
|
[
{
"answer_id": 198631,
"author": "vivek mengu",
"author_id": 77782,
"author_profile": "https://wordpress.stackexchange.com/users/77782",
"pm_score": 3,
"selected": true,
"text": "<p>Add below code</p>\n\n<pre><code>#site-navigation .menu > ul > li.menu-item-has-children > a::after {\ncontent: '\\f107';\nfont-family: FontAwesome;\nfont-size: 10px;\nmargin-left: 10px;\nvertical-align: 1px;\n}\n\n\n#site-navigation .menu > ul > li > ul > li.menu-item-has-children > a::after {\ncolor: rgb(34, 34, 34);\ncontent: '\\f105';\nfont-family: FontAwesome;\nfont-size: 10px;\nvertical-align: 1px;\nfloat: right;\n}\n</code></pre>\n\n<p>Add 3rd level navigation.\nIf you face any issues, reply.</p>\n"
},
{
"answer_id": 198646,
"author": "user1903471",
"author_id": 71602,
"author_profile": "https://wordpress.stackexchange.com/users/71602",
"pm_score": 1,
"selected": false,
"text": "<p>You Add Two time (\"\") Quote in you css see below</p>\n\n<p>Replace </p>\n\n<p>content: \"\"\\f105\"\";</p>\n\n<p>To</p>\n\n<p>content: \"\\f105\";</p>\n\n<p>And Check Again</p>\n"
},
{
"answer_id": 198679,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>you can add a arrow next to the menu label with the free plugin \"Menu Icons\".\ngo in \"extensions\" -> \"add new\" and search \"Menu Icons\"</p>\n\n<p>after activating this plugin, go to the menu editor and at each menu element you can choose a icon</p>\n"
}
] |
2015/08/14
|
[
"https://wordpress.stackexchange.com/questions/198655",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77788/"
] |
I'm having an issue with me rewrite rule works fine here:
example.com/resources/
example.com/resources/articles/
but when i use pagination to the next page i get a 404 here:
example.com//resources/articles/page/2/
example.com//resources/articles/page/3/
example.com//resources/articles/page/4/
I was able to write two rewrite rules but now instead of getting a 404 page, the page refreshes with same content but URL changes here is my rewrite rules hopefully some one can help?
```
add_rewrite_rule( 'resources/([^/]+)/([^/]+)/?', 'index.php?taxonomy=res_category&term=$matches[1]&post_type=$matches[2]', 'top');
//added for page turn on pagination
add_rewrite_rule('resources/([^/]+)/([^/]+)/page/([0-9]{1,})/?', 'index.php?taxonomy=res_category&term=$matches[1]&post_type=$matches[2]&paged=$matches[3]', 'top');
```
thank you ahead for any help.
|
Add below code
```
#site-navigation .menu > ul > li.menu-item-has-children > a::after {
content: '\f107';
font-family: FontAwesome;
font-size: 10px;
margin-left: 10px;
vertical-align: 1px;
}
#site-navigation .menu > ul > li > ul > li.menu-item-has-children > a::after {
color: rgb(34, 34, 34);
content: '\f105';
font-family: FontAwesome;
font-size: 10px;
vertical-align: 1px;
float: right;
}
```
Add 3rd level navigation.
If you face any issues, reply.
|
198,667 |
<p>I want to automate updating plugin options. There are some things that I repeat a lot.</p>
<p>With <a href="http://wp-cli.org">wp-cli</a> I know I can update simple options like this:</p>
<pre><code>php wp-cli.phar option update blog_public 1
</code></pre>
<p>However, some plugin options save their options in a serialized string. </p>
<p>Example of serialized option_value in wp_options:</p>
<pre><code>a:9:{s:4:"from";s:21:"[email protected]";s:8:"fromname";s:51:"xxx";s:4:"host";s:13:"smtp.xx.com";s:10:"smtpsecure";s:3:"ssl";s:4:"port";s:3:"465";s:8:"smtpauth";s:3:"yes";s:8:"username";s:21:"[email protected]";s:8:"password";s:13:"xxx";s:10:"deactivate";s:0:"";}
</code></pre>
<p>How to update those options?</p>
|
[
{
"answer_id": 198673,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://wp-cli.org/\" rel=\"nofollow\">WP-CLI</a> command <a href=\"http://wp-cli.org/commands/option/\" rel=\"nofollow\"><code>option</code></a> does use WordPress' <a href=\"https://codex.wordpress.org/Options_API\" rel=\"nofollow\">Options API</a> to do its job. Given, e.g. with the subcommand <a href=\"http://wp-cli.org/commands/option/update/\" rel=\"nofollow\"><code>update</code></a>, a correct input, an <code>array</code>, you should be able to do this with WP-CLI. You should make use of the <code>--format</code> parameter here, to make sure you get the same, <code>json</code> works generally fine for the <code>update</code> subcommand. Note, the subcommand <a href=\"http://wp-cli.org/commands/option/get/\" rel=\"nofollow\"><code>get</code></a> should return you the option unserialized, because the Options API is used, which you then can save, modify and/or transfer/set-up on other/new installations.</p>\n"
},
{
"answer_id": 199315,
"author": "lalo",
"author_id": 75628,
"author_profile": "https://wordpress.stackexchange.com/users/75628",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Solved it myself, this is how to do it:</strong></p>\n\n<p>If you want to programatically update serialized options:</p>\n\n<p>download wp-cli from wp-cli.org</p>\n\n<p>Find out what is the \"key\" for the options you are using. In this example the key is \"wp_smtp_options\" </p>\n\n<p>If you don't know the key, search in wp_options table and try to figure it out. </p>\n\n<p>Example: <code>select * from wp_options where option_name like '%smtp%'</code></p>\n\n<p>Now that you know your key, use this command to save your configuration to json file:</p>\n\n<pre><code>php wp-cli.phar option get wp_smtp_options --format=json > my_saved_config.txt\n</code></pre>\n\n<p>Whenever you want that configuration to be restored use this command</p>\n\n<pre><code>php wp-cli.phar option update wp_smtp_options --format=json < my_saved_config.txt\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>works in WAMPSERVER64</li>\n<li>works with unicode characters like ñ á é</li>\n<li>you can have your json file with paddings and spaces, for legibility</li>\n</ul>\n\n<p>It would be great not having to use an intermediate file for this purpose. Does anybody know how to do it?</p>\n"
},
{
"answer_id": 249914,
"author": "Laurent",
"author_id": 28715,
"author_profile": "https://wordpress.stackexchange.com/users/28715",
"pm_score": 3,
"selected": false,
"text": "<p>Here is how I do it in a bash script:</p>\n\n<pre><code>wp option get wp_smtp_options --format=json | php -r '\n$var = json_decode( fgets(STDIN) );\n$var->from = \"[email protected]\";\n$var->fromname = \"me\";\nprint json_encode($var);\n' | wp option set wp_smtp_options --format=json\n</code></pre>\n"
},
{
"answer_id": 287713,
"author": "Mike Andreasen",
"author_id": 132678,
"author_profile": "https://wordpress.stackexchange.com/users/132678",
"pm_score": 5,
"selected": false,
"text": "<p>WP-CLI is definitely the answer to this after the update to 1.4.0 which introduced the <a href=\"https://developer.wordpress.org/cli/commands/option/pluck/\" rel=\"noreferrer\">pluck</a> and <a href=\"https://developer.wordpress.org/cli/commands/option/patch/\" rel=\"noreferrer\">patch</a> commands for accessing serialized data in WordPress.</p>\n\n<p>The pluck command takes this format for grabbing serialized values</p>\n\n<pre><code>wp option pluck <key> <key-name>\n</code></pre>\n\n<p>For example in the active_plugins option you can grab first item</p>\n\n<pre><code>wp option pluck active_plugins 0\n</code></pre>\n\n<p>The patch command takes this format for inserting, updating or removing serialized values (the action)</p>\n\n<pre><code>wp option patch <action> <key> <key-name> <value>\n</code></pre>\n\n<p>Deleting the first active_plugin would look like this</p>\n\n<pre><code>wp option patch delete active_plugins 0\n</code></pre>\n\n<p>The same pluck and patch were also added for other commands like postmeta, you can now use WP-CLI to do some cool loops for updating <a href=\"https://guides.wp-bullet.com/using-wp-cli-for-batch-updating-contact-form-7-postmeta-options/\" rel=\"noreferrer\">WordPress serialized data programmatically</a></p>\n"
}
] |
2015/08/14
|
[
"https://wordpress.stackexchange.com/questions/198667",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75628/"
] |
I want to automate updating plugin options. There are some things that I repeat a lot.
With [wp-cli](http://wp-cli.org) I know I can update simple options like this:
```
php wp-cli.phar option update blog_public 1
```
However, some plugin options save their options in a serialized string.
Example of serialized option\_value in wp\_options:
```
a:9:{s:4:"from";s:21:"[email protected]";s:8:"fromname";s:51:"xxx";s:4:"host";s:13:"smtp.xx.com";s:10:"smtpsecure";s:3:"ssl";s:4:"port";s:3:"465";s:8:"smtpauth";s:3:"yes";s:8:"username";s:21:"[email protected]";s:8:"password";s:13:"xxx";s:10:"deactivate";s:0:"";}
```
How to update those options?
|
WP-CLI is definitely the answer to this after the update to 1.4.0 which introduced the [pluck](https://developer.wordpress.org/cli/commands/option/pluck/) and [patch](https://developer.wordpress.org/cli/commands/option/patch/) commands for accessing serialized data in WordPress.
The pluck command takes this format for grabbing serialized values
```
wp option pluck <key> <key-name>
```
For example in the active\_plugins option you can grab first item
```
wp option pluck active_plugins 0
```
The patch command takes this format for inserting, updating or removing serialized values (the action)
```
wp option patch <action> <key> <key-name> <value>
```
Deleting the first active\_plugin would look like this
```
wp option patch delete active_plugins 0
```
The same pluck and patch were also added for other commands like postmeta, you can now use WP-CLI to do some cool loops for updating [WordPress serialized data programmatically](https://guides.wp-bullet.com/using-wp-cli-for-batch-updating-contact-form-7-postmeta-options/)
|
198,681 |
<p>I am trying to confirm if a filter I have applied has changed the wp_login_url to the correct address. I just want to print out the result of wp_login_url somewhere I can see it.</p>
<pre><code>if ( has_shortcode( $post->post_content, 'clean-login' ) ) {
add_filter('login_url', get_permalink( $post->ID ), 10, 2);
//$log_url = wp_login_url();
error_log(esc_url(wp_login_url($redirect)));
}
</code></pre>
<p>I have been playing round with printf echo and now error_log. Not a super experienced php guy and only just playing with the wp debug.log now. </p>
<p>Any help would be really appreciated.</p>
|
[
{
"answer_id": 198673,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://wp-cli.org/\" rel=\"nofollow\">WP-CLI</a> command <a href=\"http://wp-cli.org/commands/option/\" rel=\"nofollow\"><code>option</code></a> does use WordPress' <a href=\"https://codex.wordpress.org/Options_API\" rel=\"nofollow\">Options API</a> to do its job. Given, e.g. with the subcommand <a href=\"http://wp-cli.org/commands/option/update/\" rel=\"nofollow\"><code>update</code></a>, a correct input, an <code>array</code>, you should be able to do this with WP-CLI. You should make use of the <code>--format</code> parameter here, to make sure you get the same, <code>json</code> works generally fine for the <code>update</code> subcommand. Note, the subcommand <a href=\"http://wp-cli.org/commands/option/get/\" rel=\"nofollow\"><code>get</code></a> should return you the option unserialized, because the Options API is used, which you then can save, modify and/or transfer/set-up on other/new installations.</p>\n"
},
{
"answer_id": 199315,
"author": "lalo",
"author_id": 75628,
"author_profile": "https://wordpress.stackexchange.com/users/75628",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Solved it myself, this is how to do it:</strong></p>\n\n<p>If you want to programatically update serialized options:</p>\n\n<p>download wp-cli from wp-cli.org</p>\n\n<p>Find out what is the \"key\" for the options you are using. In this example the key is \"wp_smtp_options\" </p>\n\n<p>If you don't know the key, search in wp_options table and try to figure it out. </p>\n\n<p>Example: <code>select * from wp_options where option_name like '%smtp%'</code></p>\n\n<p>Now that you know your key, use this command to save your configuration to json file:</p>\n\n<pre><code>php wp-cli.phar option get wp_smtp_options --format=json > my_saved_config.txt\n</code></pre>\n\n<p>Whenever you want that configuration to be restored use this command</p>\n\n<pre><code>php wp-cli.phar option update wp_smtp_options --format=json < my_saved_config.txt\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>works in WAMPSERVER64</li>\n<li>works with unicode characters like ñ á é</li>\n<li>you can have your json file with paddings and spaces, for legibility</li>\n</ul>\n\n<p>It would be great not having to use an intermediate file for this purpose. Does anybody know how to do it?</p>\n"
},
{
"answer_id": 249914,
"author": "Laurent",
"author_id": 28715,
"author_profile": "https://wordpress.stackexchange.com/users/28715",
"pm_score": 3,
"selected": false,
"text": "<p>Here is how I do it in a bash script:</p>\n\n<pre><code>wp option get wp_smtp_options --format=json | php -r '\n$var = json_decode( fgets(STDIN) );\n$var->from = \"[email protected]\";\n$var->fromname = \"me\";\nprint json_encode($var);\n' | wp option set wp_smtp_options --format=json\n</code></pre>\n"
},
{
"answer_id": 287713,
"author": "Mike Andreasen",
"author_id": 132678,
"author_profile": "https://wordpress.stackexchange.com/users/132678",
"pm_score": 5,
"selected": false,
"text": "<p>WP-CLI is definitely the answer to this after the update to 1.4.0 which introduced the <a href=\"https://developer.wordpress.org/cli/commands/option/pluck/\" rel=\"noreferrer\">pluck</a> and <a href=\"https://developer.wordpress.org/cli/commands/option/patch/\" rel=\"noreferrer\">patch</a> commands for accessing serialized data in WordPress.</p>\n\n<p>The pluck command takes this format for grabbing serialized values</p>\n\n<pre><code>wp option pluck <key> <key-name>\n</code></pre>\n\n<p>For example in the active_plugins option you can grab first item</p>\n\n<pre><code>wp option pluck active_plugins 0\n</code></pre>\n\n<p>The patch command takes this format for inserting, updating or removing serialized values (the action)</p>\n\n<pre><code>wp option patch <action> <key> <key-name> <value>\n</code></pre>\n\n<p>Deleting the first active_plugin would look like this</p>\n\n<pre><code>wp option patch delete active_plugins 0\n</code></pre>\n\n<p>The same pluck and patch were also added for other commands like postmeta, you can now use WP-CLI to do some cool loops for updating <a href=\"https://guides.wp-bullet.com/using-wp-cli-for-batch-updating-contact-form-7-postmeta-options/\" rel=\"noreferrer\">WordPress serialized data programmatically</a></p>\n"
}
] |
2015/08/14
|
[
"https://wordpress.stackexchange.com/questions/198681",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77144/"
] |
I am trying to confirm if a filter I have applied has changed the wp\_login\_url to the correct address. I just want to print out the result of wp\_login\_url somewhere I can see it.
```
if ( has_shortcode( $post->post_content, 'clean-login' ) ) {
add_filter('login_url', get_permalink( $post->ID ), 10, 2);
//$log_url = wp_login_url();
error_log(esc_url(wp_login_url($redirect)));
}
```
I have been playing round with printf echo and now error\_log. Not a super experienced php guy and only just playing with the wp debug.log now.
Any help would be really appreciated.
|
WP-CLI is definitely the answer to this after the update to 1.4.0 which introduced the [pluck](https://developer.wordpress.org/cli/commands/option/pluck/) and [patch](https://developer.wordpress.org/cli/commands/option/patch/) commands for accessing serialized data in WordPress.
The pluck command takes this format for grabbing serialized values
```
wp option pluck <key> <key-name>
```
For example in the active\_plugins option you can grab first item
```
wp option pluck active_plugins 0
```
The patch command takes this format for inserting, updating or removing serialized values (the action)
```
wp option patch <action> <key> <key-name> <value>
```
Deleting the first active\_plugin would look like this
```
wp option patch delete active_plugins 0
```
The same pluck and patch were also added for other commands like postmeta, you can now use WP-CLI to do some cool loops for updating [WordPress serialized data programmatically](https://guides.wp-bullet.com/using-wp-cli-for-batch-updating-contact-form-7-postmeta-options/)
|
198,689 |
<p>I'm creating a widget, and cannot figure out how to get an event right before the person clicks "save" or presses the enter button on the widget admin panel. What would be the javascript code to get the event on the widget admins' form submit? </p>
<p>Example:
<a href="https://i.stack.imgur.com/zkhjg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zkhjg.png" alt="enter image description here"></a></p>
<p>Thanks!</p>
|
[
{
"answer_id": 198864,
"author": "webtoure",
"author_id": 72992,
"author_profile": "https://wordpress.stackexchange.com/users/72992",
"pm_score": 4,
"selected": true,
"text": "<p>You need to listen for the <code>click</code> event (there is no such thing as a pre/before click) and do some work right then or figure out if you want to allow the <code>click</code> to \"go through\" or not based on some validation for example.</p>\n\n<pre><code>jQuery(function($) {\n // We are binding to the body so that the code\n // will work for future elements added to the DOM\n $('body').on('click', '.widget-control-save', function(ev) {\n var my_validation = true;\n\n if ( my_validation ) {\n console.log('widget save!');\n } else {\n ev.preventDefault();\n ev.stopPropagation(); /* We are capturing the event so it won't bubble up. */\n }\n })\n});\n</code></pre>\n"
},
{
"answer_id": 198898,
"author": "feelinferrety",
"author_id": 48824,
"author_profile": "https://wordpress.stackexchange.com/users/48824",
"pm_score": 1,
"selected": false,
"text": "<p>See the WordPress Codex page on <a href=\"http://codex.wordpress.org/Widgets_API\" rel=\"nofollow\">Widgets API</a> and utilize the <code>update()</code> function in your widget class declaration as used <a href=\"http://codex.wordpress.org/Widgets_API#Default_Usage\" rel=\"nofollow\">here</a> and add a script call in the appropriate place:</p>\n\n<pre><code>/**\n * Processing widget options on save\n *\n * @param array $new_instance The new options\n * @param array $old_instance The previous options\n */\npublic function update( $new_instance, $old_instance ) {\n // processes widget options to be saved\n?>\n <script type=\"javascript\">\n /*Your function here*/\n </script>\n<?php\n // be sure to include normal save functions as defined by Codex / source code\n}\n</code></pre>\n"
},
{
"answer_id": 199061,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 0,
"selected": false,
"text": "<p>1) If you want to perform certain operation as a first activity after the save button click, then you would have achieved it via server side script (here PHP) by hooking into some action, but as you are clearly specifying that you want client side action only, I think there is no straightforward way to control the order of the even like <code>click</code>. However, one following can be done -</p>\n\n<p>If you have to perform more than one JavaScript operations, then you can put your functions in the order accordingly.\ne.g. \non click, <code>func1()</code> should execute first and then <code>func2()</code>, so just call these in that order.</p>\n\n<p>2) If you have to perform only one JavaScript operation, then it will anyway be executed and then server side code will execute on submit. \nOR if this approach doesn't completely execute your JS function first, then you can use <code>preventDefault()</code> to let your JS function execute first and then automatically submit the form using JavaScript function only \ne.g. <code>.submit()</code> is available in jQuery </p>\n\n<p>3) Apart from these, I have one more way which I'm not completely sure but may help you -\nCan you use <code>onfocus</code> event instead? This will execute before click and will work with mouse as well as keyboard.\nBut, a disadvantage is that it will always execute your script irrespective of whether the user actually submitted the form or not.</p>\n\n<p>4) WordPress widget saves the widget form via ajax, so you can check if there is any hook available where you can inject your script and get your script executed before the form entry is actually made in database.</p>\n"
}
] |
2015/08/15
|
[
"https://wordpress.stackexchange.com/questions/198689",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2001/"
] |
I'm creating a widget, and cannot figure out how to get an event right before the person clicks "save" or presses the enter button on the widget admin panel. What would be the javascript code to get the event on the widget admins' form submit?
Example:
[](https://i.stack.imgur.com/zkhjg.png)
Thanks!
|
You need to listen for the `click` event (there is no such thing as a pre/before click) and do some work right then or figure out if you want to allow the `click` to "go through" or not based on some validation for example.
```
jQuery(function($) {
// We are binding to the body so that the code
// will work for future elements added to the DOM
$('body').on('click', '.widget-control-save', function(ev) {
var my_validation = true;
if ( my_validation ) {
console.log('widget save!');
} else {
ev.preventDefault();
ev.stopPropagation(); /* We are capturing the event so it won't bubble up. */
}
})
});
```
|
198,693 |
<p>I have a widget form with custom fields like age,pincode etc.The submitted form data will be submitted through a 3rd party API which will output me JSON. Now I want to redirect to a page showing the results.How can i redirect to a page from the widget with the result.?</p>
|
[
{
"answer_id": 198864,
"author": "webtoure",
"author_id": 72992,
"author_profile": "https://wordpress.stackexchange.com/users/72992",
"pm_score": 4,
"selected": true,
"text": "<p>You need to listen for the <code>click</code> event (there is no such thing as a pre/before click) and do some work right then or figure out if you want to allow the <code>click</code> to \"go through\" or not based on some validation for example.</p>\n\n<pre><code>jQuery(function($) {\n // We are binding to the body so that the code\n // will work for future elements added to the DOM\n $('body').on('click', '.widget-control-save', function(ev) {\n var my_validation = true;\n\n if ( my_validation ) {\n console.log('widget save!');\n } else {\n ev.preventDefault();\n ev.stopPropagation(); /* We are capturing the event so it won't bubble up. */\n }\n })\n});\n</code></pre>\n"
},
{
"answer_id": 198898,
"author": "feelinferrety",
"author_id": 48824,
"author_profile": "https://wordpress.stackexchange.com/users/48824",
"pm_score": 1,
"selected": false,
"text": "<p>See the WordPress Codex page on <a href=\"http://codex.wordpress.org/Widgets_API\" rel=\"nofollow\">Widgets API</a> and utilize the <code>update()</code> function in your widget class declaration as used <a href=\"http://codex.wordpress.org/Widgets_API#Default_Usage\" rel=\"nofollow\">here</a> and add a script call in the appropriate place:</p>\n\n<pre><code>/**\n * Processing widget options on save\n *\n * @param array $new_instance The new options\n * @param array $old_instance The previous options\n */\npublic function update( $new_instance, $old_instance ) {\n // processes widget options to be saved\n?>\n <script type=\"javascript\">\n /*Your function here*/\n </script>\n<?php\n // be sure to include normal save functions as defined by Codex / source code\n}\n</code></pre>\n"
},
{
"answer_id": 199061,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 0,
"selected": false,
"text": "<p>1) If you want to perform certain operation as a first activity after the save button click, then you would have achieved it via server side script (here PHP) by hooking into some action, but as you are clearly specifying that you want client side action only, I think there is no straightforward way to control the order of the even like <code>click</code>. However, one following can be done -</p>\n\n<p>If you have to perform more than one JavaScript operations, then you can put your functions in the order accordingly.\ne.g. \non click, <code>func1()</code> should execute first and then <code>func2()</code>, so just call these in that order.</p>\n\n<p>2) If you have to perform only one JavaScript operation, then it will anyway be executed and then server side code will execute on submit. \nOR if this approach doesn't completely execute your JS function first, then you can use <code>preventDefault()</code> to let your JS function execute first and then automatically submit the form using JavaScript function only \ne.g. <code>.submit()</code> is available in jQuery </p>\n\n<p>3) Apart from these, I have one more way which I'm not completely sure but may help you -\nCan you use <code>onfocus</code> event instead? This will execute before click and will work with mouse as well as keyboard.\nBut, a disadvantage is that it will always execute your script irrespective of whether the user actually submitted the form or not.</p>\n\n<p>4) WordPress widget saves the widget form via ajax, so you can check if there is any hook available where you can inject your script and get your script executed before the form entry is actually made in database.</p>\n"
}
] |
2015/08/15
|
[
"https://wordpress.stackexchange.com/questions/198693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77808/"
] |
I have a widget form with custom fields like age,pincode etc.The submitted form data will be submitted through a 3rd party API which will output me JSON. Now I want to redirect to a page showing the results.How can i redirect to a page from the widget with the result.?
|
You need to listen for the `click` event (there is no such thing as a pre/before click) and do some work right then or figure out if you want to allow the `click` to "go through" or not based on some validation for example.
```
jQuery(function($) {
// We are binding to the body so that the code
// will work for future elements added to the DOM
$('body').on('click', '.widget-control-save', function(ev) {
var my_validation = true;
if ( my_validation ) {
console.log('widget save!');
} else {
ev.preventDefault();
ev.stopPropagation(); /* We are capturing the event so it won't bubble up. */
}
})
});
```
|
198,781 |
<p>So I have been reading through every WordPress front-end AJAX file upload tutorial I can fine. Nothing is working for me at the moment. The one that makes the most sense to me is this one: <a href="http://theaveragedev.com/wordpress-files-ajax/" rel="noreferrer">http://theaveragedev.com/wordpress-files-ajax/</a></p>
<p>Here is my code:</p>
<p>In my template file example.php</p>
<pre><code><script>var ajax_url = "<?php echo admin_url('admin-ajax.php'); ?>"</script>
<form id="file_form">
<?php wp_nonce_field('ajax_file_nonce', 'security'); ?>
<input type="hidden" name="action" value="my_file_upload">
<label for="file_upload">It's a file upload...</label>
<input type="file" name="file_upload">
<input type="submit" value="Go">
</form>
</code></pre>
<p>This is in ajax-file-upload.js</p>
<pre><code>jQuery(document).ready(function(){
var form_data = {};
$(this).find('input').each(function(){
form_data[this.name] = $(this).val();
});
$('#file_form').ajaxForm({
url: ajax_url, // there on the admin side, do-it-yourself on the front-end
data: form_data,
type: 'POST',
contentType: 'json',
success: function(response){
alert(response.message);
}
});
});
</code></pre>
<p>This is in my functions.php</p>
<pre><code>function q_scripts(){
$src = get_template_directory_uri().'/js/ajax-file-upload.js';
wp_enqueue_script('my_ajax_file_uploader_thing', $src, array('jquery', 'jquery-form'));
}
add_action('init', 'q_scripts');
function handle_file_upload(){
check_ajax_referer('ajax_file_nonce', 'security');
if(!(is_array($_POST) && is_array($_FILES) && defined('DOING_AJAX') && DOING_AJAX)){
return;
}
if(!function_exists('wp_handle_upload')){
require_once(ABSPATH . 'wp-admin/includes/file.php');
}
$upload_overrides = array('test_form' => false);
$response = array();
foreach($_FILES as $file){
$file_info = wp_handle_upload($file, $upload_overrides);
// do something with the file info...
$response['message'] = 'Done!';
}
echo json_encode($response);
die();
}
add_action('wp_ajax_my_file_upload', 'handle_file_upload');
</code></pre>
<p>I have tried adding the enctype to the form element and this didn't work. The error I keep getting is an alert saying 'undefined'. Does anyone know how I can correct this issue?</p>
<p><strong>EDIT</strong></p>
<p>The 'undefined' issue has now gone away as I editied the js file to have a click event and changed the selector for the form input loop:</p>
<pre><code>jQuery(document).ready(function($){
$('#file_form :submit').click(function() {
var form_data = {};
$('#file_form').find('input').each(function () {
form_data[this.name] = $(this).val();
});
console.log(form_data);
$('#file_form').ajaxForm({
url: ajax_url, // there on the admin side, do-it-yourself on the front-end
data: form_data,
type: 'POST',
contentType: 'json',
success: function (response) {
alert(response.message);
},
error: function (response) {
console.log('error');
}
});
return false;
});
});
</code></pre>
<p>The files still aren't being uploaded to the media folder. I also want to get the uploaded URL back once it has uploaded.</p>
<p>I am writing to the console the file object so I can see what is happening. Here is an example of it:</p>
<pre><code>Object {security: "e6db2a6eee", _wp_http_referer: "/chat?sessionappid=138", action: "my_file_upload", file_upload: "C:\fakepath\download.jpg", "": "Go"}
</code></pre>
<p>Is there something wrong with this and is that why it isn't uploading?</p>
|
[
{
"answer_id": 263934,
"author": "Adnan Limdiwala",
"author_id": 85960,
"author_profile": "https://wordpress.stackexchange.com/users/85960",
"pm_score": 4,
"selected": false,
"text": "<p>Hi You have Use this COde For WordPress front-end AJAX file upload tutorial Code\nHere is my code:</p>\n\n<p>In my template file example.php</p>\n\n<pre><code><form enctype=\"multipart/form-data\">\n <input type=\"text\" name=\"support_title\" class=\"support-title\">\n <input type=\"file\" id=\"sortpicture\" name=\"upload\">\n <input class=\"save-support\" name=\"save_support\" type=\"button\" value=\"Save\">\n </form>\n</code></pre>\n\n<p>This is in ajax-file-upload.js</p>\n\n<pre><code> jQuery(document).on('click', '.save-support', function (e) {\n\n var supporttitle = jQuery('.support-title').val();\n\n var querytype = jQuery('.support-query').val();\n var file_data = jQuery('#sortpicture').prop('files')[0];\n\n var form_data = new FormData();\n if (supporttitle == '') {\n jQuery('.support-title').css({\"border\": \"1px solid red\"})\n return false;\n } else {\n jQuery('.support-title').css({\"border\": \"1px solid #e3ecf0\"})\n }\n\n form_data.append('file', file_data);\n form_data.append('action', 'md_support_save');\n form_data.append('supporttitle', supporttitle);\n\n jQuery.ajax({\n url: '<?php echo admin_url('admin-ajax.php'); ?>',\n type: 'post',\n contentType: false,\n processData: false,\n data: form_data,\n success: function (response) {\n jQuery('.Success-div').html(\"Form Submit Successfully\")\n }, \n error: function (response) {\n console.log('error');\n }\n\n });\n });\n\n });\n</code></pre>\n\n<p>This iS functions.php code</p>\n\n<pre><code> add_action( 'wp_ajax_md_support_save','md_support_save' );\n add_action( 'wp_ajax_nopriv_md_support_save','md_support_save' );\n\n\n function md_support_save(){\n $support_title = !empty($_POST['supporttitle']) ? \n $_POST['supporttitle'] : 'Support Title';\n\n if (!function_exists('wp_handle_upload')) {\n require_once(ABSPATH . 'wp-admin/includes/file.php');\n }\n // echo $_FILES[\"upload\"][\"name\"];\n $uploadedfile = $_FILES['file'];\n $upload_overrides = array('test_form' => false);\n $movefile = wp_handle_upload($uploadedfile, $upload_overrides);\n\n // echo $movefile['url'];\n if ($movefile && !isset($movefile['error'])) {\n echo \"File Upload Successfully\";\n } else {\n /**\n * Error generated by _wp_handle_upload()\n * @see _wp_handle_upload() in wp-admin/includes/file.php\n */\n echo $movefile['error'];\n }\n die();\n }\n</code></pre>\n"
},
{
"answer_id": 272851,
"author": "Rakesh Shah",
"author_id": 123511,
"author_profile": "https://wordpress.stackexchange.com/users/123511",
"pm_score": 0,
"selected": false,
"text": "<hr>\n\n<blockquote>\n <p>all codes for function.php</p>\n</blockquote>\n\n<hr>\n\n<p>\n\n<pre><code>if (!empty($_POST) || (!empty($_FILES))) {\n require_once (ABSPATH . '/wp-admin/includes/file.php');\n require_once (ABSPATH . '/wp-admin/includes/image.php');\n global $wpdb;\n if (isset($_POST['submit'])) {\n // Upload Exhibitor Logo\n $file = $_FILES['uploaded_doc'];\n if (!empty($file)) {\n $uploads = wp_upload_dir();\n // Create 'user_avatar' directory if not exist\n $folderPath = ABSPATH . 'wp-content/uploads/Reports';\n if (!file_exists($folderPath)) {\n mkdir($folderPath, 0777, true);\n }\n\n $ext = end((explode(\".\", $_FILES['uploaded_doc']['name']))); \n if( $ext== 'pdf' || $ext== 'docx' ){ \n $ABSPATH_userAvatarFullImage = ABSPATH . 'wp-content/uploads/Reports/' . time() . '.' . $ext;\n if (move_uploaded_file($_FILES['uploaded_doc']['tmp_name'], $ABSPATH_userAvatarFullImage)) { \n $data = array(\n 'title' => $_POST['title'],\n 'arabic_title' => $_POST['arabic_title'],\n 'principle_investigators' => $_POST['principle_investigators'],\n 'co_investgators' => $_POST['co_investgators'],\n 'coverage_area' => $_POST['coverage_area'],\n 'publication_year' => $_POST['publication_year'],\n 'types' => $_POST['types'],\n 'uploaded_doc' => $_FILES['uploaded_doc']['name'],\n 'create_date'=> date('Y-m-d H:i:s') \n\n ); \n $table = $wpdb->prefix . \"reports_publication\"; \n $result = $wpdb->insert($table, $data);\n\n }\n echo \"1\";\n }else{\n echo \"File not in format\";\n }\n\n }\n\n\n}\n}\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 358545,
"author": "Asha",
"author_id": 92824,
"author_profile": "https://wordpress.stackexchange.com/users/92824",
"pm_score": 2,
"selected": false,
"text": "<p><strong>HTML</strong></p>\n\n<pre><code><form id=\"article_form\" name=\"article_form\" class=\"wordpress-ajax-form\" method=\"post\" action=\"<?php echo admin_url('admin-ajax.php'); ?>\" enctype=\"multipart/form-data\" >\n <input type=\"file\" name=\"uploadedfiles\" id=\"uploadedfiles\" accept=\"image/*\" >\n <br>\n <input type=\"hidden\" name=\"action\" value=\"custom_action\">\n <br>\n <button>Send</button>\n </form>\n</code></pre>\n\n<p><strong>JS</strong></p>\n\n<pre><code> $(\".wordpress-ajax-form\").submit(function(evt){ \n\n evt.preventDefault();\n var formData = new FormData($(this)[0]);\n\n $.ajax({\n url: $('#article_form').attr('action'),\n type: 'POST',\n data: formData,\n async: true,\n cache: false,\n contentType: false,\n enctype: 'multipart/form-data',\n processData: false,\n success: function (response) {\n // alert(response);\n alert('Article created Successfully!!!');\n }\n });\n return false;\n }); \n</code></pre>\n"
}
] |
2015/08/16
|
[
"https://wordpress.stackexchange.com/questions/198781",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77850/"
] |
So I have been reading through every WordPress front-end AJAX file upload tutorial I can fine. Nothing is working for me at the moment. The one that makes the most sense to me is this one: <http://theaveragedev.com/wordpress-files-ajax/>
Here is my code:
In my template file example.php
```
<script>var ajax_url = "<?php echo admin_url('admin-ajax.php'); ?>"</script>
<form id="file_form">
<?php wp_nonce_field('ajax_file_nonce', 'security'); ?>
<input type="hidden" name="action" value="my_file_upload">
<label for="file_upload">It's a file upload...</label>
<input type="file" name="file_upload">
<input type="submit" value="Go">
</form>
```
This is in ajax-file-upload.js
```
jQuery(document).ready(function(){
var form_data = {};
$(this).find('input').each(function(){
form_data[this.name] = $(this).val();
});
$('#file_form').ajaxForm({
url: ajax_url, // there on the admin side, do-it-yourself on the front-end
data: form_data,
type: 'POST',
contentType: 'json',
success: function(response){
alert(response.message);
}
});
});
```
This is in my functions.php
```
function q_scripts(){
$src = get_template_directory_uri().'/js/ajax-file-upload.js';
wp_enqueue_script('my_ajax_file_uploader_thing', $src, array('jquery', 'jquery-form'));
}
add_action('init', 'q_scripts');
function handle_file_upload(){
check_ajax_referer('ajax_file_nonce', 'security');
if(!(is_array($_POST) && is_array($_FILES) && defined('DOING_AJAX') && DOING_AJAX)){
return;
}
if(!function_exists('wp_handle_upload')){
require_once(ABSPATH . 'wp-admin/includes/file.php');
}
$upload_overrides = array('test_form' => false);
$response = array();
foreach($_FILES as $file){
$file_info = wp_handle_upload($file, $upload_overrides);
// do something with the file info...
$response['message'] = 'Done!';
}
echo json_encode($response);
die();
}
add_action('wp_ajax_my_file_upload', 'handle_file_upload');
```
I have tried adding the enctype to the form element and this didn't work. The error I keep getting is an alert saying 'undefined'. Does anyone know how I can correct this issue?
**EDIT**
The 'undefined' issue has now gone away as I editied the js file to have a click event and changed the selector for the form input loop:
```
jQuery(document).ready(function($){
$('#file_form :submit').click(function() {
var form_data = {};
$('#file_form').find('input').each(function () {
form_data[this.name] = $(this).val();
});
console.log(form_data);
$('#file_form').ajaxForm({
url: ajax_url, // there on the admin side, do-it-yourself on the front-end
data: form_data,
type: 'POST',
contentType: 'json',
success: function (response) {
alert(response.message);
},
error: function (response) {
console.log('error');
}
});
return false;
});
});
```
The files still aren't being uploaded to the media folder. I also want to get the uploaded URL back once it has uploaded.
I am writing to the console the file object so I can see what is happening. Here is an example of it:
```
Object {security: "e6db2a6eee", _wp_http_referer: "/chat?sessionappid=138", action: "my_file_upload", file_upload: "C:\fakepath\download.jpg", "": "Go"}
```
Is there something wrong with this and is that why it isn't uploading?
|
Hi You have Use this COde For WordPress front-end AJAX file upload tutorial Code
Here is my code:
In my template file example.php
```
<form enctype="multipart/form-data">
<input type="text" name="support_title" class="support-title">
<input type="file" id="sortpicture" name="upload">
<input class="save-support" name="save_support" type="button" value="Save">
</form>
```
This is in ajax-file-upload.js
```
jQuery(document).on('click', '.save-support', function (e) {
var supporttitle = jQuery('.support-title').val();
var querytype = jQuery('.support-query').val();
var file_data = jQuery('#sortpicture').prop('files')[0];
var form_data = new FormData();
if (supporttitle == '') {
jQuery('.support-title').css({"border": "1px solid red"})
return false;
} else {
jQuery('.support-title').css({"border": "1px solid #e3ecf0"})
}
form_data.append('file', file_data);
form_data.append('action', 'md_support_save');
form_data.append('supporttitle', supporttitle);
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
contentType: false,
processData: false,
data: form_data,
success: function (response) {
jQuery('.Success-div').html("Form Submit Successfully")
},
error: function (response) {
console.log('error');
}
});
});
});
```
This iS functions.php code
```
add_action( 'wp_ajax_md_support_save','md_support_save' );
add_action( 'wp_ajax_nopriv_md_support_save','md_support_save' );
function md_support_save(){
$support_title = !empty($_POST['supporttitle']) ?
$_POST['supporttitle'] : 'Support Title';
if (!function_exists('wp_handle_upload')) {
require_once(ABSPATH . 'wp-admin/includes/file.php');
}
// echo $_FILES["upload"]["name"];
$uploadedfile = $_FILES['file'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
// echo $movefile['url'];
if ($movefile && !isset($movefile['error'])) {
echo "File Upload Successfully";
} else {
/**
* Error generated by _wp_handle_upload()
* @see _wp_handle_upload() in wp-admin/includes/file.php
*/
echo $movefile['error'];
}
die();
}
```
|
198,792 |
<p>I am trying to limit the files that are shown in the wordpress media library popup (from wp_editor). </p>
<p><em>Currently every single file that I have ever uploaded to my site is shown in the library but I would like to limit what users see to just files uploaded in the last 24 hours.</em></p>
<p>It is possible to limit the media library by author using the following code; however I'm not even sure where to start to limit the media library popup to files uploaded in the last 24 hours.</p>
<pre><code>add_action('pre_get_posts','users_own_attachments');
function users_own_attachments( $wp_query_obj ) {
global $current_user, $pagenow;
if( !is_a( $current_user, 'WP_User') )
return;
if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) )
return;
if( !current_user_can('delete_pages') )
$wp_query_obj->set('author', $current_user->ID );
return;
}
</code></pre>
|
[
{
"answer_id": 198809,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>You can adjust the <em>attachment query</em> in the media library popup, through the <code>ajax_query_attachments_args</code> filter.</p>\n\n<p>Here are two PHP 5.4+ examples:</p>\n\n<p><strong>Example #1:</strong></p>\n\n<p>Show only attachments that where uploaded during the last 24 hours:</p>\n\n<pre><code>/**\n * Media Library popup \n * - Only display attachments uploaded during the last 24 hours:\n */\nadd_filter( 'ajax_query_attachments_args', function( $args )\n{\n $args['date_query'] = [['after' => '24 hours ago', 'inclusive' => true ]];\n return $args;\n} );\n</code></pre>\n\n<p><strong>Example #2:</strong></p>\n\n<p>Show only attachments that where uploaded during the last 24 hours by the current user:</p>\n\n<pre><code>/**\n * Media Library popup\n * - Only display attachments uploaded during the last 24 hours by the current user:\n */\nadd_filter( 'ajax_query_attachments_args', function( $args )\n{\n $args['author'] = get_current_user_id();\n $args['date_query'] = [['after' => '24 hours ago', 'inclusive' => true ]];\n return $args;\n} );\n</code></pre>\n"
},
{
"answer_id": 198811,
"author": "Salem Terrano",
"author_id": 47211,
"author_profile": "https://wordpress.stackexchange.com/users/47211",
"pm_score": 2,
"selected": false,
"text": "<p>Add the filter \"ajax_query_attachments_args\" in this way and URLs variables are sent to the class WP_Query</p>\n\n<p>the default is to send</p>\n\n<pre><code>array(7) {\n [\"orderby\"]=> string(4) \"date\"\n [\"order\"]=> string(4) \"DESC\"\n [\"posts_per_page\"]=> string(2) \"40\"\n [\"paged\"]=> string(1) \"1\"\n [\"post_type\"]=> string(10) \"attachment\"\n [\"post_status\"]=> string(15) \"inherit,private\"\n}\n</code></pre>\n\n<p>Here you can modify to your liking</p>\n\n<pre><code>add_filter( 'ajax_query_attachments_args', 'my_ajax_query_attachments_args', 1, 10 );\n\nfunction my_ajax_query_attachments_args($query) {\n $query['date_query'] = array(\n array(\n 'before' => \"-1 day\",\n 'inclusive' => true,\n ),\n );\n var_dump($query);\n return $query;\n} \n</code></pre>\n"
}
] |
2015/08/16
|
[
"https://wordpress.stackexchange.com/questions/198792",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25609/"
] |
I am trying to limit the files that are shown in the wordpress media library popup (from wp\_editor).
*Currently every single file that I have ever uploaded to my site is shown in the library but I would like to limit what users see to just files uploaded in the last 24 hours.*
It is possible to limit the media library by author using the following code; however I'm not even sure where to start to limit the media library popup to files uploaded in the last 24 hours.
```
add_action('pre_get_posts','users_own_attachments');
function users_own_attachments( $wp_query_obj ) {
global $current_user, $pagenow;
if( !is_a( $current_user, 'WP_User') )
return;
if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) )
return;
if( !current_user_can('delete_pages') )
$wp_query_obj->set('author', $current_user->ID );
return;
}
```
|
You can adjust the *attachment query* in the media library popup, through the `ajax_query_attachments_args` filter.
Here are two PHP 5.4+ examples:
**Example #1:**
Show only attachments that where uploaded during the last 24 hours:
```
/**
* Media Library popup
* - Only display attachments uploaded during the last 24 hours:
*/
add_filter( 'ajax_query_attachments_args', function( $args )
{
$args['date_query'] = [['after' => '24 hours ago', 'inclusive' => true ]];
return $args;
} );
```
**Example #2:**
Show only attachments that where uploaded during the last 24 hours by the current user:
```
/**
* Media Library popup
* - Only display attachments uploaded during the last 24 hours by the current user:
*/
add_filter( 'ajax_query_attachments_args', function( $args )
{
$args['author'] = get_current_user_id();
$args['date_query'] = [['after' => '24 hours ago', 'inclusive' => true ]];
return $args;
} );
```
|
198,824 |
<p>I am trying to create custom menu nav walker. I added below code </p>
<pre><code>function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output )
{
$id_field = $this->db_fields['id'];
if ( is_object( $args[0] ) ) {
$args[0]->has_children = ! empty( $children_elements[$element->$id_field] );
}
return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
</code></pre>
<p>As a result I can use if ( $args->has_children ) statement in my start_el function, unfortunately the same code doesn't seem to be working in end_el function. </p>
<p>Entire code:</p>
<p>
<pre><code>class CSS_Menu_Walker2 extends Walker {
/**
* What the class handles.
*
* @see Walker::$tree_type
* @since 3.0.0
* @var string
*/
public $tree_type = array( 'post_type', 'taxonomy', 'custom' );
/**
* Database fields to use.
*
* @see Walker::$db_fields
* @since 3.0.0
* @todo Decouple this.
* @var array
*/
public $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' );
/**
* Starts the list before the elements are added.
*
* @see Walker::start_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent <div class=\"collapsible-body\"> <ul class=\"sub-menu\">\n";
}
/**
* Ends the list of after the elements are added.
*
* @see Walker::end_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul></div>\n";
}
/**
* Start the element output.
*
* @see Walker::start_el()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
* @param int $id Current item ID.
*/
function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output )
{
$id_field = $this->db_fields['id'];
if ( is_object( $args[0] ) ) {
$args[0]->has_children = ! empty( $children_elements[$element->$id_field] );
}
return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
/**
* Filter the CSS class(es) applied to a menu item's list item element.
*
* @since 3.0.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $classes The CSS classes that are applied to the menu item's `<li>` element.
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
/**
* Filter the ID applied to a menu item's list item element.
*
* @since 3.0.1
* @since 4.1.0 The `$depth` parameter was added.
*
* @param string $menu_id The ID that is applied to the menu item's `<li>` element.
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
if ( $args->has_children ) {
$output .= $indent . '<ul class="collapsible collapsible-accordion">';
$output .= $indent . '<a class="collapsible-header waves-effect waves-teal ">';
}
$output .= $indent . '<li' . $id . $class_names .'>';
$atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
/**
* Filter the HTML attributes applied to a menu item's anchor element.
*
* @since 3.6.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $title Title attribute.
* @type string $target Target attribute.
* @type string $rel The rel attribute.
* @type string $href The href attribute.
* }
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$item_output = $args->before;
if (!$args->has_children )
$item_output .= '<a'. $attributes .'>';
/** This filter is documented in wp-includes/post-template.php */
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
if (!$args->has_children )
$item_output .= '</a>';
$item_output .= $args->after;
/**
* Filter a menu item's starting output.
*
* The menu item's starting output only includes `$args->before`, the opening `<a>`,
* the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is
* no filter for modifying the opening and closing `<li>` for a menu item.
*
* @since 3.0.0
*
* @param string $item_output The menu item's starting HTML output.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of {@see wp_nav_menu()} arguments.
*/
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
/**
* Ends the element output, if needed.
*
* @see Walker::end_el()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Page data object. Not used.
* @param int $depth Depth of page. Not Used.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function end_el( &$output, $item, $depth = 0, $args = array() ) {
$output .= "</li>\n";
}
} // Walker_Nav_Menu
?>
a
</code></pre>
<p>Am I doing something wrong?</p>
|
[
{
"answer_id": 199847,
"author": "Jorge Raigoza",
"author_id": 74600,
"author_profile": "https://wordpress.stackexchange.com/users/74600",
"pm_score": 3,
"selected": true,
"text": "<p>I have the same issue. Some answers claim that you can use <code>$args->has_children</code> or <code>$args[0]->has_children</code>, but it's never added to $args. Sometimes, <code>has_children</code> is added under <code>$args->walker->has_children</code>, but it's always set to <code>false</code>, in other words, useless...</p>\n\n<p>As a work around, the current template that I'm using adds a class to items that contain children (menu-item-has-children), so I searched for it under <code>$item->classes</code>.</p>\n\n<pre><code>function end_el( &$output, $item, $depth = 0, $args = array() ) {\n\n if( !empty($item->classes) && \n is_array($item->classes) && \n in_array('menu-item-has-children', $item->classes) ){\n\n // This guy has children\n\n }\n}\n</code></pre>\n\n<p>I guess, you could add a mark in your start_el function and then search for it...</p>\n\n<p>I hope this helps. If you have a better solutions, please share it.</p>\n"
},
{
"answer_id": 396409,
"author": "Jefferson",
"author_id": 190088,
"author_profile": "https://wordpress.stackexchange.com/users/190088",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a one-liner that checks the <code>$children_elements</code> for the existence of the <code>$element->ID</code> as a top-level array key and is, therefore, a parent.</p>\n<pre><code>$is_parent = array_key_exists( $element->ID, $children_elements );\n</code></pre>\n<p><strong>EDIT:</strong> I should have mentioned this must be used in <code>Walker</code> method <code>display_element</code> so to use this you would add the method to your custom walker class as follows:</p>\n<pre><code>class Your_Custom_Walker extends Walker_Nav_Menu {\n\n public function display_element( $element, &$children_elements, $max_depth, $depth = 0, $args, &$output ) {\n\n $is_parent = array_key_exists( $element->ID, $children_elements );\n\n //do stuff with $is_parent\n\n }\n}\n</code></pre>\n<p>If you're not already using the <code>display_element</code> method then this 'one-liner' starts to look more cumbersome. This method makes iterating over and manipulating the menu tree a little easier as it happens before being passed to <code>start_el</code> and gives you access to <code>$children_elements</code>.</p>\n"
}
] |
2015/08/17
|
[
"https://wordpress.stackexchange.com/questions/198824",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77480/"
] |
I am trying to create custom menu nav walker. I added below code
```
function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output )
{
$id_field = $this->db_fields['id'];
if ( is_object( $args[0] ) ) {
$args[0]->has_children = ! empty( $children_elements[$element->$id_field] );
}
return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
```
As a result I can use if ( $args->has\_children ) statement in my start\_el function, unfortunately the same code doesn't seem to be working in end\_el function.
Entire code:
```
class CSS_Menu_Walker2 extends Walker {
/**
* What the class handles.
*
* @see Walker::$tree_type
* @since 3.0.0
* @var string
*/
public $tree_type = array( 'post_type', 'taxonomy', 'custom' );
/**
* Database fields to use.
*
* @see Walker::$db_fields
* @since 3.0.0
* @todo Decouple this.
* @var array
*/
public $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' );
/**
* Starts the list before the elements are added.
*
* @see Walker::start_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent <div class=\"collapsible-body\"> <ul class=\"sub-menu\">\n";
}
/**
* Ends the list of after the elements are added.
*
* @see Walker::end_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul></div>\n";
}
/**
* Start the element output.
*
* @see Walker::start_el()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
* @param int $id Current item ID.
*/
function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output )
{
$id_field = $this->db_fields['id'];
if ( is_object( $args[0] ) ) {
$args[0]->has_children = ! empty( $children_elements[$element->$id_field] );
}
return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
/**
* Filter the CSS class(es) applied to a menu item's list item element.
*
* @since 3.0.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $classes The CSS classes that are applied to the menu item's `<li>` element.
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
/**
* Filter the ID applied to a menu item's list item element.
*
* @since 3.0.1
* @since 4.1.0 The `$depth` parameter was added.
*
* @param string $menu_id The ID that is applied to the menu item's `<li>` element.
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
if ( $args->has_children ) {
$output .= $indent . '<ul class="collapsible collapsible-accordion">';
$output .= $indent . '<a class="collapsible-header waves-effect waves-teal ">';
}
$output .= $indent . '<li' . $id . $class_names .'>';
$atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
/**
* Filter the HTML attributes applied to a menu item's anchor element.
*
* @since 3.6.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $title Title attribute.
* @type string $target Target attribute.
* @type string $rel The rel attribute.
* @type string $href The href attribute.
* }
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$item_output = $args->before;
if (!$args->has_children )
$item_output .= '<a'. $attributes .'>';
/** This filter is documented in wp-includes/post-template.php */
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
if (!$args->has_children )
$item_output .= '</a>';
$item_output .= $args->after;
/**
* Filter a menu item's starting output.
*
* The menu item's starting output only includes `$args->before`, the opening `<a>`,
* the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is
* no filter for modifying the opening and closing `<li>` for a menu item.
*
* @since 3.0.0
*
* @param string $item_output The menu item's starting HTML output.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of {@see wp_nav_menu()} arguments.
*/
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
/**
* Ends the element output, if needed.
*
* @see Walker::end_el()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Page data object. Not used.
* @param int $depth Depth of page. Not Used.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function end_el( &$output, $item, $depth = 0, $args = array() ) {
$output .= "</li>\n";
}
} // Walker_Nav_Menu
?>
a
```
Am I doing something wrong?
|
I have the same issue. Some answers claim that you can use `$args->has_children` or `$args[0]->has_children`, but it's never added to $args. Sometimes, `has_children` is added under `$args->walker->has_children`, but it's always set to `false`, in other words, useless...
As a work around, the current template that I'm using adds a class to items that contain children (menu-item-has-children), so I searched for it under `$item->classes`.
```
function end_el( &$output, $item, $depth = 0, $args = array() ) {
if( !empty($item->classes) &&
is_array($item->classes) &&
in_array('menu-item-has-children', $item->classes) ){
// This guy has children
}
}
```
I guess, you could add a mark in your start\_el function and then search for it...
I hope this helps. If you have a better solutions, please share it.
|
198,837 |
<p>I am new to PHP and WordPress.<br></p>
<p>I have this scenario.<br>
There are 4 custom fields saved in page, named: <br>
_custField1<br>
_custField2<br>
_custField3<br>
_custField4<br></p>
<p>What I need to do now is to fetch their values and save them in an array and save that array back to page as custom field.</p>
<p>I tried following.</p>
<pre><code>$page_list = get_pages();
foreach($page_list as $page) {
$post_id = $page->ID;
$custField1= get_post_meta( $post_id, '_custField1' );
$custField2= get_post_meta( $post_id, '_custField2' );
$custField3= get_post_meta( $post_id, '_custField3' );
$custField4= get_post_meta( $post_id, '_custField4' );
$custArray[] = array(
'_custField1'=>$custField1,
'_custField2'=>$custField2,
'_custField3'=>$custField3,
'_custField4'=>$custField4
);
add_post_meta ( $post_id, '_newcust',maybe_serialize($custArray), true );
}
endforeach;
wp_reset_postdata();
</code></pre>
<p>It does save as array but each custom field is saved as array themself. While I want to achieve the results now as _newcust['_custField1'] , which I can not.</p>
<p>What I am doing wrong here ?</p>
<p>PS: One more thing, above code crashes the website if there are more than 50 pages, how should I optimize it.</p>
<p>Help will be greatly appreciated. </p>
|
[
{
"answer_id": 199847,
"author": "Jorge Raigoza",
"author_id": 74600,
"author_profile": "https://wordpress.stackexchange.com/users/74600",
"pm_score": 3,
"selected": true,
"text": "<p>I have the same issue. Some answers claim that you can use <code>$args->has_children</code> or <code>$args[0]->has_children</code>, but it's never added to $args. Sometimes, <code>has_children</code> is added under <code>$args->walker->has_children</code>, but it's always set to <code>false</code>, in other words, useless...</p>\n\n<p>As a work around, the current template that I'm using adds a class to items that contain children (menu-item-has-children), so I searched for it under <code>$item->classes</code>.</p>\n\n<pre><code>function end_el( &$output, $item, $depth = 0, $args = array() ) {\n\n if( !empty($item->classes) && \n is_array($item->classes) && \n in_array('menu-item-has-children', $item->classes) ){\n\n // This guy has children\n\n }\n}\n</code></pre>\n\n<p>I guess, you could add a mark in your start_el function and then search for it...</p>\n\n<p>I hope this helps. If you have a better solutions, please share it.</p>\n"
},
{
"answer_id": 396409,
"author": "Jefferson",
"author_id": 190088,
"author_profile": "https://wordpress.stackexchange.com/users/190088",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a one-liner that checks the <code>$children_elements</code> for the existence of the <code>$element->ID</code> as a top-level array key and is, therefore, a parent.</p>\n<pre><code>$is_parent = array_key_exists( $element->ID, $children_elements );\n</code></pre>\n<p><strong>EDIT:</strong> I should have mentioned this must be used in <code>Walker</code> method <code>display_element</code> so to use this you would add the method to your custom walker class as follows:</p>\n<pre><code>class Your_Custom_Walker extends Walker_Nav_Menu {\n\n public function display_element( $element, &$children_elements, $max_depth, $depth = 0, $args, &$output ) {\n\n $is_parent = array_key_exists( $element->ID, $children_elements );\n\n //do stuff with $is_parent\n\n }\n}\n</code></pre>\n<p>If you're not already using the <code>display_element</code> method then this 'one-liner' starts to look more cumbersome. This method makes iterating over and manipulating the menu tree a little easier as it happens before being passed to <code>start_el</code> and gives you access to <code>$children_elements</code>.</p>\n"
}
] |
2015/08/17
|
[
"https://wordpress.stackexchange.com/questions/198837",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77888/"
] |
I am new to PHP and WordPress.
I have this scenario.
There are 4 custom fields saved in page, named:
\_custField1
\_custField2
\_custField3
\_custField4
What I need to do now is to fetch their values and save them in an array and save that array back to page as custom field.
I tried following.
```
$page_list = get_pages();
foreach($page_list as $page) {
$post_id = $page->ID;
$custField1= get_post_meta( $post_id, '_custField1' );
$custField2= get_post_meta( $post_id, '_custField2' );
$custField3= get_post_meta( $post_id, '_custField3' );
$custField4= get_post_meta( $post_id, '_custField4' );
$custArray[] = array(
'_custField1'=>$custField1,
'_custField2'=>$custField2,
'_custField3'=>$custField3,
'_custField4'=>$custField4
);
add_post_meta ( $post_id, '_newcust',maybe_serialize($custArray), true );
}
endforeach;
wp_reset_postdata();
```
It does save as array but each custom field is saved as array themself. While I want to achieve the results now as \_newcust['\_custField1'] , which I can not.
What I am doing wrong here ?
PS: One more thing, above code crashes the website if there are more than 50 pages, how should I optimize it.
Help will be greatly appreciated.
|
I have the same issue. Some answers claim that you can use `$args->has_children` or `$args[0]->has_children`, but it's never added to $args. Sometimes, `has_children` is added under `$args->walker->has_children`, but it's always set to `false`, in other words, useless...
As a work around, the current template that I'm using adds a class to items that contain children (menu-item-has-children), so I searched for it under `$item->classes`.
```
function end_el( &$output, $item, $depth = 0, $args = array() ) {
if( !empty($item->classes) &&
is_array($item->classes) &&
in_array('menu-item-has-children', $item->classes) ){
// This guy has children
}
}
```
I guess, you could add a mark in your start\_el function and then search for it...
I hope this helps. If you have a better solutions, please share it.
|
198,880 |
<p>I tried to migrate my old blogs to a new server. The domain remained the same (it was also transfered to the new server). To perform this task I tried to follow these steps: <a href="https://codex.wordpress.org/Moving_WordPress#Keeping_Your_Domain_Name_and_URLs" rel="nofollow">https://codex.wordpress.org/Moving_WordPress#Keeping_Your_Domain_Name_and_URLs</a></p>
<p>When I now visit the moved blogs, I get nothing more than the "infamous white screen of death".</p>
<p>The wordpress version seems to be 4.1.2
The moved blog should be found at <a href="http://yeara.net/odysseus/" rel="nofollow">http://yeara.net/odysseus/</a>
The old blog is at <a href="http://speendo.cassiopeia.uberspace.de/odysseus/" rel="nofollow">http://speendo.cassiopeia.uberspace.de/odysseus/</a></p>
<p>Can you help me to get this straight?</p>
<p>(X-post: <a href="https://wordpress.org/support/topic/server-migration-white-screen-of-death" rel="nofollow">https://wordpress.org/support/topic/server-migration-white-screen-of-death</a>)</p>
|
[
{
"answer_id": 198881,
"author": "Dale Allen",
"author_id": 77912,
"author_profile": "https://wordpress.stackexchange.com/users/77912",
"pm_score": 0,
"selected": false,
"text": "<p>If the old blog and new blog have different domains then they didn't not remain the same. Share:</p>\n\n<ul>\n<li>current exact URL to the home page is intended to be?</li>\n<li>old exact URL to the home page was?</li>\n</ul>\n\n<p>Without knowing more it seems like either a URL/directory issue or perhaps an issue with the files/database migration.</p>\n"
},
{
"answer_id": 198885,
"author": "Dale Allen",
"author_id": 77912,
"author_profile": "https://wordpress.stackexchange.com/users/77912",
"pm_score": 2,
"selected": false,
"text": "<p>So your domain at yeara.net/odysseus loads the following in plain HTML:</p>\n\n<pre><code><?php\n/**\n * Front to the WordPress application. This file doesn't do anything, but loads\n * wp-blog-header.php which does and tells WordPress to load the theme.\n *\n * @package WordPress\n */\n\n /**\n * Tells WordPress to load the WordPress theme and output it.\n *\n * @var bool\n */\n define('WP_USE_THEMES', true);\n\n /** Loads the WordPress Environment and Template */\n require( dirname( __FILE__ ) . '/wp-blog-header.php' );\n</code></pre>\n\n<p>Have you confirmed that PHP is installed on your new server?</p>\n"
},
{
"answer_id": 198886,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>It might be a problem with file permissions, maybe related to the method you use for uploading the files, or as @webtoure pointed out with your apache set-up. The content @DaleAllen pointed out is the <code>index.php</code> of your WordPress installation. More critical I can see the content of your <code>wp-config.php</code> by directly pointing at it.</p>\n<p>Take a look at the codex articles:</p>\n<ul>\n<li><a href=\"https://codex.wordpress.org/Changing_File_Permissions\" rel=\"nofollow noreferrer\">Changing File Permissions</a></li>\n<li><a href=\"https://wordpress.org/support/article/hardening-wordpress/\" rel=\"nofollow noreferrer\">Hardening WordPress</a></li>\n</ul>\n<p>to change the file permissions accordingly.</p>\n<p><em>Do <strong>NOT</strong> forget to change all security relevant information!</em> Because if I can see it, everybody can.</p>\n"
},
{
"answer_id": 198887,
"author": "webtoure",
"author_id": 72992,
"author_profile": "https://wordpress.stackexchange.com/users/72992",
"pm_score": 3,
"selected": true,
"text": "<p>You may not have configured Apache. Add this line in your <code>apache2.conf</code> file:</p>\n\n<pre><code>AddType application/x-httpd-php .php .htm .html\n</code></pre>\n\n<p>Evidently, you should make sure you actually have <a href=\"http://php.net/manual/en/install.unix.debian.php\" rel=\"nofollow\">installed and activated the PHP module</a> first and foremost (the above Apache directive might not even be necessary in this case). In this regard, you can visit the <code>/etc/apache2/mods-enabled/</code> folder and look for the <code>php5.load</code>, <code>php5.conf</code> files.</p>\n"
}
] |
2015/08/17
|
[
"https://wordpress.stackexchange.com/questions/198880",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4544/"
] |
I tried to migrate my old blogs to a new server. The domain remained the same (it was also transfered to the new server). To perform this task I tried to follow these steps: <https://codex.wordpress.org/Moving_WordPress#Keeping_Your_Domain_Name_and_URLs>
When I now visit the moved blogs, I get nothing more than the "infamous white screen of death".
The wordpress version seems to be 4.1.2
The moved blog should be found at <http://yeara.net/odysseus/>
The old blog is at <http://speendo.cassiopeia.uberspace.de/odysseus/>
Can you help me to get this straight?
(X-post: <https://wordpress.org/support/topic/server-migration-white-screen-of-death>)
|
You may not have configured Apache. Add this line in your `apache2.conf` file:
```
AddType application/x-httpd-php .php .htm .html
```
Evidently, you should make sure you actually have [installed and activated the PHP module](http://php.net/manual/en/install.unix.debian.php) first and foremost (the above Apache directive might not even be necessary in this case). In this regard, you can visit the `/etc/apache2/mods-enabled/` folder and look for the `php5.load`, `php5.conf` files.
|
198,904 |
<p>I have a wordpress site, against which I ran a penetration testing tool (debug mode was on at the time)</p>
<p>It reported a (medium severity) issue in that errors were being displayed, and cited</p>
<blockquote>
<p><code>/wp-login.php?redirect_to[]=blah</code> </p>
<p>as triggering a warning: <code>urlencode()</code> expects parameter 1 to be string,
array given in <code>/home3/.../wp-includes/general-template.php</code> on line 340</p>
</blockquote>
<p>When I turned debug mode off, and replayed the session the redirect took place, and redirected me to /Array</p>
<p>Which concerns me that wordpress may be trying to evaluate the querystring parameter name in some way that is exploitable.</p>
<p>Am I being overly paranoid?</p>
|
[
{
"answer_id": 198881,
"author": "Dale Allen",
"author_id": 77912,
"author_profile": "https://wordpress.stackexchange.com/users/77912",
"pm_score": 0,
"selected": false,
"text": "<p>If the old blog and new blog have different domains then they didn't not remain the same. Share:</p>\n\n<ul>\n<li>current exact URL to the home page is intended to be?</li>\n<li>old exact URL to the home page was?</li>\n</ul>\n\n<p>Without knowing more it seems like either a URL/directory issue or perhaps an issue with the files/database migration.</p>\n"
},
{
"answer_id": 198885,
"author": "Dale Allen",
"author_id": 77912,
"author_profile": "https://wordpress.stackexchange.com/users/77912",
"pm_score": 2,
"selected": false,
"text": "<p>So your domain at yeara.net/odysseus loads the following in plain HTML:</p>\n\n<pre><code><?php\n/**\n * Front to the WordPress application. This file doesn't do anything, but loads\n * wp-blog-header.php which does and tells WordPress to load the theme.\n *\n * @package WordPress\n */\n\n /**\n * Tells WordPress to load the WordPress theme and output it.\n *\n * @var bool\n */\n define('WP_USE_THEMES', true);\n\n /** Loads the WordPress Environment and Template */\n require( dirname( __FILE__ ) . '/wp-blog-header.php' );\n</code></pre>\n\n<p>Have you confirmed that PHP is installed on your new server?</p>\n"
},
{
"answer_id": 198886,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>It might be a problem with file permissions, maybe related to the method you use for uploading the files, or as @webtoure pointed out with your apache set-up. The content @DaleAllen pointed out is the <code>index.php</code> of your WordPress installation. More critical I can see the content of your <code>wp-config.php</code> by directly pointing at it.</p>\n<p>Take a look at the codex articles:</p>\n<ul>\n<li><a href=\"https://codex.wordpress.org/Changing_File_Permissions\" rel=\"nofollow noreferrer\">Changing File Permissions</a></li>\n<li><a href=\"https://wordpress.org/support/article/hardening-wordpress/\" rel=\"nofollow noreferrer\">Hardening WordPress</a></li>\n</ul>\n<p>to change the file permissions accordingly.</p>\n<p><em>Do <strong>NOT</strong> forget to change all security relevant information!</em> Because if I can see it, everybody can.</p>\n"
},
{
"answer_id": 198887,
"author": "webtoure",
"author_id": 72992,
"author_profile": "https://wordpress.stackexchange.com/users/72992",
"pm_score": 3,
"selected": true,
"text": "<p>You may not have configured Apache. Add this line in your <code>apache2.conf</code> file:</p>\n\n<pre><code>AddType application/x-httpd-php .php .htm .html\n</code></pre>\n\n<p>Evidently, you should make sure you actually have <a href=\"http://php.net/manual/en/install.unix.debian.php\" rel=\"nofollow\">installed and activated the PHP module</a> first and foremost (the above Apache directive might not even be necessary in this case). In this regard, you can visit the <code>/etc/apache2/mods-enabled/</code> folder and look for the <code>php5.load</code>, <code>php5.conf</code> files.</p>\n"
}
] |
2015/08/18
|
[
"https://wordpress.stackexchange.com/questions/198904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77928/"
] |
I have a wordpress site, against which I ran a penetration testing tool (debug mode was on at the time)
It reported a (medium severity) issue in that errors were being displayed, and cited
>
> `/wp-login.php?redirect_to[]=blah`
>
>
> as triggering a warning: `urlencode()` expects parameter 1 to be string,
> array given in `/home3/.../wp-includes/general-template.php` on line 340
>
>
>
When I turned debug mode off, and replayed the session the redirect took place, and redirected me to /Array
Which concerns me that wordpress may be trying to evaluate the querystring parameter name in some way that is exploitable.
Am I being overly paranoid?
|
You may not have configured Apache. Add this line in your `apache2.conf` file:
```
AddType application/x-httpd-php .php .htm .html
```
Evidently, you should make sure you actually have [installed and activated the PHP module](http://php.net/manual/en/install.unix.debian.php) first and foremost (the above Apache directive might not even be necessary in this case). In this regard, you can visit the `/etc/apache2/mods-enabled/` folder and look for the `php5.load`, `php5.conf` files.
|
198,906 |
<p>After my WordPress site was updated to 4.2.4, my PayPal buttons no longer work. I can SEE the buttons, but can't click on them and go to PayPal. Hovering over the button shows no web link. I've recopied the code from PayPal several times, to no avail. </p>
<p>I notice that the (form) command gets screwed up every time I save/update the page where the buttons are. It puts the (/form) BEFORE the table where I have price options, near the beginning of the code. I then cut it and put it at the END of the code, click "update" and when I go back into the text mode, it has moved the again! Very frustrating. </p>
<p>I posted this question on WordPress.org, but no answers as of yet. I also emailed PayPal, but no answers yet either. Any ideas?</p>
<h2>Thanks</h2>
<p><strong>UPDATE</strong>: I see that when I put the (form) command, it stripped it because it was HTML. So I've put parentheses on it now so it shows up.
The page on my website where I'm having the problem is:
<a href="http://sonomabodybalance.com/workshops/" rel="nofollow">www.sonomabodybalance.com/workshops/</a></p>
<p>You can see the PayPal button, but hovering or clicking does nothing.</p>
<p>I've pasted the CODE here, and I indented by 4 spaces, like the "How to Format" instructions say, but it's not working: (suggestions welcome...)
Tuition:
Paid by 9/11 $25.00 USD
Paid by 9/14 $30.00 USD
Paid after 9/14 $40.00 USD
</p>
|
[
{
"answer_id": 198881,
"author": "Dale Allen",
"author_id": 77912,
"author_profile": "https://wordpress.stackexchange.com/users/77912",
"pm_score": 0,
"selected": false,
"text": "<p>If the old blog and new blog have different domains then they didn't not remain the same. Share:</p>\n\n<ul>\n<li>current exact URL to the home page is intended to be?</li>\n<li>old exact URL to the home page was?</li>\n</ul>\n\n<p>Without knowing more it seems like either a URL/directory issue or perhaps an issue with the files/database migration.</p>\n"
},
{
"answer_id": 198885,
"author": "Dale Allen",
"author_id": 77912,
"author_profile": "https://wordpress.stackexchange.com/users/77912",
"pm_score": 2,
"selected": false,
"text": "<p>So your domain at yeara.net/odysseus loads the following in plain HTML:</p>\n\n<pre><code><?php\n/**\n * Front to the WordPress application. This file doesn't do anything, but loads\n * wp-blog-header.php which does and tells WordPress to load the theme.\n *\n * @package WordPress\n */\n\n /**\n * Tells WordPress to load the WordPress theme and output it.\n *\n * @var bool\n */\n define('WP_USE_THEMES', true);\n\n /** Loads the WordPress Environment and Template */\n require( dirname( __FILE__ ) . '/wp-blog-header.php' );\n</code></pre>\n\n<p>Have you confirmed that PHP is installed on your new server?</p>\n"
},
{
"answer_id": 198886,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>It might be a problem with file permissions, maybe related to the method you use for uploading the files, or as @webtoure pointed out with your apache set-up. The content @DaleAllen pointed out is the <code>index.php</code> of your WordPress installation. More critical I can see the content of your <code>wp-config.php</code> by directly pointing at it.</p>\n<p>Take a look at the codex articles:</p>\n<ul>\n<li><a href=\"https://codex.wordpress.org/Changing_File_Permissions\" rel=\"nofollow noreferrer\">Changing File Permissions</a></li>\n<li><a href=\"https://wordpress.org/support/article/hardening-wordpress/\" rel=\"nofollow noreferrer\">Hardening WordPress</a></li>\n</ul>\n<p>to change the file permissions accordingly.</p>\n<p><em>Do <strong>NOT</strong> forget to change all security relevant information!</em> Because if I can see it, everybody can.</p>\n"
},
{
"answer_id": 198887,
"author": "webtoure",
"author_id": 72992,
"author_profile": "https://wordpress.stackexchange.com/users/72992",
"pm_score": 3,
"selected": true,
"text": "<p>You may not have configured Apache. Add this line in your <code>apache2.conf</code> file:</p>\n\n<pre><code>AddType application/x-httpd-php .php .htm .html\n</code></pre>\n\n<p>Evidently, you should make sure you actually have <a href=\"http://php.net/manual/en/install.unix.debian.php\" rel=\"nofollow\">installed and activated the PHP module</a> first and foremost (the above Apache directive might not even be necessary in this case). In this regard, you can visit the <code>/etc/apache2/mods-enabled/</code> folder and look for the <code>php5.load</code>, <code>php5.conf</code> files.</p>\n"
}
] |
2015/08/18
|
[
"https://wordpress.stackexchange.com/questions/198906",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77933/"
] |
After my WordPress site was updated to 4.2.4, my PayPal buttons no longer work. I can SEE the buttons, but can't click on them and go to PayPal. Hovering over the button shows no web link. I've recopied the code from PayPal several times, to no avail.
I notice that the (form) command gets screwed up every time I save/update the page where the buttons are. It puts the (/form) BEFORE the table where I have price options, near the beginning of the code. I then cut it and put it at the END of the code, click "update" and when I go back into the text mode, it has moved the again! Very frustrating.
I posted this question on WordPress.org, but no answers as of yet. I also emailed PayPal, but no answers yet either. Any ideas?
Thanks
------
**UPDATE**: I see that when I put the (form) command, it stripped it because it was HTML. So I've put parentheses on it now so it shows up.
The page on my website where I'm having the problem is:
[www.sonomabodybalance.com/workshops/](http://sonomabodybalance.com/workshops/)
You can see the PayPal button, but hovering or clicking does nothing.
I've pasted the CODE here, and I indented by 4 spaces, like the "How to Format" instructions say, but it's not working: (suggestions welcome...)
Tuition:
Paid by 9/11 $25.00 USD
Paid by 9/14 $30.00 USD
Paid after 9/14 $40.00 USD
|
You may not have configured Apache. Add this line in your `apache2.conf` file:
```
AddType application/x-httpd-php .php .htm .html
```
Evidently, you should make sure you actually have [installed and activated the PHP module](http://php.net/manual/en/install.unix.debian.php) first and foremost (the above Apache directive might not even be necessary in this case). In this regard, you can visit the `/etc/apache2/mods-enabled/` folder and look for the `php5.load`, `php5.conf` files.
|
198,943 |
<p>WordPress already has a default URL for jQuery-WordPress application calls and it's well known as the <code>ajaxurl</code>. However, there are cases wherein one would need to enable <strong>Cross-Origin Resource Sharing</strong> (CORS) on it such that any hostname will be able to access using it.</p>
<p>My current solutions is by adding a line in <code>/wp-includes/http.php</code> with:</p>
<pre><code>@header( 'Access-Control-Allow-Origin: *' );
</code></pre>
<p>Such that it will be:</p>
<h2>http.php</h2>
<pre><code>...
function send_origin_headers() {
$origin = get_http_origin();
@header( 'Access-Control-Allow-Origin: *' );
if ( is_allowed_http_origin( $origin ) ) {
@header( 'Access-Control-Allow-Origin: ' . $origin );
@header( 'Access-Control-Allow-Credentials: true' );
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] )
exit;
return $origin;
}
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
status_header( 403 );
exit;
}
return false;
}
...
</code></pre>
<p>It works but editing the WordPress core is not a good solution.</p>
<p>Is there a better way to enable CORS for the <code>ajaxurl</code>?</p>
<h1>Warning</h1>
<p><a href="https://stackoverflow.blog/2019/11/26/copying-code-from-stack-overflow-you-might-be-spreading-security-vulnerabilities/">This topic contains security vulnerabilities</a> when actually implementing it on a wordpress installation.</p>
<h1>Note</h1>
<p>This question was posted during the era of <strong>Wordpress 4.3</strong>. When the <strong>Wordpress 4.4</strong> was released with the new feature <a href="https://wordpress.org/support/wordpress-version/version-4-4/#for-developers" rel="noreferrer">WordPress REST API</a>, enabling CORS no longer became necessary and instead just use the <code>rest_api_init</code> hook to <a href="https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/" rel="noreferrer">add custom REST endpoints</a>.</p>
|
[
{
"answer_id": 198961,
"author": "Sundar",
"author_id": 75205,
"author_profile": "https://wordpress.stackexchange.com/users/75205",
"pm_score": 1,
"selected": false,
"text": "<p>You can achieve it by the following code. </p>\n\n<p>Open you <strong>header.php</strong> </p>\n\n<p>find the following text in that file </p>\n\n<pre><code>< !DOCTYPE html>\n</code></pre>\n\n<p>and replace it with the following. </p>\n\n<pre><code><?php /** @package WordPress @subpackage Default_Theme **/\nheader(\"Access-Control-Allow-Origin: *\"); \n?>\n<! DOCTYPE html>\n...\n</code></pre>\n\n<p>Now u can find Access-Control-Allow-Origin: * in your header. </p>\n\n<p>Hope this helps..!Cheers.</p>\n"
},
{
"answer_id": 226494,
"author": "Julian",
"author_id": 93994,
"author_profile": "https://wordpress.stackexchange.com/users/93994",
"pm_score": 4,
"selected": false,
"text": "<p>Milo is correct.</p>\n\n<p>For instance, go to your theme's functions.php file, and add the following:</p>\n\n<pre><code>add_filter( 'allowed_http_origins', 'add_allowed_origins' );\nfunction add_allowed_origins( $origins ) {\n $origins[] = 'https://site1.example.com';\n $origins[] = 'https://site2.example.com';\n return $origins;\n}\n</code></pre>\n\n<p>Now an ajax call from <a href=\"https://site1.example.com\" rel=\"noreferrer\">https://site1.example.com</a> to your site's ajax url will have the appropriate Access-Control-Allow-Origin header in the response. eg.</p>\n\n<pre><code>$.ajax({\n url: 'https://site1.example.com/wp-admin/admin-ajax.php',\n type: \"POST\",\n data: {\n ...\n },\n success: function(doc) {\n ...\n }\n});\n</code></pre>\n"
},
{
"answer_id": 352454,
"author": "Saurabh",
"author_id": 178259,
"author_profile": "https://wordpress.stackexchange.com/users/178259",
"pm_score": 0,
"selected": false,
"text": "<p>The best way as far as I found, I followed this link .</p>\n\n<p><em>Just add the origin code to the WordPress <strong>header.php</strong> or ajax <strong>functions/api</strong> file.</em></p>\n\n<p><strong>Link:</strong> [<a href=\"https://stackoverflow.com/a/25719261/5431206]\">https://stackoverflow.com/a/25719261/5431206]</a></p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 362905,
"author": "Ali Raza",
"author_id": 111084,
"author_profile": "https://wordpress.stackexchange.com/users/111084",
"pm_score": 2,
"selected": false,
"text": "<p>Just add this code into your function.php, no need to update <code>.htaccess</code>, <code>/wp-includes/http.php</code> or any other core file.</p>\n<pre><code>function just_add_cors_http_header($headers){\n\n $headers['Access-Control-Allow-Origin'] = '*';\n\n return $headers;\n\n}\n\nadd_filter('wp_headers','just_add_cors_http_header');\n</code></pre>\n<p>Cheers!</p>\n"
}
] |
2015/08/18
|
[
"https://wordpress.stackexchange.com/questions/198943",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58915/"
] |
WordPress already has a default URL for jQuery-WordPress application calls and it's well known as the `ajaxurl`. However, there are cases wherein one would need to enable **Cross-Origin Resource Sharing** (CORS) on it such that any hostname will be able to access using it.
My current solutions is by adding a line in `/wp-includes/http.php` with:
```
@header( 'Access-Control-Allow-Origin: *' );
```
Such that it will be:
http.php
--------
```
...
function send_origin_headers() {
$origin = get_http_origin();
@header( 'Access-Control-Allow-Origin: *' );
if ( is_allowed_http_origin( $origin ) ) {
@header( 'Access-Control-Allow-Origin: ' . $origin );
@header( 'Access-Control-Allow-Credentials: true' );
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] )
exit;
return $origin;
}
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
status_header( 403 );
exit;
}
return false;
}
...
```
It works but editing the WordPress core is not a good solution.
Is there a better way to enable CORS for the `ajaxurl`?
Warning
=======
[This topic contains security vulnerabilities](https://stackoverflow.blog/2019/11/26/copying-code-from-stack-overflow-you-might-be-spreading-security-vulnerabilities/) when actually implementing it on a wordpress installation.
Note
====
This question was posted during the era of **Wordpress 4.3**. When the **Wordpress 4.4** was released with the new feature [WordPress REST API](https://wordpress.org/support/wordpress-version/version-4-4/#for-developers), enabling CORS no longer became necessary and instead just use the `rest_api_init` hook to [add custom REST endpoints](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/).
|
Milo is correct.
For instance, go to your theme's functions.php file, and add the following:
```
add_filter( 'allowed_http_origins', 'add_allowed_origins' );
function add_allowed_origins( $origins ) {
$origins[] = 'https://site1.example.com';
$origins[] = 'https://site2.example.com';
return $origins;
}
```
Now an ajax call from <https://site1.example.com> to your site's ajax url will have the appropriate Access-Control-Allow-Origin header in the response. eg.
```
$.ajax({
url: 'https://site1.example.com/wp-admin/admin-ajax.php',
type: "POST",
data: {
...
},
success: function(doc) {
...
}
});
```
|
198,950 |
<p>I use a <code>get_posts()</code> call with these arguments:</p>
<pre><code>array(6) {
["include"]=> string(14) "1633,1634,1635"
["post_status"]=> string(3) "any"
["post_type"]=> string(10) "attachment"
["post_mime_type"]=> string(5) "image"
["order"]=> string(3) "ASC"
["orderby"]=> string(8) "post__in"
}
</code></pre>
<p>While <strong>logged out</strong> or logged in as an <strong>Admin</strong>, <strong>it works fine</strong> and returns the objects for 3 images. However, when the <strong>user is just a Subscriber/Author/Editor/Contributor, it returns an empty array</strong>.</p>
<p>All plugins enabled/disabled doesn't make a difference.</p>
<p>When switching the theme to an official WP theme, the <strong>error no longer persists</strong>.</p>
<p>I've dumped all hooks using <a href="http://www.rarst.net/wordpress/debug-wordpress-hooks/" rel="nofollow">this</a> (one logged in with subscriber, one with admin), but I find no considerable difference. <a href="http://https://gist.githubusercontent.com/Thefirsh/3175b3aab22d3edb61ee/raw/197dfcf21f563ff10704f7e73f3ee00ef5407c6b/a.txt" rel="nofollow">Case A</a> / <a href="https://gist.githubusercontent.com/Thefirsh/3175b3aab22d3edb61ee/raw/197dfcf21f563ff10704f7e73f3ee00ef5407c6b/b.txt" rel="nofollow">Case B</a>. I was assuming that the theme alters my arguments to an extent that there are no results for the altered query. If it's still the case, how and where should it do that?</p>
<p>The theme is Javo Directory.</p>
|
[
{
"answer_id": 198961,
"author": "Sundar",
"author_id": 75205,
"author_profile": "https://wordpress.stackexchange.com/users/75205",
"pm_score": 1,
"selected": false,
"text": "<p>You can achieve it by the following code. </p>\n\n<p>Open you <strong>header.php</strong> </p>\n\n<p>find the following text in that file </p>\n\n<pre><code>< !DOCTYPE html>\n</code></pre>\n\n<p>and replace it with the following. </p>\n\n<pre><code><?php /** @package WordPress @subpackage Default_Theme **/\nheader(\"Access-Control-Allow-Origin: *\"); \n?>\n<! DOCTYPE html>\n...\n</code></pre>\n\n<p>Now u can find Access-Control-Allow-Origin: * in your header. </p>\n\n<p>Hope this helps..!Cheers.</p>\n"
},
{
"answer_id": 226494,
"author": "Julian",
"author_id": 93994,
"author_profile": "https://wordpress.stackexchange.com/users/93994",
"pm_score": 4,
"selected": false,
"text": "<p>Milo is correct.</p>\n\n<p>For instance, go to your theme's functions.php file, and add the following:</p>\n\n<pre><code>add_filter( 'allowed_http_origins', 'add_allowed_origins' );\nfunction add_allowed_origins( $origins ) {\n $origins[] = 'https://site1.example.com';\n $origins[] = 'https://site2.example.com';\n return $origins;\n}\n</code></pre>\n\n<p>Now an ajax call from <a href=\"https://site1.example.com\" rel=\"noreferrer\">https://site1.example.com</a> to your site's ajax url will have the appropriate Access-Control-Allow-Origin header in the response. eg.</p>\n\n<pre><code>$.ajax({\n url: 'https://site1.example.com/wp-admin/admin-ajax.php',\n type: \"POST\",\n data: {\n ...\n },\n success: function(doc) {\n ...\n }\n});\n</code></pre>\n"
},
{
"answer_id": 352454,
"author": "Saurabh",
"author_id": 178259,
"author_profile": "https://wordpress.stackexchange.com/users/178259",
"pm_score": 0,
"selected": false,
"text": "<p>The best way as far as I found, I followed this link .</p>\n\n<p><em>Just add the origin code to the WordPress <strong>header.php</strong> or ajax <strong>functions/api</strong> file.</em></p>\n\n<p><strong>Link:</strong> [<a href=\"https://stackoverflow.com/a/25719261/5431206]\">https://stackoverflow.com/a/25719261/5431206]</a></p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 362905,
"author": "Ali Raza",
"author_id": 111084,
"author_profile": "https://wordpress.stackexchange.com/users/111084",
"pm_score": 2,
"selected": false,
"text": "<p>Just add this code into your function.php, no need to update <code>.htaccess</code>, <code>/wp-includes/http.php</code> or any other core file.</p>\n<pre><code>function just_add_cors_http_header($headers){\n\n $headers['Access-Control-Allow-Origin'] = '*';\n\n return $headers;\n\n}\n\nadd_filter('wp_headers','just_add_cors_http_header');\n</code></pre>\n<p>Cheers!</p>\n"
}
] |
2015/08/18
|
[
"https://wordpress.stackexchange.com/questions/198950",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28069/"
] |
I use a `get_posts()` call with these arguments:
```
array(6) {
["include"]=> string(14) "1633,1634,1635"
["post_status"]=> string(3) "any"
["post_type"]=> string(10) "attachment"
["post_mime_type"]=> string(5) "image"
["order"]=> string(3) "ASC"
["orderby"]=> string(8) "post__in"
}
```
While **logged out** or logged in as an **Admin**, **it works fine** and returns the objects for 3 images. However, when the **user is just a Subscriber/Author/Editor/Contributor, it returns an empty array**.
All plugins enabled/disabled doesn't make a difference.
When switching the theme to an official WP theme, the **error no longer persists**.
I've dumped all hooks using [this](http://www.rarst.net/wordpress/debug-wordpress-hooks/) (one logged in with subscriber, one with admin), but I find no considerable difference. [Case A](http://https://gist.githubusercontent.com/Thefirsh/3175b3aab22d3edb61ee/raw/197dfcf21f563ff10704f7e73f3ee00ef5407c6b/a.txt) / [Case B](https://gist.githubusercontent.com/Thefirsh/3175b3aab22d3edb61ee/raw/197dfcf21f563ff10704f7e73f3ee00ef5407c6b/b.txt). I was assuming that the theme alters my arguments to an extent that there are no results for the altered query. If it's still the case, how and where should it do that?
The theme is Javo Directory.
|
Milo is correct.
For instance, go to your theme's functions.php file, and add the following:
```
add_filter( 'allowed_http_origins', 'add_allowed_origins' );
function add_allowed_origins( $origins ) {
$origins[] = 'https://site1.example.com';
$origins[] = 'https://site2.example.com';
return $origins;
}
```
Now an ajax call from <https://site1.example.com> to your site's ajax url will have the appropriate Access-Control-Allow-Origin header in the response. eg.
```
$.ajax({
url: 'https://site1.example.com/wp-admin/admin-ajax.php',
type: "POST",
data: {
...
},
success: function(doc) {
...
}
});
```
|
198,981 |
<p>So I have created a custom post type and under that taxonomy named "Category" which serves for categories. How can I list all the categories from there?</p>
|
[
{
"answer_id": 198985,
"author": "artist learning to code",
"author_id": 34034,
"author_profile": "https://wordpress.stackexchange.com/users/34034",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want to list them you can use the get_terms function:</p>\n\n<pre><code>$terms = get_terms( 'my_taxonomy' );\nif ( ! empty( $terms ) && ! is_wp_error( $terms ) ){\n echo '<ul>';\n foreach ( $terms as $term ) {\n echo '<li>' . $term->name . '</li>';\n\n }\n echo '</ul>';\n}\n</code></pre>\n\n<p>Read the codex, it has a lot of examples:\n<a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_terms</a></p>\n"
},
{
"answer_id": 261642,
"author": "Mixmastermiike",
"author_id": 58060,
"author_profile": "https://wordpress.stackexchange.com/users/58060",
"pm_score": 1,
"selected": false,
"text": "<p>nm I should start my own question...</p>\n\n<p>EDIT: I figured out what I was going to ask, but if anybody stumbles on this original question, here's what you can also do to just link to the categories after they are listed:</p>\n\n<pre><code><?php\n$terms = get_terms( 'nameofyourregisteredtaxonomygoeshere' );\n$count = count( $terms );\nif ( $count > 0 ) {\necho '<h3>Total Projects: '. $count . '</h3>';\necho '<ul>';\nforeach ( $terms as $term ) {\n echo '<li>';\n echo '<a href=\"' . esc_url( get_term_link( $term ) ) . '\" alt=\"'. esc_attr( sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $term->name ) ) . '\">' . $term->name . '</a>';\n echo '</li>';\n\n\n}\necho '</ul>';\n}\n?>\n</code></pre>\n"
}
] |
2015/08/18
|
[
"https://wordpress.stackexchange.com/questions/198981",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77967/"
] |
So I have created a custom post type and under that taxonomy named "Category" which serves for categories. How can I list all the categories from there?
|
If you just want to list them you can use the get\_terms function:
```
$terms = get_terms( 'my_taxonomy' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<ul>';
foreach ( $terms as $term ) {
echo '<li>' . $term->name . '</li>';
}
echo '</ul>';
}
```
Read the codex, it has a lot of examples:
<https://codex.wordpress.org/Function_Reference/get_terms>
|
199,070 |
<p>I'm trying to return a custom field as soon as a post gets published. I'm using the <code>publish_post</code> (or <code>{status}_{post_type}</code>) action, but it looks like the custom fields are created after the hook.</p>
<p>My code in <code>functions.php</code>:</p>
<pre><code>function create_recurring_posts( $ID, $post ) {
logMe(print_r(get_post_custom($ID), true));
}
add_action( 'publish_profile', 'create_recurring_posts', 10, 2 );
</code></pre>
<p>The <code>logMe()</code> function just logs the output to a file for testing purposes. My problem is, when I create the profile post, the only custom fields that get returned are <code>_edit_last</code> and <code>_edit_lock</code>. But when I view the page afterwards, where I have the same <code>get_post_custom()</code> function being ran, I see the other custom field I need.</p>
<p>I'm using Advanced Custom Fields for the field creation. Any help is appreciated.</p>
|
[
{
"answer_id": 199077,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 2,
"selected": false,
"text": "<p>Your action is triggered in <code>wp_transition_post_status()</code> which gets called by <code>wp_insert_post()</code> <em>before</em> the action <code>save_post</code> is triggered. <code>save_post</code> is the typical action to handle custom fields. ACF also works on this. </p>\n\n<p>Basically you have to wait until ACF is done with its stuff, means you'll have to hook to <code>save_post</code> with a priority > 10 or better use <code>wp_insert_post</code> which runs right after <code>save_post</code>.</p>\n\n<p>To track the post status transition, you can use a simple »log« like this:</p>\n\n<pre><code><?php\n\nnamespace WPSE199070;\n\nclass PublishedTransitionLog {\n\n /**\n * @type array\n */\n private $status_log = [];\n\n /**\n * logs a published post id \n * \n * @wp-hook publish_profile\n *\n * @param int $post_id\n */\n public function published_post( $post_id ) {\n\n $blog_id = get_current_blog_id();\n if ( ! isset( $this->status_log[ $blog_id ] ) )\n $this->status_log[ $blog_id ] = [];\n\n if ( in_array( $post_id, $this->status_log[ $blog_id ] ) )\n return;\n\n $this->status_log[ $blog_id ][] = $post_id;\n }\n\n /**\n * @param int $post_id\n * @return bool\n */\n public function post_published( $post_id ) {\n\n $blog_id = get_current_blog_id();\n if ( ! isset( $this->status_log[ $blog_id ] ) )\n return FALSE;\n\n return in_array( $post_id, $this->status_log[ $blog_id ] );\n }\n}\n\nclass PublishPostHandler {\n\n /**\n * @type PublishedTransitionLog\n */\n private $log;\n\n public function __construct( PublishedTransitionLog $log ) {\n\n $this->log = $log;\n }\n\n /**\n * @param int $post_id\n * @param \\WP_Post $post \n * @param bool $updated\n */\n public function update( $post_id, \\WP_Post $post, $updated ) {\n\n if ( ! $this->log->post_published( $post_id ) )\n return;\n\n // do your stuff here\n }\n}\n\n$transition_log = new PublishedTransitionLog;\n$handler = new PublisPostHandler( $transition_log );\n\nadd_action( 'publish_profile', array( $transition_log, 'published_post' ) );\nadd_action( 'wp_insert_post', array( $handler, 'update', 10, 3 ) );\n</code></pre>\n\n<p>Let me explain this. The first class, <code>PublishedTransitionLog</code> listens to the action <code>publish_profile</code> and stores each published post for each blog internally. It also provides a method to check if a post was published before.</p>\n\n<p>The second class should provide your logic and depends on the first class. If the post was not published it does just nothing. </p>\n\n<p>This way you can listen independently to tow different hooks. </p>\n"
},
{
"answer_id": 199095,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>@David explained why your code doesn't work and sketched out a solution (use <code>save_post</code> instead). However, you can \"chain\" hooks together so that you should still be able to use the transition filters to control execution:</p>\n\n<pre><code>function create_recurring_posts( $ID, $post ) {\n add_action(\n 'save_post',\n function() {\n // debug, since I don't have a `logMe()` function :)\n var_dump(print_r(get_post_custom($ID), true));\n die;\n },\n PHP_INT_MAX,\n 1\n ); \n}\nadd_action( 'publish_profile', 'create_recurring_posts', 10, 2 );\n</code></pre>\n"
}
] |
2015/08/19
|
[
"https://wordpress.stackexchange.com/questions/199070",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78023/"
] |
I'm trying to return a custom field as soon as a post gets published. I'm using the `publish_post` (or `{status}_{post_type}`) action, but it looks like the custom fields are created after the hook.
My code in `functions.php`:
```
function create_recurring_posts( $ID, $post ) {
logMe(print_r(get_post_custom($ID), true));
}
add_action( 'publish_profile', 'create_recurring_posts', 10, 2 );
```
The `logMe()` function just logs the output to a file for testing purposes. My problem is, when I create the profile post, the only custom fields that get returned are `_edit_last` and `_edit_lock`. But when I view the page afterwards, where I have the same `get_post_custom()` function being ran, I see the other custom field I need.
I'm using Advanced Custom Fields for the field creation. Any help is appreciated.
|
Your action is triggered in `wp_transition_post_status()` which gets called by `wp_insert_post()` *before* the action `save_post` is triggered. `save_post` is the typical action to handle custom fields. ACF also works on this.
Basically you have to wait until ACF is done with its stuff, means you'll have to hook to `save_post` with a priority > 10 or better use `wp_insert_post` which runs right after `save_post`.
To track the post status transition, you can use a simple »log« like this:
```
<?php
namespace WPSE199070;
class PublishedTransitionLog {
/**
* @type array
*/
private $status_log = [];
/**
* logs a published post id
*
* @wp-hook publish_profile
*
* @param int $post_id
*/
public function published_post( $post_id ) {
$blog_id = get_current_blog_id();
if ( ! isset( $this->status_log[ $blog_id ] ) )
$this->status_log[ $blog_id ] = [];
if ( in_array( $post_id, $this->status_log[ $blog_id ] ) )
return;
$this->status_log[ $blog_id ][] = $post_id;
}
/**
* @param int $post_id
* @return bool
*/
public function post_published( $post_id ) {
$blog_id = get_current_blog_id();
if ( ! isset( $this->status_log[ $blog_id ] ) )
return FALSE;
return in_array( $post_id, $this->status_log[ $blog_id ] );
}
}
class PublishPostHandler {
/**
* @type PublishedTransitionLog
*/
private $log;
public function __construct( PublishedTransitionLog $log ) {
$this->log = $log;
}
/**
* @param int $post_id
* @param \WP_Post $post
* @param bool $updated
*/
public function update( $post_id, \WP_Post $post, $updated ) {
if ( ! $this->log->post_published( $post_id ) )
return;
// do your stuff here
}
}
$transition_log = new PublishedTransitionLog;
$handler = new PublisPostHandler( $transition_log );
add_action( 'publish_profile', array( $transition_log, 'published_post' ) );
add_action( 'wp_insert_post', array( $handler, 'update', 10, 3 ) );
```
Let me explain this. The first class, `PublishedTransitionLog` listens to the action `publish_profile` and stores each published post for each blog internally. It also provides a method to check if a post was published before.
The second class should provide your logic and depends on the first class. If the post was not published it does just nothing.
This way you can listen independently to tow different hooks.
|
199,072 |
<p>This error only happened this morning as I updated my wordpress site to version 4.3. Two other sites on the same hosting ( and all using CPanel as an admin portal for the hosting) are not having any problem. On this one problematic site company.com though on the wordpress admin portal and the live site there is an error repeating several times at the top of the page, that is:</p>
<p><a href="https://i.stack.imgur.com/OfHNk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OfHNk.png" alt="The error continues down the page like this 9 times."></a></p>
<p><a href="https://i.stack.imgur.com/X4nMM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X4nMM.png" alt="The error page is then finished off with this error/line."></a></p>
<p>I have read up today on this and it is perhaps to do with upgrading from PHP4 to PHP5, although there is no problem with the other WP sites on the same server. I also disabled all the plugins on the site to test and the problem was still there. Short of restoring from a backup (which is not easy to do and can cause errors of its own) is there anyone else having this issue today/recently? </p>
<p>It does not help that the error message appears to suggest a solution itself before it is cut off at the end with </p>
<blockquote>
<p>Use...". The error message begins "company/public_html/wp-includes/ ...". The second line is "constructor method for WP_Widget is deprecated since version 4.3.0. </p>
</blockquote>
<p>Version 4.3 is the version that WP was updated to today. It seemingly has caused this error but I do not know how to fix it. </p>
<p>Any other information needed to answer this I'll be more than happy to provide.</p>
|
[
{
"answer_id": 199098,
"author": "bishless",
"author_id": 31169,
"author_profile": "https://wordpress.stackexchange.com/users/31169",
"pm_score": 0,
"selected": false,
"text": "<p>I was in a similar boat (first had to fix some custom widgets in a theme), but had the message even after fixing them.</p>\n\n<p>Switched to a default theme: still had the same error.</p>\n\n<p><strong>TL;DR</strong>: Started deactivating plugins one-by-one... found <a href=\"https://wordpress.org/plugins/list-category-posts/\" rel=\"nofollow\">https://wordpress.org/plugins/list-category-posts/</a> was the culprit.</p>\n"
},
{
"answer_id": 199118,
"author": "tjbp",
"author_id": 78053,
"author_profile": "https://wordpress.stackexchange.com/users/78053",
"pm_score": 2,
"selected": false,
"text": "<p>The error isn't actually caused by your PHP version (PHP 4 constructors won't be removed until PHP 7) - it's a warning produced by WordPress in preparation for this. Each repetition of the error represents a plugin using the outdated code.</p>\n\n<p>Until your plugins' authors update them, you can run the following shell command on a Linux system to find the old constructor calls:</p>\n\n<pre><code>grep -R \"WP_Widget\\(\" /path/to/your/wp/install\n</code></pre>\n\n<p>This will give you a list of files that you can either modify on the command line, or use WP's plugin editor. Matched strings - mostly <code>parent::WP_Widget(args)</code> should be changed to <code>parent::__construct(args)</code>.</p>\n"
},
{
"answer_id": 199893,
"author": "Emanuel David Brigham Vitorino",
"author_id": 73704,
"author_profile": "https://wordpress.stackexchange.com/users/73704",
"pm_score": -1,
"selected": false,
"text": "<p>Wordpress Debug mode can produce these kinds of messages.</p>\n\n<p>I had the same problem on one of my sites.</p>\n\n<p>Maybe you have this line of code on your wp-config.php file:</p>\n\n<pre>define('WP_DEBUG', true);</pre>\n\n<p>Try changing it to:</p>\n\n<pre>define('WP_DEBUG', false);</pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 199951,
"author": "Lorenzo Zottar",
"author_id": 78458,
"author_profile": "https://wordpress.stackexchange.com/users/78458",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to keep WP_DEBUG on and do you want to hide this specific type of error, put in your theme functions.php this line:</p>\n\n<pre><code>add_filter('deprecated_constructor_trigger_error', '__return_false');\n</code></pre>\n\n<p>This will prevent this kind of error to be displayed.</p>\n\n<p>I hope it helps :)</p>\n"
},
{
"answer_id": 200273,
"author": "studiobovenkamer",
"author_id": 78635,
"author_profile": "https://wordpress.stackexchange.com/users/78635",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress is giving you a notice that this construct is deprecated, because it is preparing for PHP7. You should check your custom code and any plug-ins for the use of the WP_Widget construct. There are (still) a lot of plug-ins that need to update their code.</p>\n\n<p>Here is a list of plug-ins that use the deprecated WP_Widget construct:\n<a href=\"https://gist.github.com/chriscct7/d7d077afb01011b1839d\" rel=\"nofollow\">https://gist.github.com/chriscct7/d7d077afb01011b1839d</a></p>\n\n<p>You can either wait for the plug-in authors to update their code or you can change the code of plug-ins (temporarily) yourself. There is a good summary about changing your code (by <a href=\"https://gist.github.com/chriscct7/d7d077afb01011b1839d\" rel=\"nofollow\">Chris Christoff</a>)</p>\n\n<blockquote>\n <p>Basically instead of doing these:</p>\n \n <ul>\n <li><code>{classname}::{classname}()</code> as in <code>WP_Widget::WP_Widget()</code> or</li>\n <li><code>parent::{classname}()</code> as in <code>parent::WP_Widget()</code> or</li>\n <li><code>{object}->{classname}()</code> as in <code>{object}->WP_Widget()</code> (a more specific\n example: <code>$this->WP_Widget()</code>)</li>\n </ul>\n \n <p>Do:</p>\n \n <ul>\n <li><code>parent::__construct()</code> to call the parent class constructor from a child class </li>\n <li><code>$var = new {class name}()</code> as in <code>$var = new My_Widget_Class()</code> to hold an instance of a widget (don't use <code>My_Widget_Class</code> as the name of your widget class though, use something more unique and applicable to avoid class name conflicts with other\n plugins.</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 203657,
"author": "MikeiLL",
"author_id": 48604,
"author_profile": "https://wordpress.stackexchange.com/users/48604",
"pm_score": 2,
"selected": false,
"text": "<p>It seems that it's not <code>WP_Widget</code> that's being updated, but the way it is referenced.</p>\n\n<p>I believe what we want is to go from this:</p>\n\n<pre><code>class mZ_Mindbody_day_schedule extends WP_Widget {\n\n function mZ_Mindbody_day_schedule() {\n $widget_ops = array(\n 'classname' => 'mZ_Mindbody_day_schedule_class',\n 'description' => __('Display class schedule for current day.', 'mz-mindbody-api')\n );\n $this->WP_Widget('mZ_Mindbody_day_schedule', __('Today\\'s MindBody Schedule', 'mz-mindbody-api'),\n $widget_ops );\n } \n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>class mZ_Mindbody_day_schedule extends WP_Widget {\n\n function mZ_Mindbody_day_schedule() {\n $widget_ops = array(\n 'classname' => 'mZ_Mindbody_day_schedule_class',\n 'description' => __('Display class schedule for current day.', 'mz-mindbody-api')\n );\n parent::__construct('mZ_Mindbody_day_schedule', __('Today\\'s MindBody Schedule', 'mz-mindbody-api'),\n $widget_ops );\n } \n</code></pre>\n\n<p>Where it's only line six of the above code that gets updated.</p>\n"
}
] |
2015/08/19
|
[
"https://wordpress.stackexchange.com/questions/199072",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77953/"
] |
This error only happened this morning as I updated my wordpress site to version 4.3. Two other sites on the same hosting ( and all using CPanel as an admin portal for the hosting) are not having any problem. On this one problematic site company.com though on the wordpress admin portal and the live site there is an error repeating several times at the top of the page, that is:
[](https://i.stack.imgur.com/OfHNk.png)
[](https://i.stack.imgur.com/X4nMM.png)
I have read up today on this and it is perhaps to do with upgrading from PHP4 to PHP5, although there is no problem with the other WP sites on the same server. I also disabled all the plugins on the site to test and the problem was still there. Short of restoring from a backup (which is not easy to do and can cause errors of its own) is there anyone else having this issue today/recently?
It does not help that the error message appears to suggest a solution itself before it is cut off at the end with
>
> Use...". The error message begins "company/public\_html/wp-includes/ ...". The second line is "constructor method for WP\_Widget is deprecated since version 4.3.0.
>
>
>
Version 4.3 is the version that WP was updated to today. It seemingly has caused this error but I do not know how to fix it.
Any other information needed to answer this I'll be more than happy to provide.
|
The error isn't actually caused by your PHP version (PHP 4 constructors won't be removed until PHP 7) - it's a warning produced by WordPress in preparation for this. Each repetition of the error represents a plugin using the outdated code.
Until your plugins' authors update them, you can run the following shell command on a Linux system to find the old constructor calls:
```
grep -R "WP_Widget\(" /path/to/your/wp/install
```
This will give you a list of files that you can either modify on the command line, or use WP's plugin editor. Matched strings - mostly `parent::WP_Widget(args)` should be changed to `parent::__construct(args)`.
|
199,086 |
<p>What is the best way to pass some information from <code>functions.php</code> to a plugin?</p>
<p>I need to give a user the ability to <em>pass</em> a piece of data <em>from</em> their <code>functions.php</code> file <em>to</em> my plugin. (It can be any data, just something that I can check for; it can be a variable's value, or even the fact that a variable was set or a function was defined.) </p>
<p>I tried the suggestion found here:</p>
<p><a href="https://wordpress.stackexchange.com/questions/169284/pass-a-value-from-outside-to-a-plugin-variable">Pass A Value From Outside To A Plugin Variable</a></p>
<p>I plugged in that code verbatim:</p>
<p><em>On your plugin :</em></p>
<pre><code> $value = 0;
$value = apply_filter('get_value_from_function', $value);
</code></pre>
<p><em>Then on <code>functions.php</code></em></p>
<pre><code>add_filter('get_value_from_function', 'my_special_value_treatment', 10, 1);
function my_special_value_treatment ($value){
return 1;
}
</code></pre>
<p>But that results in an error: </p>
<blockquote>
<p>Fatal error: Call to undefined function apply_filter() in /pathtomyplugin/my-plugin-name/my-plugin-name.php on line 93</p>
</blockquote>
<p>I don't understand why that fails. What is the best way to do this?</p>
<p><em>Edited with this addition:</em></p>
<p>After changing it to <code>apply_filters()</code>, this still happens... In my plugin:</p>
<pre><code>$value = 0;
$value = apply_filters('get_value_from_function', $value);
if ($value===0) {
$test_info = 'not_passed';
} else {
$test_info = 'passed';
};
// $test_info is not_passed
</code></pre>
|
[
{
"answer_id": 199087,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 0,
"selected": false,
"text": "<p>This is the correct method - except the function is <code>apply_filters</code>, not apply_filter. Hence your error.</p>\n"
},
{
"answer_id": 199094,
"author": "webtoure",
"author_id": 72992,
"author_profile": "https://wordpress.stackexchange.com/users/72992",
"pm_score": 3,
"selected": true,
"text": "<p>Plugins are loaded before the theme which means that your <code>apply_filters</code> won't have any actual callbacks registered to it. Instead, you need to call your <code>apply_filters</code> sometime after the theme has been loaded. Something like this:</p>\n\n<pre><code>/* Your plugin's file: */\n\nadd_action( 'init', 'my_lovely_funky_filters' );\n\nfunction my_lovely_funky_filters() {\n /* Fire our callbacks */\n $value = 0;\n $value = apply_filters( 'get_value_from_function', $value );\n\n /* Check your $value now */\n /* echo \"<pre>{$value}</pre>\"; */\n}\n\n/* Your functions.php file */\n\nadd_filter( 'get_value_from_function', 'my_special_value_treatment', 10, 1 );\nfunction my_special_value_treatment( $value ) {\n /* A little more interesting */\n return (int)$value + 1;\n}\n</code></pre>\n"
}
] |
2015/08/19
|
[
"https://wordpress.stackexchange.com/questions/199086",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60192/"
] |
What is the best way to pass some information from `functions.php` to a plugin?
I need to give a user the ability to *pass* a piece of data *from* their `functions.php` file *to* my plugin. (It can be any data, just something that I can check for; it can be a variable's value, or even the fact that a variable was set or a function was defined.)
I tried the suggestion found here:
[Pass A Value From Outside To A Plugin Variable](https://wordpress.stackexchange.com/questions/169284/pass-a-value-from-outside-to-a-plugin-variable)
I plugged in that code verbatim:
*On your plugin :*
```
$value = 0;
$value = apply_filter('get_value_from_function', $value);
```
*Then on `functions.php`*
```
add_filter('get_value_from_function', 'my_special_value_treatment', 10, 1);
function my_special_value_treatment ($value){
return 1;
}
```
But that results in an error:
>
> Fatal error: Call to undefined function apply\_filter() in /pathtomyplugin/my-plugin-name/my-plugin-name.php on line 93
>
>
>
I don't understand why that fails. What is the best way to do this?
*Edited with this addition:*
After changing it to `apply_filters()`, this still happens... In my plugin:
```
$value = 0;
$value = apply_filters('get_value_from_function', $value);
if ($value===0) {
$test_info = 'not_passed';
} else {
$test_info = 'passed';
};
// $test_info is not_passed
```
|
Plugins are loaded before the theme which means that your `apply_filters` won't have any actual callbacks registered to it. Instead, you need to call your `apply_filters` sometime after the theme has been loaded. Something like this:
```
/* Your plugin's file: */
add_action( 'init', 'my_lovely_funky_filters' );
function my_lovely_funky_filters() {
/* Fire our callbacks */
$value = 0;
$value = apply_filters( 'get_value_from_function', $value );
/* Check your $value now */
/* echo "<pre>{$value}</pre>"; */
}
/* Your functions.php file */
add_filter( 'get_value_from_function', 'my_special_value_treatment', 10, 1 );
function my_special_value_treatment( $value ) {
/* A little more interesting */
return (int)$value + 1;
}
```
|
199,111 |
<p>I have a little problem that I can not solve. I have a website "multi-site" system with ADS script. I wish I could enter leaderboard banner.</p>
<p>This is an example script:</p>
<pre><code><div id=""><script src=""></script><script src="" ></script></div>
</code></pre>
<p>i have insert this code script is work, but the problem is that it appears the entire network, instead I wish that each script is separate and in each subdomain change advertising by area.</p>
<p>it correct this recall:</p>
<pre><code><?php
if ( get_current_blog_id() === 1 ) {
</code></pre>
<p>how can I integrate the php code with the script?</p>
|
[
{
"answer_id": 199087,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 0,
"selected": false,
"text": "<p>This is the correct method - except the function is <code>apply_filters</code>, not apply_filter. Hence your error.</p>\n"
},
{
"answer_id": 199094,
"author": "webtoure",
"author_id": 72992,
"author_profile": "https://wordpress.stackexchange.com/users/72992",
"pm_score": 3,
"selected": true,
"text": "<p>Plugins are loaded before the theme which means that your <code>apply_filters</code> won't have any actual callbacks registered to it. Instead, you need to call your <code>apply_filters</code> sometime after the theme has been loaded. Something like this:</p>\n\n<pre><code>/* Your plugin's file: */\n\nadd_action( 'init', 'my_lovely_funky_filters' );\n\nfunction my_lovely_funky_filters() {\n /* Fire our callbacks */\n $value = 0;\n $value = apply_filters( 'get_value_from_function', $value );\n\n /* Check your $value now */\n /* echo \"<pre>{$value}</pre>\"; */\n}\n\n/* Your functions.php file */\n\nadd_filter( 'get_value_from_function', 'my_special_value_treatment', 10, 1 );\nfunction my_special_value_treatment( $value ) {\n /* A little more interesting */\n return (int)$value + 1;\n}\n</code></pre>\n"
}
] |
2015/08/19
|
[
"https://wordpress.stackexchange.com/questions/199111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78038/"
] |
I have a little problem that I can not solve. I have a website "multi-site" system with ADS script. I wish I could enter leaderboard banner.
This is an example script:
```
<div id=""><script src=""></script><script src="" ></script></div>
```
i have insert this code script is work, but the problem is that it appears the entire network, instead I wish that each script is separate and in each subdomain change advertising by area.
it correct this recall:
```
<?php
if ( get_current_blog_id() === 1 ) {
```
how can I integrate the php code with the script?
|
Plugins are loaded before the theme which means that your `apply_filters` won't have any actual callbacks registered to it. Instead, you need to call your `apply_filters` sometime after the theme has been loaded. Something like this:
```
/* Your plugin's file: */
add_action( 'init', 'my_lovely_funky_filters' );
function my_lovely_funky_filters() {
/* Fire our callbacks */
$value = 0;
$value = apply_filters( 'get_value_from_function', $value );
/* Check your $value now */
/* echo "<pre>{$value}</pre>"; */
}
/* Your functions.php file */
add_filter( 'get_value_from_function', 'my_special_value_treatment', 10, 1 );
function my_special_value_treatment( $value ) {
/* A little more interesting */
return (int)$value + 1;
}
```
|
199,114 |
<p>I have a custom post type that is an Event.</p>
<p>I'm trying to query those Events and only return Events that are in the current month or later. So the event could be in the past, but it has to be in the same month. The event date is a custom field.</p>
<p>So right now I would only want events that were in the month of August or later, and no events prior to August.</p>
<p>Here's my current query, ordered from oldest to newest:</p>
<pre><code>$custom_post_type = 'event';
$args = array(
'post_type' => $custom_post_type,
'post_status' => 'publish',
'meta_key' => 'event_date_and_time',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => -1
);
$events = get_posts($args);
</code></pre>
|
[
{
"answer_id": 199122,
"author": "Marek",
"author_id": 54031,
"author_profile": "https://wordpress.stackexchange.com/users/54031",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>meta_query</code>, if you date information is saved in custom field. Like this:</p>\n\n<pre><code>$args = array(\n 'post_type' => $custom_post_type,\n 'posts_per_page' => -1,\n 'meta_query' => array(\n array(\n 'key' => 'event_date_and_time',\n 'value' => current_time('Ymd'),\n 'compare' => '>='\n )\n ),\n 'orderby' => 'meta_value_num',\n 'order' => 'ASC'\n);\n</code></pre>\n\n<p>This code suppose you date is saved in YYYYMMDD format (20150820). And it shows post from today to future, so you will have to change <code>value</code> to \"first day of current month\".</p>\n"
},
{
"answer_id": 199123,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>meta_query</code> argument in the array.</p>\n\n<pre><code>$custom_post_type = 'event';\n\n$args = array(\n 'post_type' => $custom_post_type,\n 'post_status' => 'publish',\n 'meta_key' => 'event_date_and_time',\n 'orderby' => 'meta_value_num',\n 'order' => 'ASC',\n 'posts_per_page' => -1\n 'meta_query' => array(\n array(\n 'key' => 'event_date_and_time',\n 'value' => date(\"Y-m-1\"); // starting from 1st of current month. This will change based on how you store dates.\n 'compare' => '>=',\n 'type' => 'NUMERIC,' // Let WordPress know we're working with numbers\n )\n )\n);\n\n$events = get_posts($args);\n</code></pre>\n"
}
] |
2015/08/20
|
[
"https://wordpress.stackexchange.com/questions/199114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75134/"
] |
I have a custom post type that is an Event.
I'm trying to query those Events and only return Events that are in the current month or later. So the event could be in the past, but it has to be in the same month. The event date is a custom field.
So right now I would only want events that were in the month of August or later, and no events prior to August.
Here's my current query, ordered from oldest to newest:
```
$custom_post_type = 'event';
$args = array(
'post_type' => $custom_post_type,
'post_status' => 'publish',
'meta_key' => 'event_date_and_time',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => -1
);
$events = get_posts($args);
```
|
You can use `meta_query`, if you date information is saved in custom field. Like this:
```
$args = array(
'post_type' => $custom_post_type,
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'event_date_and_time',
'value' => current_time('Ymd'),
'compare' => '>='
)
),
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
```
This code suppose you date is saved in YYYYMMDD format (20150820). And it shows post from today to future, so you will have to change `value` to "first day of current month".
|
199,141 |
<p>I have some problems to asign a class to tag with wp_nav_menu() instead of asign the class to the tag it creates a and asign the class to that one.</p>
<p>My register_nav_menu function:</p>
<pre><code> function register_primary_menu() {
register_nav_menu('primary-menu', __('Primary Menu'));
}
add_action('init', 'register_primary_menu');
</code></pre>
<p>wp_nav_menu:</p>
<pre><code><?php
$defaults = array(
'theme_location' => 'primary-menu',
'menu' => '',
'container' => 'flase',
'container_class' => '',
'container_id' => '',
'menu_class' => 'nav navbar-nav',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '<li>',
'after' => '</li>',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
wp_nav_menu( $defaults );
?>
</code></pre>
<p>What I want is this:</p>
<pre><code><ul class="nav navbar-nav">
<li><a href="#">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
</code></pre>
<p>And what I get is this:</p>
<pre><code><div class="nav navbar-nav">
<ul>
<li class="page_item page-item-56"><a href="[URL]">Page 1</a></li>
<li class="page_item page-item-58"><a href="[URL]">Page 2</a></li>
<li class="page_item page-item-60"><a href="[URL]">Page 3</a></li>
<li class="page_item page-item-2"><a href="[URL]">Sample Page</a></li>
</ul>
</div>
</code></pre>
|
[
{
"answer_id": 199143,
"author": "passatgt",
"author_id": 8038,
"author_profile": "https://wordpress.stackexchange.com/users/8038",
"pm_score": -1,
"selected": true,
"text": "<p>Make sure your menu does setup correctly in that location in Appearance / Menus, unless it wont display that class. After you set the theme location to Primary Menu, it should work fine. No idea why, guess its a bug in WordPress.</p>\n\n<p>Also fix the typo: <code>'container' => false</code></p>\n"
},
{
"answer_id": 293936,
"author": "Chris Eckman",
"author_id": 136728,
"author_profile": "https://wordpress.stackexchange.com/users/136728",
"pm_score": 2,
"selected": false,
"text": "<p>You need to set 'container' => 'ul'. </p>\n"
},
{
"answer_id": 318875,
"author": "Morgan Old",
"author_id": 153855,
"author_profile": "https://wordpress.stackexchange.com/users/153855",
"pm_score": -1,
"selected": false,
"text": "<p>I have same problem and i fix it. My theme_location i set primary in the functions.php file, but i don't set that location in the wp admin -> Appearance and in the Menu Settings set your location. </p>\n\n<p><a href=\"https://i.stack.imgur.com/pTaLb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pTaLb.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2015/08/20
|
[
"https://wordpress.stackexchange.com/questions/199141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66256/"
] |
I have some problems to asign a class to tag with wp\_nav\_menu() instead of asign the class to the tag it creates a and asign the class to that one.
My register\_nav\_menu function:
```
function register_primary_menu() {
register_nav_menu('primary-menu', __('Primary Menu'));
}
add_action('init', 'register_primary_menu');
```
wp\_nav\_menu:
```
<?php
$defaults = array(
'theme_location' => 'primary-menu',
'menu' => '',
'container' => 'flase',
'container_class' => '',
'container_id' => '',
'menu_class' => 'nav navbar-nav',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '<li>',
'after' => '</li>',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
wp_nav_menu( $defaults );
?>
```
What I want is this:
```
<ul class="nav navbar-nav">
<li><a href="#">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
```
And what I get is this:
```
<div class="nav navbar-nav">
<ul>
<li class="page_item page-item-56"><a href="[URL]">Page 1</a></li>
<li class="page_item page-item-58"><a href="[URL]">Page 2</a></li>
<li class="page_item page-item-60"><a href="[URL]">Page 3</a></li>
<li class="page_item page-item-2"><a href="[URL]">Sample Page</a></li>
</ul>
</div>
```
|
Make sure your menu does setup correctly in that location in Appearance / Menus, unless it wont display that class. After you set the theme location to Primary Menu, it should work fine. No idea why, guess its a bug in WordPress.
Also fix the typo: `'container' => false`
|
199,146 |
<p>How do I query for a specific user role?</p>
<pre><code>if (is_user_logged_in() && user_role == "user") {}
</code></pre>
<p>The part I'm unsure about is user_role.</p>
<p><strong>Is there a way I can ask WordPress to check for a specific user role by name/string</strong>?</p>
|
[
{
"answer_id": 199158,
"author": "theHubi",
"author_id": 63130,
"author_profile": "https://wordpress.stackexchange.com/users/63130",
"pm_score": 0,
"selected": false,
"text": "<p>You can make WordPress query for a certain user role by using <code>current_user_can(\"role_name\")</code>.</p>\n\n<p>Thanks to <a href=\"https://wordpress.stackexchange.com/users/22728/mayeenul-islam\">Mayeenul Islam</a> for providing the solution!</p>\n"
},
{
"answer_id": 199159,
"author": "Pooja Mistry",
"author_id": 71675,
"author_profile": "https://wordpress.stackexchange.com/users/71675",
"pm_score": 2,
"selected": true,
"text": "<p>You can check for specific user role using following code - </p>\n\n<pre><code>if (is_user_logged_in() && current_user_can('administrator')) {}\n</code></pre>\n\n<p>The function current_user_can() takes role name as parameter. <br>\nFor more info - <a href=\"https://codex.wordpress.org/Function_Reference/current_user_can/\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/current_user_can/</a></p>\n"
}
] |
2015/08/20
|
[
"https://wordpress.stackexchange.com/questions/199146",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63130/"
] |
How do I query for a specific user role?
```
if (is_user_logged_in() && user_role == "user") {}
```
The part I'm unsure about is user\_role.
**Is there a way I can ask WordPress to check for a specific user role by name/string**?
|
You can check for specific user role using following code -
```
if (is_user_logged_in() && current_user_can('administrator')) {}
```
The function current\_user\_can() takes role name as parameter.
For more info - <https://codex.wordpress.org/Function_Reference/current_user_can/>
|
199,160 |
<p>Im have a little issue querying a custom post type by category using the_title(); </p>
<p>The reason why im doing it like this is because the title is the same as the category name.</p>
<pre><code>$args = array('post_type' => 'Testimonials', 'order' => 'ASC', 'category_name' =>the_title());
</code></pre>
<p>However with this im not getting a thing i have also tried this: </p>
<pre><code>$title = the_title();
$args = array('post_type' => 'Testimonials', 'order' => 'ASC', 'category_name' =>$title);
</code></pre>
<p>Any help?</p>
|
[
{
"answer_id": 199162,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 1,
"selected": false,
"text": "<p>Look at the declaration of the function <code>the_title()</code>, it prints the title, if the third parameter <code>$echo</code> is set to <code>TRUE</code> which is the default:</p>\n\n<pre><code>/**\n * Display or retrieve the current post title with optional content.\n *\n * @since 0.71\n *\n * @param string $before Optional. Content to prepend to the title.\n * @param string $after Optional. Content to append to the title.\n * @param bool $echo Optional, default to true.Whether to display or return.\n * @return null|string Null on no title. String if $echo parameter is false.\n */\nfunction the_title($before = '', $after = '', $echo = true) {\n $title = get_the_title();\n\n if ( strlen($title) == 0 )\n return;\n\n $title = $before . $title . $after;\n\n if ( $echo )\n echo $title;\n else\n return $title;\n}\n</code></pre>\n\n<p>So either you use <code>the_title( '', '', FALSE )</code> or even better <code>get_the_title()</code> because it makes the code better readable:</p>\n\n<pre><code>$title = get_the_title();\n$args = array(\n 'post_type' => 'Testimonials',\n 'order' => 'ASC',\n 'category_name' => $title\n);\n</code></pre>\n"
},
{
"answer_id": 199166,
"author": "user78072",
"author_id": 78072,
"author_profile": "https://wordpress.stackexchange.com/users/78072",
"pm_score": 0,
"selected": false,
"text": "<p>I think that the whole concept of this question is a little bit wrong. The thing about custom post types is that they don't have categories like regular posts. They have taxonomies and terms. In fact regular categories are also a taxonomy for regular posts.</p>\n\n<p>So answering your questions, you need to know the name of the taxonomy first.\nThe simple way is to hover over taxonomy menu item in WordPress dashboard using Chrome. The taxonomy will appear in a lower left corner of the screen. See screenshot <a href=\"https://i.stack.imgur.com/vp38u.jpg\" rel=\"nofollow noreferrer\">http://i.stack.imgur.com/vp38u.jpg</a></p>\n\n<p>Then, when you know the taxonomy name, you can do something like this:</p>\n\n<pre><code>$term = $post->post_name;\n\n$args = array(\n 'post_type' => 'Testimonials',\n 'order' => 'ASC',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'your_taxonomy_name',\n 'field' => 'slug',\n 'terms' => $term\n )\n )\n);\n</code></pre>\n\n<p>But this thing will only work if the name of the term you are trying get is the same with the slug of the current post you are on.</p>\n"
}
] |
2015/08/20
|
[
"https://wordpress.stackexchange.com/questions/199160",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67253/"
] |
Im have a little issue querying a custom post type by category using the\_title();
The reason why im doing it like this is because the title is the same as the category name.
```
$args = array('post_type' => 'Testimonials', 'order' => 'ASC', 'category_name' =>the_title());
```
However with this im not getting a thing i have also tried this:
```
$title = the_title();
$args = array('post_type' => 'Testimonials', 'order' => 'ASC', 'category_name' =>$title);
```
Any help?
|
Look at the declaration of the function `the_title()`, it prints the title, if the third parameter `$echo` is set to `TRUE` which is the default:
```
/**
* Display or retrieve the current post title with optional content.
*
* @since 0.71
*
* @param string $before Optional. Content to prepend to the title.
* @param string $after Optional. Content to append to the title.
* @param bool $echo Optional, default to true.Whether to display or return.
* @return null|string Null on no title. String if $echo parameter is false.
*/
function the_title($before = '', $after = '', $echo = true) {
$title = get_the_title();
if ( strlen($title) == 0 )
return;
$title = $before . $title . $after;
if ( $echo )
echo $title;
else
return $title;
}
```
So either you use `the_title( '', '', FALSE )` or even better `get_the_title()` because it makes the code better readable:
```
$title = get_the_title();
$args = array(
'post_type' => 'Testimonials',
'order' => 'ASC',
'category_name' => $title
);
```
|
199,182 |
<p>I've a pretty basic problem that I'm surprised WP doesn't have a native solution for (unless I'm overlooking something, hopefully). </p>
<p>I've a WP site with <code>static page</code> set as front page in reading setting. In a plugin code, I'm trying to determine whether WP is displaying the front page and add a class to <code>$classes</code> array if so is true. I'm using following code to accomplish it </p>
<pre><code>add_filter('body_class', function($classes){
if(is_front_page() || is_home()){
$classes[] = 'home-page';
}
return $classes;
});
</code></pre>
<p>I'm using both <code>is_front_page()</code> and <code>is_home()</code> in case the front page setting changes from static page to blog layout in future. </p>
<p>The issue I'm encountering is that this code adds <code>home-page</code> class to <code>body</code> even on <code>wp-signup.php</code> page. </p>
<p>Inspecting the code reveals that <code>is_front_page()</code> calls <code>WP_Query::is_front_page()</code> , which essentially returns results of <code>WP_Query::is_page(get_option('page_on_front'))</code>. So the root of the problem is that <code>wp-signup.php</code> qualifies as the page (id) returned by <code>get_option('page_on_front')</code> (<em>which returns <code>ID</code> of the static page set as front page in settings > reading</em>). </p>
<p><code>WP_Query::is_page()</code> uses <code>WP_Query::get_queried_object()</code> internally to decide whether current page is the page present in method arguments. In <code>wp-signup.php</code> case, the code that sets the current queried object is as following </p>
<pre><code>/*...other code... */
elseif ( $this->is_singular && ! empty( $this->post ) ) {
$this->queried_object = $this->post;
$this->queried_object_id = (int) $this->post->ID;
}
/*...other code... */
</code></pre>
<p>This shows that wordpress, for some reason, queries the front page in order to display <code>wp-signup.php</code> and raises following questions. </p>
<ul>
<li>Why <code>is_front_page()</code> is returning wrong results?</li>
<li>AFAIK <code>wp-signup.php</code> can never be set as home page using Wordpress administrator setting then why wordpress code isn't bailing out just by checking <code>PHP_SELF</code> or <code>REQUEST_URI</code>?</li>
<li>Why does WP_Query have current home page in <code>$this->post</code> at this point? </li>
</ul>
<p>I've ruled out <em>plugin issue</em> by removing the plugins (and mu-plugins) directory. It still qualifies <code>wp-signup.php</code> as front page where it doesn't for any other page. </p>
<p>Any help regarding this issue will be greatly appreciated.</p>
<p><strong>Update</strong><br>
I'm using WP verison 4.2.4 and it is a multisite setup.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 199676,
"author": "jim.duck",
"author_id": 78337,
"author_profile": "https://wordpress.stackexchange.com/users/78337",
"pm_score": -1,
"selected": false,
"text": "<p>WordPress uses different templates for pages on your site. If you have a page.php template in your theme, that will be used to display your pages. If you have a single.php, that will be used to display your single posts. index.php or home.php would display your home page, or page.php if you have a certain page selected as the home page through the reading options.</p>\n\n<p>So, your conditional statement:</p>\n\n<pre><code><?php if (is_front_page()){ ?>\n<p>Home Page</p>\n<?php else { ?>\n<p>Not Home Page</p>\n<?php } ?>\n?>\n</code></pre>\n\n<p>Would only really be useful in the header.php or the footer.php file- or in page.php if you have a certain page selected in the reading options.</p>\n"
},
{
"answer_id": 202112,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>Just speculation, but I wonder if you're running into an anonymous function problem. Anonymous functions are allowed in WP, and usually work fine (presuming updated PHP), but, if you search around you'll find reports of suspected bugs or at least of unexpected behavior. </p>\n\n<p>For that matter, I'm not sure that I've ever seen an anonymous function used as an example in the WordPress Codex, and I can't recall ever running across one before in theme and plug-in code. Of course, I've not had my eye out for anon functions, but, still, I think the above function will almost always be written in some version of the more familiar two-part format - ie:</p>\n\n<pre><code>add_filter('body_class', 'ejay_add_home_class');\n\nfunction ejay_add_home_class($classes) {\n\n if (is_front_page() || is_home()) {\n\n $classes[] = 'home-page';\n }\n\n return $classes;\n} \n</code></pre>\n\n<p>So, as an experiment, I'd try the above more \"conventional\" format, and also try it with a designated priority higher or lower than 10. If attaching multiple anonymous functions to the same filter, I'd give them different priorities, or use an array (example here: <a href=\"http://snippets.khromov.se/adding-multiple-actions-and-filters-using-anonymous-functions-in-wordpress/\" rel=\"nofollow\">http://snippets.khromov.se/adding-multiple-actions-and-filters-using-anonymous-functions-in-wordpress/</a> ), or write each one of them as named two-parters, too. </p>\n\n<p>In truth, I find the slightly lengthier 2-part way easier to read, track, and adjust anyway.</p>\n"
}
] |
2015/08/20
|
[
"https://wordpress.stackexchange.com/questions/199182",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56722/"
] |
I've a pretty basic problem that I'm surprised WP doesn't have a native solution for (unless I'm overlooking something, hopefully).
I've a WP site with `static page` set as front page in reading setting. In a plugin code, I'm trying to determine whether WP is displaying the front page and add a class to `$classes` array if so is true. I'm using following code to accomplish it
```
add_filter('body_class', function($classes){
if(is_front_page() || is_home()){
$classes[] = 'home-page';
}
return $classes;
});
```
I'm using both `is_front_page()` and `is_home()` in case the front page setting changes from static page to blog layout in future.
The issue I'm encountering is that this code adds `home-page` class to `body` even on `wp-signup.php` page.
Inspecting the code reveals that `is_front_page()` calls `WP_Query::is_front_page()` , which essentially returns results of `WP_Query::is_page(get_option('page_on_front'))`. So the root of the problem is that `wp-signup.php` qualifies as the page (id) returned by `get_option('page_on_front')` (*which returns `ID` of the static page set as front page in settings > reading*).
`WP_Query::is_page()` uses `WP_Query::get_queried_object()` internally to decide whether current page is the page present in method arguments. In `wp-signup.php` case, the code that sets the current queried object is as following
```
/*...other code... */
elseif ( $this->is_singular && ! empty( $this->post ) ) {
$this->queried_object = $this->post;
$this->queried_object_id = (int) $this->post->ID;
}
/*...other code... */
```
This shows that wordpress, for some reason, queries the front page in order to display `wp-signup.php` and raises following questions.
* Why `is_front_page()` is returning wrong results?
* AFAIK `wp-signup.php` can never be set as home page using Wordpress administrator setting then why wordpress code isn't bailing out just by checking `PHP_SELF` or `REQUEST_URI`?
* Why does WP\_Query have current home page in `$this->post` at this point?
I've ruled out *plugin issue* by removing the plugins (and mu-plugins) directory. It still qualifies `wp-signup.php` as front page where it doesn't for any other page.
Any help regarding this issue will be greatly appreciated.
**Update**
I'm using WP verison 4.2.4 and it is a multisite setup.
Thanks.
|
Just speculation, but I wonder if you're running into an anonymous function problem. Anonymous functions are allowed in WP, and usually work fine (presuming updated PHP), but, if you search around you'll find reports of suspected bugs or at least of unexpected behavior.
For that matter, I'm not sure that I've ever seen an anonymous function used as an example in the WordPress Codex, and I can't recall ever running across one before in theme and plug-in code. Of course, I've not had my eye out for anon functions, but, still, I think the above function will almost always be written in some version of the more familiar two-part format - ie:
```
add_filter('body_class', 'ejay_add_home_class');
function ejay_add_home_class($classes) {
if (is_front_page() || is_home()) {
$classes[] = 'home-page';
}
return $classes;
}
```
So, as an experiment, I'd try the above more "conventional" format, and also try it with a designated priority higher or lower than 10. If attaching multiple anonymous functions to the same filter, I'd give them different priorities, or use an array (example here: <http://snippets.khromov.se/adding-multiple-actions-and-filters-using-anonymous-functions-in-wordpress/> ), or write each one of them as named two-parters, too.
In truth, I find the slightly lengthier 2-part way easier to read, track, and adjust anyway.
|
199,197 |
<p>i want to restrict all authors to spesific categories i already done it but via theme function.php, i trying to build as a plugin:</p>
<p>this my plugin content:</p>
<pre><code><?php
/**
* Plugin Name: My Restricted
* Plugin URI:
* Description: Restrcted
* Version: 0.0.1
* Author: mm
* Author URI: http://www.mm.com
* License: A "Mikvision" license e.g. GPL12
*/
$user = wp_get_current_user();
$allowed_roles = array('author');
if( array_intersect($allowed_roles, $user->roles ) ) {
function wpse_77670_filterGetTermArgs($args, $taxonomies) {
global $typenow;
if ($typenow == 'post') {
// check whether we're currently filtering selected taxonomy
if (implode('', $taxonomies) == 'category') {
$cats = array(11,13); // as an array
if (empty($cats))
$args['include'] = array(99999999); // no available categories
else
$args['include'] = $cats;
}
}
return $args;
}
add_filter('get_terms_args', 'wpse_77670_filterGetTermArgs', 10, 2);
}
</code></pre>
<p>if u put it inside function.php of my theme its working but plugin not working showing white page.</p>
|
[
{
"answer_id": 199676,
"author": "jim.duck",
"author_id": 78337,
"author_profile": "https://wordpress.stackexchange.com/users/78337",
"pm_score": -1,
"selected": false,
"text": "<p>WordPress uses different templates for pages on your site. If you have a page.php template in your theme, that will be used to display your pages. If you have a single.php, that will be used to display your single posts. index.php or home.php would display your home page, or page.php if you have a certain page selected as the home page through the reading options.</p>\n\n<p>So, your conditional statement:</p>\n\n<pre><code><?php if (is_front_page()){ ?>\n<p>Home Page</p>\n<?php else { ?>\n<p>Not Home Page</p>\n<?php } ?>\n?>\n</code></pre>\n\n<p>Would only really be useful in the header.php or the footer.php file- or in page.php if you have a certain page selected in the reading options.</p>\n"
},
{
"answer_id": 202112,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>Just speculation, but I wonder if you're running into an anonymous function problem. Anonymous functions are allowed in WP, and usually work fine (presuming updated PHP), but, if you search around you'll find reports of suspected bugs or at least of unexpected behavior. </p>\n\n<p>For that matter, I'm not sure that I've ever seen an anonymous function used as an example in the WordPress Codex, and I can't recall ever running across one before in theme and plug-in code. Of course, I've not had my eye out for anon functions, but, still, I think the above function will almost always be written in some version of the more familiar two-part format - ie:</p>\n\n<pre><code>add_filter('body_class', 'ejay_add_home_class');\n\nfunction ejay_add_home_class($classes) {\n\n if (is_front_page() || is_home()) {\n\n $classes[] = 'home-page';\n }\n\n return $classes;\n} \n</code></pre>\n\n<p>So, as an experiment, I'd try the above more \"conventional\" format, and also try it with a designated priority higher or lower than 10. If attaching multiple anonymous functions to the same filter, I'd give them different priorities, or use an array (example here: <a href=\"http://snippets.khromov.se/adding-multiple-actions-and-filters-using-anonymous-functions-in-wordpress/\" rel=\"nofollow\">http://snippets.khromov.se/adding-multiple-actions-and-filters-using-anonymous-functions-in-wordpress/</a> ), or write each one of them as named two-parters, too. </p>\n\n<p>In truth, I find the slightly lengthier 2-part way easier to read, track, and adjust anyway.</p>\n"
}
] |
2015/08/20
|
[
"https://wordpress.stackexchange.com/questions/199197",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78089/"
] |
i want to restrict all authors to spesific categories i already done it but via theme function.php, i trying to build as a plugin:
this my plugin content:
```
<?php
/**
* Plugin Name: My Restricted
* Plugin URI:
* Description: Restrcted
* Version: 0.0.1
* Author: mm
* Author URI: http://www.mm.com
* License: A "Mikvision" license e.g. GPL12
*/
$user = wp_get_current_user();
$allowed_roles = array('author');
if( array_intersect($allowed_roles, $user->roles ) ) {
function wpse_77670_filterGetTermArgs($args, $taxonomies) {
global $typenow;
if ($typenow == 'post') {
// check whether we're currently filtering selected taxonomy
if (implode('', $taxonomies) == 'category') {
$cats = array(11,13); // as an array
if (empty($cats))
$args['include'] = array(99999999); // no available categories
else
$args['include'] = $cats;
}
}
return $args;
}
add_filter('get_terms_args', 'wpse_77670_filterGetTermArgs', 10, 2);
}
```
if u put it inside function.php of my theme its working but plugin not working showing white page.
|
Just speculation, but I wonder if you're running into an anonymous function problem. Anonymous functions are allowed in WP, and usually work fine (presuming updated PHP), but, if you search around you'll find reports of suspected bugs or at least of unexpected behavior.
For that matter, I'm not sure that I've ever seen an anonymous function used as an example in the WordPress Codex, and I can't recall ever running across one before in theme and plug-in code. Of course, I've not had my eye out for anon functions, but, still, I think the above function will almost always be written in some version of the more familiar two-part format - ie:
```
add_filter('body_class', 'ejay_add_home_class');
function ejay_add_home_class($classes) {
if (is_front_page() || is_home()) {
$classes[] = 'home-page';
}
return $classes;
}
```
So, as an experiment, I'd try the above more "conventional" format, and also try it with a designated priority higher or lower than 10. If attaching multiple anonymous functions to the same filter, I'd give them different priorities, or use an array (example here: <http://snippets.khromov.se/adding-multiple-actions-and-filters-using-anonymous-functions-in-wordpress/> ), or write each one of them as named two-parters, too.
In truth, I find the slightly lengthier 2-part way easier to read, track, and adjust anyway.
|
199,226 |
<p>I'm creating a template for archive-product.php page in WooCommerce.</p>
<p>I would like to have 3 boxes and link each to a different product category. </p>
<p><strong>How do I get dynamic link to each product category in <code><a></code> tag?</strong>
For now I put static links, but I'm sure there is a way to make them dynamic in WordPress</p>
<p>Here's what my code looks like:</p>
<pre><code> <ul class="shop-items">
<li class="fine-art">
<a href="http://url.com/product-category/categories/fine-art/">
<div>Fine Art
<span>Description</span>
</div>
</a>
</li>
<li class="dance-art">
<a href="http://url.com/product-category/categories/dance-art/">
<div>Dance Art
<span>Description</span>
</div>
</a>
</li>
<li class="history-art">
<a href="http://url.com/product-category/categories/history-art/">
<div>History Art
<span>Description</span>
</div>
</a>
</li>
</ul>
</code></pre>
|
[
{
"answer_id": 199263,
"author": "Marek",
"author_id": 54031,
"author_profile": "https://wordpress.stackexchange.com/users/54031",
"pm_score": 3,
"selected": true,
"text": "<p>For this purpose there is <code>get_term_link</code> function (<a href=\"https://codex.wordpress.org/Function_Reference/get_term_link\" rel=\"nofollow\">documentation</a>).</p>\n\n<pre><code><a href=\"<?php echo get_term_link( 42 ,'product_cat') ?>\">Fine Art ... etc.</a>\n</code></pre>\n\n<p>Product category is just WP taxonomy, so there is plenty of functions to work with. In this case you have to know your product category ID (taxonomy term ID, actually). When editing category, you will find it in URL: .../edit-tags.php?action=edit&taxonomy=product_cat&tag_ID=<strong>42</strong>&post_type=product</p>\n"
},
{
"answer_id": 369434,
"author": "R VC",
"author_id": 190313,
"author_profile": "https://wordpress.stackexchange.com/users/190313",
"pm_score": 0,
"selected": false,
"text": "<p>I am trying to do the same</p>\n<pre><code><?php\n\nclass My_Dropdown_Category_Control extends WP_Customize_Control {\n\n public $type = 'dropdown-category';\n\n protected $dropdown_args = false;\n\n protected function render_content() {\n ?><label><?php\n\n if ( ! empty( $this->label ) ) :\n ?><span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span><?php\n endif;\n\n if ( ! empty( $this->description ) ) :\n ?><span class="description customize-control-description"><?php echo $this->description; ?></span><?php\n endif;\n\n $dropdown_args = wp_parse_args( $this->dropdown_args, array(\n 'taxonomy' => 'product_cat',\n 'show_option_none' => ' ',\n 'selected' => $this->value(),\n 'show_option_all' => '',\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'show_count' => 1,\n 'hide_empty' => 1,\n 'child_of' => 0,\n 'exclude' => '',\n 'hierarchical' => 1,\n 'depth' => 0,\n 'tab_index' => 0,\n 'hide_if_empty' => false,\n 'option_none_value' => 0,\n 'value_field' => 'term_id',\n ) );\n\n $dropdown_args['echo'] = false;\n\n $dropdown = wp_dropdown_categories( $dropdown_args );\n $dropdown = str_replace( '<select', '<select ' . $this->get_link(), $dropdown );\n echo $dropdown;\n\n ?></label><?php\n\n }\n}\n\n\nfunction olsen_light_child_customize_register( WP_Customize_Manager $wp_customize ) {\n require_once get_stylesheet_directory() . '/inc/dropdown-category.php';\n\n $wp_customize->add_section( 'homepage', array(\n 'title' => esc_html_x( 'Test-Link', 'customizer section title', 'olsen-light-child' ),\n ) );\n\n $wp_customize->add_setting( 'home_slider_category', array(\n 'default' => 0,\n 'sanitize_callback' => 'absint',\n ) );\n\n $wp_customize->add_control( new My_Dropdown_Category_Control( $wp_customize, 'home_slider_category', array(\n 'section' => 'homepage',\n 'label' => esc_html__( 'Slider posts category', 'olsen-light-child' ),\n 'description' => esc_html__( 'Select the category that the slider will show posts from. If no category is selected, the slider will be disabled.', 'olsen-light-child' ),\n ) ) );\n}\n\nadd_action( 'customize_register', 'olsen_light_child_customize_register' );\n</code></pre>\n<p>but when I echo my the settings in my front page, many elements of my site dissapear..., any clue, thanks</p>\n<pre><code><a href="<?php echo get_term_link(get_theme_mod(‘home_slider_category’))?>"><span><?php echo get_theme_mod('gs_slider_one_txt')?></span></a>\n</code></pre>\n"
}
] |
2015/08/20
|
[
"https://wordpress.stackexchange.com/questions/199226",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78105/"
] |
I'm creating a template for archive-product.php page in WooCommerce.
I would like to have 3 boxes and link each to a different product category.
**How do I get dynamic link to each product category in `<a>` tag?**
For now I put static links, but I'm sure there is a way to make them dynamic in WordPress
Here's what my code looks like:
```
<ul class="shop-items">
<li class="fine-art">
<a href="http://url.com/product-category/categories/fine-art/">
<div>Fine Art
<span>Description</span>
</div>
</a>
</li>
<li class="dance-art">
<a href="http://url.com/product-category/categories/dance-art/">
<div>Dance Art
<span>Description</span>
</div>
</a>
</li>
<li class="history-art">
<a href="http://url.com/product-category/categories/history-art/">
<div>History Art
<span>Description</span>
</div>
</a>
</li>
</ul>
```
|
For this purpose there is `get_term_link` function ([documentation](https://codex.wordpress.org/Function_Reference/get_term_link)).
```
<a href="<?php echo get_term_link( 42 ,'product_cat') ?>">Fine Art ... etc.</a>
```
Product category is just WP taxonomy, so there is plenty of functions to work with. In this case you have to know your product category ID (taxonomy term ID, actually). When editing category, you will find it in URL: .../edit-tags.php?action=edit&taxonomy=product\_cat&tag\_ID=**42**&post\_type=product
|
199,243 |
<p>I use this function to get the last time a user logged in.</p>
<pre><code>function jkn_last_login($user_login) {
$user = get_user_by( 'login', $user_login );
global $last_login;
$last_login = array();
$last_login[$user->ID] = get_user_meta($user->ID,'last-login',true);
update_user_meta( $user->ID, 'last-login', time() );
}
add_action('wp_login','jkn_last_login',12,3);
</code></pre>
<p>As you can see i define a global <code>$last_login</code> to save the last login time.</p>
<p>But if i try to echo the value of <code>$last_login</code> nothing happen.</p>
<pre><code>global $last_login;
global $current_user;
echo $last_login[$current_user->ID];
</code></pre>
|
[
{
"answer_id": 199263,
"author": "Marek",
"author_id": 54031,
"author_profile": "https://wordpress.stackexchange.com/users/54031",
"pm_score": 3,
"selected": true,
"text": "<p>For this purpose there is <code>get_term_link</code> function (<a href=\"https://codex.wordpress.org/Function_Reference/get_term_link\" rel=\"nofollow\">documentation</a>).</p>\n\n<pre><code><a href=\"<?php echo get_term_link( 42 ,'product_cat') ?>\">Fine Art ... etc.</a>\n</code></pre>\n\n<p>Product category is just WP taxonomy, so there is plenty of functions to work with. In this case you have to know your product category ID (taxonomy term ID, actually). When editing category, you will find it in URL: .../edit-tags.php?action=edit&taxonomy=product_cat&tag_ID=<strong>42</strong>&post_type=product</p>\n"
},
{
"answer_id": 369434,
"author": "R VC",
"author_id": 190313,
"author_profile": "https://wordpress.stackexchange.com/users/190313",
"pm_score": 0,
"selected": false,
"text": "<p>I am trying to do the same</p>\n<pre><code><?php\n\nclass My_Dropdown_Category_Control extends WP_Customize_Control {\n\n public $type = 'dropdown-category';\n\n protected $dropdown_args = false;\n\n protected function render_content() {\n ?><label><?php\n\n if ( ! empty( $this->label ) ) :\n ?><span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span><?php\n endif;\n\n if ( ! empty( $this->description ) ) :\n ?><span class="description customize-control-description"><?php echo $this->description; ?></span><?php\n endif;\n\n $dropdown_args = wp_parse_args( $this->dropdown_args, array(\n 'taxonomy' => 'product_cat',\n 'show_option_none' => ' ',\n 'selected' => $this->value(),\n 'show_option_all' => '',\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'show_count' => 1,\n 'hide_empty' => 1,\n 'child_of' => 0,\n 'exclude' => '',\n 'hierarchical' => 1,\n 'depth' => 0,\n 'tab_index' => 0,\n 'hide_if_empty' => false,\n 'option_none_value' => 0,\n 'value_field' => 'term_id',\n ) );\n\n $dropdown_args['echo'] = false;\n\n $dropdown = wp_dropdown_categories( $dropdown_args );\n $dropdown = str_replace( '<select', '<select ' . $this->get_link(), $dropdown );\n echo $dropdown;\n\n ?></label><?php\n\n }\n}\n\n\nfunction olsen_light_child_customize_register( WP_Customize_Manager $wp_customize ) {\n require_once get_stylesheet_directory() . '/inc/dropdown-category.php';\n\n $wp_customize->add_section( 'homepage', array(\n 'title' => esc_html_x( 'Test-Link', 'customizer section title', 'olsen-light-child' ),\n ) );\n\n $wp_customize->add_setting( 'home_slider_category', array(\n 'default' => 0,\n 'sanitize_callback' => 'absint',\n ) );\n\n $wp_customize->add_control( new My_Dropdown_Category_Control( $wp_customize, 'home_slider_category', array(\n 'section' => 'homepage',\n 'label' => esc_html__( 'Slider posts category', 'olsen-light-child' ),\n 'description' => esc_html__( 'Select the category that the slider will show posts from. If no category is selected, the slider will be disabled.', 'olsen-light-child' ),\n ) ) );\n}\n\nadd_action( 'customize_register', 'olsen_light_child_customize_register' );\n</code></pre>\n<p>but when I echo my the settings in my front page, many elements of my site dissapear..., any clue, thanks</p>\n<pre><code><a href="<?php echo get_term_link(get_theme_mod(‘home_slider_category’))?>"><span><?php echo get_theme_mod('gs_slider_one_txt')?></span></a>\n</code></pre>\n"
}
] |
2015/08/20
|
[
"https://wordpress.stackexchange.com/questions/199243",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78113/"
] |
I use this function to get the last time a user logged in.
```
function jkn_last_login($user_login) {
$user = get_user_by( 'login', $user_login );
global $last_login;
$last_login = array();
$last_login[$user->ID] = get_user_meta($user->ID,'last-login',true);
update_user_meta( $user->ID, 'last-login', time() );
}
add_action('wp_login','jkn_last_login',12,3);
```
As you can see i define a global `$last_login` to save the last login time.
But if i try to echo the value of `$last_login` nothing happen.
```
global $last_login;
global $current_user;
echo $last_login[$current_user->ID];
```
|
For this purpose there is `get_term_link` function ([documentation](https://codex.wordpress.org/Function_Reference/get_term_link)).
```
<a href="<?php echo get_term_link( 42 ,'product_cat') ?>">Fine Art ... etc.</a>
```
Product category is just WP taxonomy, so there is plenty of functions to work with. In this case you have to know your product category ID (taxonomy term ID, actually). When editing category, you will find it in URL: .../edit-tags.php?action=edit&taxonomy=product\_cat&tag\_ID=**42**&post\_type=product
|
199,244 |
<p>I'm having a hard time getting my 'Hello World' to display on the theme page I created. It all at least appears to be correct (but obviously isn't) - what am I missing here?</p>
<pre><code>// Add Theme Options to menu
function add_theme_menu_item() {
add_theme_page("Theme Panel", "Theme Panel", "manage_options", "theme-panel", "initialize_theme_options", null, 99);
}
add_action("admin_menu", "add_theme_menu_item");
/**
* Initializes the theme options page by registering the Sections,
* Fields, and Settings.
*
* This function is registered with the 'admin_init' hook.
*/
function initialize_theme_options() {
// First, we register a section. This is necessary since all future options must belong to one.
add_settings_section(
// ID used to identify this section and with which to register options
'main_settings_section',
// Title to be displayed on the administration page
'Main Theme Options',
// Callback used to render the description of the section
'main_settings_callback',
// Page
'theme-panel'
);
}
add_action('admin_init', 'initialize_theme_options');
// end initialize_theme_options
/* ------------------------------------------------------------------------ *
* Section Callbacks
* ------------------------------------------------------------------------ */
/**
* This function provides a simple description for the General Options page.
*
* It is called from the 'initialize_theme_options' function by being passed as a parameter
* in the add_settings_section function.
*/
function main_settings_callback() {
echo 'Hello world.';
}
// end main_settings_callback
</code></pre>
|
[
{
"answer_id": 199246,
"author": "Emetrop",
"author_id": 64623,
"author_profile": "https://wordpress.stackexchange.com/users/64623",
"pm_score": 1,
"selected": false,
"text": "<p>This is wrong:</p>\n\n<pre><code>add_theme_page(\"Theme Panel\", \"Theme Panel\", \"manage_options\", \"theme-panel\", \"initialize_theme_options\", null, 99);\n</code></pre>\n\n<p>The last two parameters shouldn't be there. Check this function in codex <a href=\"https://codex.wordpress.org/Function_Reference/add_theme_page\" rel=\"nofollow\">here</a>.</p>\n\n<p>EDIT:</p>\n\n<p>What's more, the last parameter (which should be there) <code>initialize_theme_options</code> is wrong too, because it should be a callback to a function which would output a content. So for example your <code>main_settings_callback</code> function.</p>\n\n<p>SECOND EDIT:</p>\n\n<p>It doesn't work you probably because in the call of <code>add_settings_section</code> function you pass in the last parameter <code>theme-panel</code> and this page probably doesn't exist. Am I right? Try to replace this parameter for example with <code>general</code> and it'll output at the main Setting page.</p>\n"
},
{
"answer_id": 199250,
"author": "jasenmp",
"author_id": 25475,
"author_profile": "https://wordpress.stackexchange.com/users/25475",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, I got it.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/do_settings_sections\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/do_settings_sections</a></p>\n\n<pre><code>function initialize_theme_options() {\n\n// First, we register a section. This is necessary since all future options must belong to one.\n\nadd_settings_section(\n\n // ID used to identify this section and with which to register options\n 'main_settings_section',\n\n // Title to be displayed on the administration page\n 'Main Theme Options',\n\n // Callback used to render the description of the section\n\n 'main_settings_callback', \n\n // Page\n\n 'theme-panel'\n\n);\n\ndo_settings_sections('theme-panel');\n\n} \n</code></pre>\n"
}
] |
2015/08/20
|
[
"https://wordpress.stackexchange.com/questions/199244",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25475/"
] |
I'm having a hard time getting my 'Hello World' to display on the theme page I created. It all at least appears to be correct (but obviously isn't) - what am I missing here?
```
// Add Theme Options to menu
function add_theme_menu_item() {
add_theme_page("Theme Panel", "Theme Panel", "manage_options", "theme-panel", "initialize_theme_options", null, 99);
}
add_action("admin_menu", "add_theme_menu_item");
/**
* Initializes the theme options page by registering the Sections,
* Fields, and Settings.
*
* This function is registered with the 'admin_init' hook.
*/
function initialize_theme_options() {
// First, we register a section. This is necessary since all future options must belong to one.
add_settings_section(
// ID used to identify this section and with which to register options
'main_settings_section',
// Title to be displayed on the administration page
'Main Theme Options',
// Callback used to render the description of the section
'main_settings_callback',
// Page
'theme-panel'
);
}
add_action('admin_init', 'initialize_theme_options');
// end initialize_theme_options
/* ------------------------------------------------------------------------ *
* Section Callbacks
* ------------------------------------------------------------------------ */
/**
* This function provides a simple description for the General Options page.
*
* It is called from the 'initialize_theme_options' function by being passed as a parameter
* in the add_settings_section function.
*/
function main_settings_callback() {
echo 'Hello world.';
}
// end main_settings_callback
```
|
This is wrong:
```
add_theme_page("Theme Panel", "Theme Panel", "manage_options", "theme-panel", "initialize_theme_options", null, 99);
```
The last two parameters shouldn't be there. Check this function in codex [here](https://codex.wordpress.org/Function_Reference/add_theme_page).
EDIT:
What's more, the last parameter (which should be there) `initialize_theme_options` is wrong too, because it should be a callback to a function which would output a content. So for example your `main_settings_callback` function.
SECOND EDIT:
It doesn't work you probably because in the call of `add_settings_section` function you pass in the last parameter `theme-panel` and this page probably doesn't exist. Am I right? Try to replace this parameter for example with `general` and it'll output at the main Setting page.
|
199,265 |
<p>I am planning to build a WordPress site in which I will setup WooCommerce to sell products. I have created a test site before in which I used my personal email account (gmail) as admin email. Then I tested selling from the site. The problem I faced is that the order confirmation emails were going to spam folder of test client email. And the reason of marking as spam is that The message may not have been sent by [email protected].</p>
<p>How can I prevent the problem in my actual site? Should I start off with an email address such as [email protected] ? Or can I start with my personal email address as the admin email and then later change the admin email? Or can I just use my personal email as admin email and in the WooCommerce email setting I should enter [email protected].</p>
<p>To those who have already built and running WooCommerce sites, What is the best possible option regarding using emails?</p>
<p>Any suggestion will be greatly appreciated.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 199246,
"author": "Emetrop",
"author_id": 64623,
"author_profile": "https://wordpress.stackexchange.com/users/64623",
"pm_score": 1,
"selected": false,
"text": "<p>This is wrong:</p>\n\n<pre><code>add_theme_page(\"Theme Panel\", \"Theme Panel\", \"manage_options\", \"theme-panel\", \"initialize_theme_options\", null, 99);\n</code></pre>\n\n<p>The last two parameters shouldn't be there. Check this function in codex <a href=\"https://codex.wordpress.org/Function_Reference/add_theme_page\" rel=\"nofollow\">here</a>.</p>\n\n<p>EDIT:</p>\n\n<p>What's more, the last parameter (which should be there) <code>initialize_theme_options</code> is wrong too, because it should be a callback to a function which would output a content. So for example your <code>main_settings_callback</code> function.</p>\n\n<p>SECOND EDIT:</p>\n\n<p>It doesn't work you probably because in the call of <code>add_settings_section</code> function you pass in the last parameter <code>theme-panel</code> and this page probably doesn't exist. Am I right? Try to replace this parameter for example with <code>general</code> and it'll output at the main Setting page.</p>\n"
},
{
"answer_id": 199250,
"author": "jasenmp",
"author_id": 25475,
"author_profile": "https://wordpress.stackexchange.com/users/25475",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, I got it.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/do_settings_sections\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/do_settings_sections</a></p>\n\n<pre><code>function initialize_theme_options() {\n\n// First, we register a section. This is necessary since all future options must belong to one.\n\nadd_settings_section(\n\n // ID used to identify this section and with which to register options\n 'main_settings_section',\n\n // Title to be displayed on the administration page\n 'Main Theme Options',\n\n // Callback used to render the description of the section\n\n 'main_settings_callback', \n\n // Page\n\n 'theme-panel'\n\n);\n\ndo_settings_sections('theme-panel');\n\n} \n</code></pre>\n"
}
] |
2015/08/21
|
[
"https://wordpress.stackexchange.com/questions/199265",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54832/"
] |
I am planning to build a WordPress site in which I will setup WooCommerce to sell products. I have created a test site before in which I used my personal email account (gmail) as admin email. Then I tested selling from the site. The problem I faced is that the order confirmation emails were going to spam folder of test client email. And the reason of marking as spam is that The message may not have been sent by \_\_\_\[email protected].
How can I prevent the problem in my actual site? Should I start off with an email address such as \_\_\_\[email protected] ? Or can I start with my personal email address as the admin email and then later change the admin email? Or can I just use my personal email as admin email and in the WooCommerce email setting I should enter [email protected].
To those who have already built and running WooCommerce sites, What is the best possible option regarding using emails?
Any suggestion will be greatly appreciated.
Thanks.
|
This is wrong:
```
add_theme_page("Theme Panel", "Theme Panel", "manage_options", "theme-panel", "initialize_theme_options", null, 99);
```
The last two parameters shouldn't be there. Check this function in codex [here](https://codex.wordpress.org/Function_Reference/add_theme_page).
EDIT:
What's more, the last parameter (which should be there) `initialize_theme_options` is wrong too, because it should be a callback to a function which would output a content. So for example your `main_settings_callback` function.
SECOND EDIT:
It doesn't work you probably because in the call of `add_settings_section` function you pass in the last parameter `theme-panel` and this page probably doesn't exist. Am I right? Try to replace this parameter for example with `general` and it'll output at the main Setting page.
|
199,266 |
<p>I am using co-author plus and I have posts in my site that are done by multiple authors. I would like that when I click on the co-author's author page, I will be able to get the posts that he/she co-authored.</p>
<p>For now, I am using a vanilla WP_Query call to primary authors. I followed db trail and the co-authors are posted on the wp_term_taxonomy table, but I am unsure on how to query and get that data.</p>
<p>Here is my paramters:</p>
<pre><code>$arg = array(
'author' => strval($user_id),
'post_per_page' => 10,
'post_status' => 'publish',
'paged' => strval($page)
);
</code></pre>
|
[
{
"answer_id": 199270,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the template functions given by Co-Authors Plus plugin such as,</p>\n\n<ol>\n<li>coauthors_posts_links() - Co-Authors Plus equivalent of the_author_posts_link() template tag.</li>\n<li>coauthors() - Co-Authors Plus equivalent of the_author() template tag.</li>\n</ol>\n\n<p>Please refer to their <a href=\"https://vip.wordpress.com/documentation/incorporate-co-authors-plus-template-tags-into-your-theme/\" rel=\"nofollow\">documentation</a></p>\n"
},
{
"answer_id": 199282,
"author": "Banago",
"author_id": 6612,
"author_profile": "https://wordpress.stackexchange.com/users/6612",
"pm_score": 1,
"selected": false,
"text": "<p>Use the <a href=\"https://wordpress.org/plugins/co-authors-plus/\" rel=\"nofollow\">Co-Authors Plus</a> to assign the authors and the post will show <strong>automatically</strong> on both author pages. I've used it and works pretty well.</p>\n"
}
] |
2015/08/21
|
[
"https://wordpress.stackexchange.com/questions/199266",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17199/"
] |
I am using co-author plus and I have posts in my site that are done by multiple authors. I would like that when I click on the co-author's author page, I will be able to get the posts that he/she co-authored.
For now, I am using a vanilla WP\_Query call to primary authors. I followed db trail and the co-authors are posted on the wp\_term\_taxonomy table, but I am unsure on how to query and get that data.
Here is my paramters:
```
$arg = array(
'author' => strval($user_id),
'post_per_page' => 10,
'post_status' => 'publish',
'paged' => strval($page)
);
```
|
Use the [Co-Authors Plus](https://wordpress.org/plugins/co-authors-plus/) to assign the authors and the post will show **automatically** on both author pages. I've used it and works pretty well.
|
199,274 |
<p>So, WordPress 4.3 has a new password system as we all know.
Unfortunately, this new system has done away with the ability to <strong>NOT</strong> send new users an email.</p>
<p>My client was using a system where he sent a custom email to his clients, manually registering their emails, and then sending them an email with the login info with a custom message. We are aware that this new system is trying to be more secure, but this isn't working for the amount of control he would like.</p>
<p>I've found the following code in my search for a solution to turn these emails off, but I think they only turn off the notification emails for if a user's email is CHANGED for previously registered users, not when it's first created:</p>
<pre><code>add_filter( 'send_password_change_email', '__return_false');
add_filter( 'send_email_change_email', '__return_false');
</code></pre>
<p>Does anyone know of any way to turn off these initial password emails sent after registration?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 199321,
"author": "Emetrop",
"author_id": 64623,
"author_profile": "https://wordpress.stackexchange.com/users/64623",
"pm_score": 2,
"selected": false,
"text": "<p>Actually it depends how you create the new user. If you do it from administration - Users - Add New you are right. In 4.3 unfortunatelly you cannot disable sending the notification email. But if you really want to create a new user without the email, there is a way. </p>\n\n<p>You can create a small plugin where you'd create a new account by yourself via <code>wp_insert_user</code> function, which doesn't send any email by default.</p>\n\n<p>This function can be called like this.</p>\n\n<pre><code>wp_insert_user( $userdata );\n</code></pre>\n\n<p>Where the <code>userdata</code> parameter is an array where you can pass all needed information.</p>\n\n<pre><code>$userdata = array(\n 'user_login' => 'login',\n 'user_pass' => 'password',\n);\n\n$user_id = wp_insert_user( $userdata ) ;\n\n//On success\nif ( ! is_wp_error( $user_id ) ) {\n echo \"User created : \". $user_id;\n}\n</code></pre>\n\n<p>For more informations check codex <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_user\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 199624,
"author": "Simon Blackbourn",
"author_id": 2877,
"author_profile": "https://wordpress.stackexchange.com/users/2877",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>wp_new_user_notification</code> function is pluggable, so you can override it by defining your own. You should be able to copy the entire function from <code>wp-includes/pluggable.php</code> into your plugin (or <code>functions.php</code>) and remove the line that sends out the email.</p>\n"
},
{
"answer_id": 205729,
"author": "fandasson",
"author_id": 56759,
"author_profile": "https://wordpress.stackexchange.com/users/56759",
"pm_score": 1,
"selected": false,
"text": "<p>To solve this in your theme create new <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">mu-plugin</a> by creating new file <code>wp_new_user_notifications.php</code> (name is up to you) and put it in <code>wp-content/mu-plugins</code> folder. If there is no folder like that, create one. Remember to put the php file directly into the folder, not to any subfolder.</p>\n\n<p>Than continue as <a href=\"https://wordpress.stackexchange.com/a/199624/56759\">Simon suggested</a> - copy <code>wp_new_user_notifications.php</code> method from <code>wp-includes/pluggable.php</code> into your brand new <code>wp_new_user_notifications.php</code> file and modify as needed.</p>\n\n<p>To answer your question: for turning off initial password e-mails is enough to remove last <code>wp_mail</code> method call.</p>\n"
},
{
"answer_id": 211097,
"author": "sxalexander",
"author_id": 1992,
"author_profile": "https://wordpress.stackexchange.com/users/1992",
"pm_score": 4,
"selected": true,
"text": "<p>You can intercept this email before it is sent using the <a href=\"https://developer.wordpress.org/reference/hooks/phpmailer_init/\" rel=\"noreferrer\"><code>phpmailer_init</code></a> hook. </p>\n\n<p>By default, this hook fires before any email is sent. In the function below, <code>$phpmailer</code> will be an instance of <a href=\"https://github.com/PHPMailer/PHPMailer\" rel=\"noreferrer\">PHPMailer</a>, and you can use its methods to remove the default recipient and manipulate the email before it is sent.</p>\n\n<pre><code>add_action('phpmailer_init', 'wse199274_intercept_registration_email');\nfunction wse199274_intercept_registration_email($phpmailer){\n $admin_email = get_option( 'admin_email' );\n\n # Intercept username and password email by checking subject line\n if( strpos($phpmailer->Subject, 'Your username and password info') ){\n # clear the recipient list\n $phpmailer->ClearAllRecipients();\n # optionally, send the email to the WordPress admin email\n $phpmailer->AddAddress($admin_email);\n }else{\n #not intercepted\n }\n}\n</code></pre>\n"
},
{
"answer_id": 292599,
"author": "Philip",
"author_id": 19188,
"author_profile": "https://wordpress.stackexchange.com/users/19188",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_filter('send_password_change_email', '__return_false');\n</code></pre>\n\n<p>Works. But its essential that its added to the plugin it self and not the functions.php for the theme.</p>\n\n<p>Like.</p>\n\n<pre><code>class ... {\n public function __construct() {\n ...\n $this->init_hooks();\n }\n\n public function init_hooks() {\n add_filter('send_password_change_email', '__return_false');\n }\n}\n</code></pre>\n"
}
] |
2015/08/21
|
[
"https://wordpress.stackexchange.com/questions/199274",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75600/"
] |
So, WordPress 4.3 has a new password system as we all know.
Unfortunately, this new system has done away with the ability to **NOT** send new users an email.
My client was using a system where he sent a custom email to his clients, manually registering their emails, and then sending them an email with the login info with a custom message. We are aware that this new system is trying to be more secure, but this isn't working for the amount of control he would like.
I've found the following code in my search for a solution to turn these emails off, but I think they only turn off the notification emails for if a user's email is CHANGED for previously registered users, not when it's first created:
```
add_filter( 'send_password_change_email', '__return_false');
add_filter( 'send_email_change_email', '__return_false');
```
Does anyone know of any way to turn off these initial password emails sent after registration?
Thank you.
|
You can intercept this email before it is sent using the [`phpmailer_init`](https://developer.wordpress.org/reference/hooks/phpmailer_init/) hook.
By default, this hook fires before any email is sent. In the function below, `$phpmailer` will be an instance of [PHPMailer](https://github.com/PHPMailer/PHPMailer), and you can use its methods to remove the default recipient and manipulate the email before it is sent.
```
add_action('phpmailer_init', 'wse199274_intercept_registration_email');
function wse199274_intercept_registration_email($phpmailer){
$admin_email = get_option( 'admin_email' );
# Intercept username and password email by checking subject line
if( strpos($phpmailer->Subject, 'Your username and password info') ){
# clear the recipient list
$phpmailer->ClearAllRecipients();
# optionally, send the email to the WordPress admin email
$phpmailer->AddAddress($admin_email);
}else{
#not intercepted
}
}
```
|
199,289 |
<p>I've tried the below code to create custom status.</p>
<pre><code>add_action( 'init', function() {
$term = get_term_by( 'name', 'shipped', 'shop_order_status' );
if ( ! $term ) {
wp_insert_term( 'shipped', 'shop_order_status' );
}
} );
</code></pre>
<p>But it is not working. I tried some other methods also. Please can anyone help me on this..</p>
|
[
{
"answer_id": 199295,
"author": "Magnetize",
"author_id": 49181,
"author_profile": "https://wordpress.stackexchange.com/users/49181",
"pm_score": 5,
"selected": true,
"text": "<p>This is what I have used to create a custom order status called \"Invoiced\".\nAdd this to your theme's functions.php</p>\n\n<pre><code>// New order status AFTER woo 2.2\nadd_action( 'init', 'register_my_new_order_statuses' );\n\nfunction register_my_new_order_statuses() {\n register_post_status( 'wc-invoiced', array(\n 'label' => _x( 'Invoiced', 'Order status', 'woocommerce' ),\n 'public' => true,\n 'exclude_from_search' => false,\n 'show_in_admin_all_list' => true,\n 'show_in_admin_status_list' => true,\n 'label_count' => _n_noop( 'Invoiced <span class=\"count\">(%s)</span>', 'Invoiced<span class=\"count\">(%s)</span>', 'woocommerce' )\n ) );\n}\n\nadd_filter( 'wc_order_statuses', 'my_new_wc_order_statuses' );\n\n// Register in wc_order_statuses.\nfunction my_new_wc_order_statuses( $order_statuses ) {\n $order_statuses['wc-invoiced'] = _x( 'Invoiced', 'Order status', 'woocommerce' );\n\n return $order_statuses;\n}\n</code></pre>\n\n<p>In order to add your new status to the admin Bulk-edit dropdown you have to use javascript.\nAdd your function to the <code>admin_footer</code> action.\nMy function then looks something like this:</p>\n\n<pre><code>function custom_bulk_admin_footer() {\n global $post_type;\n\n if ( $post_type == 'shop_order' ) {\n ?>\n <script type=\"text/javascript\">\n jQuery(document).ready(function() {\n jQuery('<option>').val('mark_invoiced').text('<?php _e( 'Mark invoiced', 'textdomain' ); ?>').appendTo(\"select[name='action']\");\n jQuery('<option>').val('mark_invoiced').text('<?php _e( 'Mark invoiced', 'textdomain' ); ?>').appendTo(\"select[name='action2']\"); \n });\n </script>\n <?php\n }\n }\n</code></pre>\n\n<p>The action is added two times because there are one bulk action at the top and another at the bottom of the order list.</p>\n"
},
{
"answer_id": 315790,
"author": "Vlăduț Ilie",
"author_id": 129711,
"author_profile": "https://wordpress.stackexchange.com/users/129711",
"pm_score": 2,
"selected": false,
"text": "<p>As a completion for above and to not use JavaScript to add the actions in bulk actions list, to add/reorder bulk actions you can use the hook <code>bulk_actions-edit-shop_order</code>. For example:</p>\n\n<pre><code>function rename_or_reorder_bulk_actions( $actions ) {\n $actions = array(\n // this is the order in which the actions are displayed; you can switch them\n 'mark_processing' => __( 'Mark placed', 'textdomain' ), // rewrite an existing status\n 'mark_invoiced' => __( 'Mark invoiced', 'textdomain' ), // adding a new one\n 'mark_completed' => $actions['mark_completed'],\n 'remove_personal_data' => $actions['remove_personal_data'],\n 'trash' => $actions['trash'],\n );\n return $actions;\n}\nadd_filter( 'bulk_actions-edit-shop_order', 'rename_or_reorder_bulk_actions', 20 );\n</code></pre>\n\n<p>Cheers!</p>\n"
}
] |
2015/08/21
|
[
"https://wordpress.stackexchange.com/questions/199289",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76222/"
] |
I've tried the below code to create custom status.
```
add_action( 'init', function() {
$term = get_term_by( 'name', 'shipped', 'shop_order_status' );
if ( ! $term ) {
wp_insert_term( 'shipped', 'shop_order_status' );
}
} );
```
But it is not working. I tried some other methods also. Please can anyone help me on this..
|
This is what I have used to create a custom order status called "Invoiced".
Add this to your theme's functions.php
```
// New order status AFTER woo 2.2
add_action( 'init', 'register_my_new_order_statuses' );
function register_my_new_order_statuses() {
register_post_status( 'wc-invoiced', array(
'label' => _x( 'Invoiced', 'Order status', 'woocommerce' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Invoiced <span class="count">(%s)</span>', 'Invoiced<span class="count">(%s)</span>', 'woocommerce' )
) );
}
add_filter( 'wc_order_statuses', 'my_new_wc_order_statuses' );
// Register in wc_order_statuses.
function my_new_wc_order_statuses( $order_statuses ) {
$order_statuses['wc-invoiced'] = _x( 'Invoiced', 'Order status', 'woocommerce' );
return $order_statuses;
}
```
In order to add your new status to the admin Bulk-edit dropdown you have to use javascript.
Add your function to the `admin_footer` action.
My function then looks something like this:
```
function custom_bulk_admin_footer() {
global $post_type;
if ( $post_type == 'shop_order' ) {
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('<option>').val('mark_invoiced').text('<?php _e( 'Mark invoiced', 'textdomain' ); ?>').appendTo("select[name='action']");
jQuery('<option>').val('mark_invoiced').text('<?php _e( 'Mark invoiced', 'textdomain' ); ?>').appendTo("select[name='action2']");
});
</script>
<?php
}
}
```
The action is added two times because there are one bulk action at the top and another at the bottom of the order list.
|
199,322 |
<p>I am using ACF (last version) with WordPress (last version too).
I need to modify the post_object fields of ACF so I use this <a href="http://www.advancedcustomfields.com/resources/acf-fields-post_object-query/" rel="nofollow"><code>acf/fields/post_object/query</code></a> function. </p>
<p>All works fine but when I do a var_dump in the function in the functions.php file, it's impossible to find the result anywhere :(</p>
<p>Does anybody know where I can find this?</p>
<p>My code in the functions.php</p>
<pre><code>function member_relation($args, $field, $post) {
var_dump($post); // This var_dump ?
$args['post_parent'] = $post;
return $args;
}
add_filter('acf/fields/post_object/query/name=list_cases', 'member_relation', 10, 3);
</code></pre>
|
[
{
"answer_id": 199324,
"author": "Emetrop",
"author_id": 64623,
"author_profile": "https://wordpress.stackexchange.com/users/64623",
"pm_score": 1,
"selected": false,
"text": "<p>Probably nowhere because it outputs too early. I recommend to use <code>error_log</code> function and turn on <code>WP_DEBUG_LOG</code>.</p>\n\n<p>Just add to the <code>wp-config.php</code> file somewhere in front of this line:</p>\n\n<pre><code>require_once(ABSPATH . 'wp-settings.php');\n</code></pre>\n\n<p>these new lines:</p>\n\n<pre><code>define( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n\n<p>Now create in <code>wp-content</code> folder a new file <code>debug.log</code> and set chmod to 640.</p>\n\n<p>And this line in your code:</p>\n\n<pre><code>var_dump($post);\n</code></pre>\n\n<p>replace with this:</p>\n\n<pre><code>error_log( var_export( $post, true ) );\n</code></pre>\n\n<p>Now you will find content of the <code>$post</code> variable in the <code>debug.log</code> file.</p>\n"
},
{
"answer_id": 221042,
"author": "samjco",
"author_id": 29133,
"author_profile": "https://wordpress.stackexchange.com/users/29133",
"pm_score": 0,
"selected": false,
"text": "<p>You can probably try using die() after the dump.</p>\n\n<pre><code>var_dump($post); // This var_dump ?\ndie();\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>print_r($post);\ndie();\n</code></pre>\n"
},
{
"answer_id": 252901,
"author": "Radoslav Georgiev",
"author_id": 59084,
"author_profile": "https://wordpress.stackexchange.com/users/59084",
"pm_score": 0,
"selected": false,
"text": "<p>If I remember correctly, the post object field doesn't query any posts until the moment you open the drop down and this is happening through AJAX. </p>\n\n<p>This means that in order to see the variable that you dumped, you need to open the developer tools of your browser while you are on the admin page where the field is shown, go to the network tab, try to open the dropdown and then finally, check the last call. </p>\n\n<p>However, as I said this is something that is happening only in the admin. If you want to modify the value in the front-end, you should just use get_field() and manipulate the variable that it returns. </p>\n"
}
] |
2015/08/21
|
[
"https://wordpress.stackexchange.com/questions/199322",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40648/"
] |
I am using ACF (last version) with WordPress (last version too).
I need to modify the post\_object fields of ACF so I use this [`acf/fields/post_object/query`](http://www.advancedcustomfields.com/resources/acf-fields-post_object-query/) function.
All works fine but when I do a var\_dump in the function in the functions.php file, it's impossible to find the result anywhere :(
Does anybody know where I can find this?
My code in the functions.php
```
function member_relation($args, $field, $post) {
var_dump($post); // This var_dump ?
$args['post_parent'] = $post;
return $args;
}
add_filter('acf/fields/post_object/query/name=list_cases', 'member_relation', 10, 3);
```
|
Probably nowhere because it outputs too early. I recommend to use `error_log` function and turn on `WP_DEBUG_LOG`.
Just add to the `wp-config.php` file somewhere in front of this line:
```
require_once(ABSPATH . 'wp-settings.php');
```
these new lines:
```
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
```
Now create in `wp-content` folder a new file `debug.log` and set chmod to 640.
And this line in your code:
```
var_dump($post);
```
replace with this:
```
error_log( var_export( $post, true ) );
```
Now you will find content of the `$post` variable in the `debug.log` file.
|
199,378 |
<p>I have built an isotope portfolio Wordpress theme which so far is working perfectly:</p>
<p>Anything posted in the custom post type 'portfolio' shows on the homepage and is filterable by the 'portfolio-category' taxonomy using the Isotope JQuery plugin.</p>
<p>So far so good.</p>
<p>However, I wish to make a small improvement.</p>
<p><strong>I only want FEATURED portfolio items to show on the homepage.</strong> For example, only portfolio items with the taxonomy classification of 'featured'. This part I have achieved easily with a custom query (see code snippet below).</p>
<p>The problem I am having is displaying the filterable buttons. I don't want a filterable button to say 'Featured' (defies the point), nor do I want any taxonomies to appear which aren't applicable to any of the featured items (because if clicked, <em>all</em> the portfolio items being displayed will disappear).</p>
<p>Here is my current query to show the portfolio items. No problems here:</p>
<pre><code><?php
// Query the portfolio posts
$args = array(
'post_type' => 'portfolio',
'portfolio-category' => 'featured',
'posts_per_page' => -1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<!-- PORTFOLIO ITEM -->
<?php endwhile; ?>
</code></pre>
<p>And here is the code I have currently which outputs the filterable taxonomies. This is what needs addressing.</p>
<pre><code><?php
$terms = get_terms('portfolio-category');
$count = count($terms);
echo '<li class="filtering"><a href="#" title="" data-filter="*" class="button-primary">All</a></li>';
if ( $count > 0 ){
foreach ( $terms as $term ) {
$termname = strtolower($term->name);
$termname = str_replace(' ', '-', $termname);
echo '<li class="filtering"><a href="#" title="" data-filter=".'.$termname.'">'.$term->name.'</a></li>';
}
}
?>
</code></pre>
<p>Many thanks!</p>
|
[
{
"answer_id": 199324,
"author": "Emetrop",
"author_id": 64623,
"author_profile": "https://wordpress.stackexchange.com/users/64623",
"pm_score": 1,
"selected": false,
"text": "<p>Probably nowhere because it outputs too early. I recommend to use <code>error_log</code> function and turn on <code>WP_DEBUG_LOG</code>.</p>\n\n<p>Just add to the <code>wp-config.php</code> file somewhere in front of this line:</p>\n\n<pre><code>require_once(ABSPATH . 'wp-settings.php');\n</code></pre>\n\n<p>these new lines:</p>\n\n<pre><code>define( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n\n<p>Now create in <code>wp-content</code> folder a new file <code>debug.log</code> and set chmod to 640.</p>\n\n<p>And this line in your code:</p>\n\n<pre><code>var_dump($post);\n</code></pre>\n\n<p>replace with this:</p>\n\n<pre><code>error_log( var_export( $post, true ) );\n</code></pre>\n\n<p>Now you will find content of the <code>$post</code> variable in the <code>debug.log</code> file.</p>\n"
},
{
"answer_id": 221042,
"author": "samjco",
"author_id": 29133,
"author_profile": "https://wordpress.stackexchange.com/users/29133",
"pm_score": 0,
"selected": false,
"text": "<p>You can probably try using die() after the dump.</p>\n\n<pre><code>var_dump($post); // This var_dump ?\ndie();\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>print_r($post);\ndie();\n</code></pre>\n"
},
{
"answer_id": 252901,
"author": "Radoslav Georgiev",
"author_id": 59084,
"author_profile": "https://wordpress.stackexchange.com/users/59084",
"pm_score": 0,
"selected": false,
"text": "<p>If I remember correctly, the post object field doesn't query any posts until the moment you open the drop down and this is happening through AJAX. </p>\n\n<p>This means that in order to see the variable that you dumped, you need to open the developer tools of your browser while you are on the admin page where the field is shown, go to the network tab, try to open the dropdown and then finally, check the last call. </p>\n\n<p>However, as I said this is something that is happening only in the admin. If you want to modify the value in the front-end, you should just use get_field() and manipulate the variable that it returns. </p>\n"
}
] |
2015/08/22
|
[
"https://wordpress.stackexchange.com/questions/199378",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78183/"
] |
I have built an isotope portfolio Wordpress theme which so far is working perfectly:
Anything posted in the custom post type 'portfolio' shows on the homepage and is filterable by the 'portfolio-category' taxonomy using the Isotope JQuery plugin.
So far so good.
However, I wish to make a small improvement.
**I only want FEATURED portfolio items to show on the homepage.** For example, only portfolio items with the taxonomy classification of 'featured'. This part I have achieved easily with a custom query (see code snippet below).
The problem I am having is displaying the filterable buttons. I don't want a filterable button to say 'Featured' (defies the point), nor do I want any taxonomies to appear which aren't applicable to any of the featured items (because if clicked, *all* the portfolio items being displayed will disappear).
Here is my current query to show the portfolio items. No problems here:
```
<?php
// Query the portfolio posts
$args = array(
'post_type' => 'portfolio',
'portfolio-category' => 'featured',
'posts_per_page' => -1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<!-- PORTFOLIO ITEM -->
<?php endwhile; ?>
```
And here is the code I have currently which outputs the filterable taxonomies. This is what needs addressing.
```
<?php
$terms = get_terms('portfolio-category');
$count = count($terms);
echo '<li class="filtering"><a href="#" title="" data-filter="*" class="button-primary">All</a></li>';
if ( $count > 0 ){
foreach ( $terms as $term ) {
$termname = strtolower($term->name);
$termname = str_replace(' ', '-', $termname);
echo '<li class="filtering"><a href="#" title="" data-filter=".'.$termname.'">'.$term->name.'</a></li>';
}
}
?>
```
Many thanks!
|
Probably nowhere because it outputs too early. I recommend to use `error_log` function and turn on `WP_DEBUG_LOG`.
Just add to the `wp-config.php` file somewhere in front of this line:
```
require_once(ABSPATH . 'wp-settings.php');
```
these new lines:
```
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
```
Now create in `wp-content` folder a new file `debug.log` and set chmod to 640.
And this line in your code:
```
var_dump($post);
```
replace with this:
```
error_log( var_export( $post, true ) );
```
Now you will find content of the `$post` variable in the `debug.log` file.
|
199,403 |
<p>What is the <em>keyboard shortcut</em> key for <em>updating</em> a page or post? It could save me a lot of time as rolling down a page draft is time consuming. </p>
|
[
{
"answer_id": 199411,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<p>I was curious about this and checked the Codex on <a href=\"https://codex.wordpress.org/Keyboard_Shortcuts\" rel=\"noreferrer\">keyboard shortcuts</a>, but didn't find it mentioned there.</p>\n\n<p>I searched and found out that this seems to be already solved, e.g. <a href=\"https://wordpress.org/plugins/save-with-keyboard/\" rel=\"noreferrer\">here</a> and <a href=\"https://github.com/johnbillion/wordpress-keyboard-shortcuts\" rel=\"noreferrer\">here</a>.</p>\n\n<p>I haven't tested out these other plugins so I'm not sure how they solve it, but I decided to take on the challenge and see how this could be solved ;-)</p>\n\n<p>So here's my hack for creating shortcuts for:</p>\n\n<pre><code>ctrl+s : Save Draft\nctrl+p : Publish / Update\n</code></pre>\n\n<p>with the following <em>test plugin</em> that runs within the <a href=\"https://wordpress.stackexchange.com/a/112192/26350\"><code>after_wp_tiny_mce</code></a> hook:</p>\n\n<pre><code>/**\n * Plugin Name: Testing ctrl+s and ctrl+p for saving and publishing posts.\n * Plugin URI: https://wordpress.stackexchange.com/a/199411/26350\n */\nadd_action( 'after_wp_tiny_mce', function()\n{?><script>\n ( function ( $ ) {\n 'use strict';\n $( window ).load( function () {\n wpse.init();\n });\n var wpse = {\n keydown : function (e) {\n if( e.ctrlKey && 83 === e.which ) {\n // ctrl+s for \"Save Draft\"\n e.preventDefault();\n $( '#save-post' ).trigger( 'click' ); \n } else if ( e.ctrlKey && 80 === e.which ) {\n // ctrl+p for \"Publish\" or \"Update\"\n e.preventDefault();\n $( '#publish' ).trigger( 'click' );\n }\n },\n set_keydown_for_document : function() {\n $(document).on( 'keydown', wpse.keydown );\n },\n set_keydown_for_tinymce : function() {\n if( typeof tinymce == 'undefined' )\n return;\n for (var i = 0; i < tinymce.editors.length; i++)\n tinymce.editors[i].on( 'keydown', wpse.keydown );\n },\n init : function() {\n wpse.set_keydown_for_document();\n wpse.set_keydown_for_tinymce();\n }\n } \n } ( jQuery ) );\n </script><?php });\n</code></pre>\n\n<p>I added the <em>wpse.keydown</em> event-callback to every <em>tinymce</em> editor on the page, so the shortcuts would be available from there too.</p>\n\n<p>Note that I use the <code>after_wp_tiny_mce</code> hook, as a convinient test-hook on a <strong>vanilla</strong> install, since we're dealing with the <em>tinymce</em> javascript object.\nWhen we ship such a plugin, we should enqueue it from a .js file, as usual.</p>\n\n<p>We could also use the <code>SetupEditor</code> event of <em>tinymce</em>, as mentioned <a href=\"https://wordpress.stackexchange.com/a/192931/26350\">here</a> by @bonger, but here I've added an extra check to see if <em>tinymce</em> is defined, to avoid javascript error on pages where it's not defined:</p>\n\n<pre><code>// Keydown for tinymce\nif( typeof tinymce != 'undefined' )\n{\n tinymce.on( 'SetupEditor', function (editor) {\n wpse.set_keydown_for_tinymce();\n });\n}\n// Keydown for document\nwpse.set_keydown_for_document();\n</code></pre>\n\n<p>We could probably setup native <em>tinymce</em> shortcuts as well.</p>\n\n<p>This might need some testing & adjustments, but it seems to work on my install.</p>\n"
},
{
"answer_id": 350566,
"author": "OHY",
"author_id": 176840,
"author_profile": "https://wordpress.stackexchange.com/users/176840",
"pm_score": 1,
"selected": false,
"text": "<p>The question is old, but there is a plugin for this purpose:\n<a href=\"https://wordpress.org/plugins/save-with-keyboard/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/save-with-keyboard/</a></p>\n"
}
] |
2015/08/22
|
[
"https://wordpress.stackexchange.com/questions/199403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78191/"
] |
What is the *keyboard shortcut* key for *updating* a page or post? It could save me a lot of time as rolling down a page draft is time consuming.
|
I was curious about this and checked the Codex on [keyboard shortcuts](https://codex.wordpress.org/Keyboard_Shortcuts), but didn't find it mentioned there.
I searched and found out that this seems to be already solved, e.g. [here](https://wordpress.org/plugins/save-with-keyboard/) and [here](https://github.com/johnbillion/wordpress-keyboard-shortcuts).
I haven't tested out these other plugins so I'm not sure how they solve it, but I decided to take on the challenge and see how this could be solved ;-)
So here's my hack for creating shortcuts for:
```
ctrl+s : Save Draft
ctrl+p : Publish / Update
```
with the following *test plugin* that runs within the [`after_wp_tiny_mce`](https://wordpress.stackexchange.com/a/112192/26350) hook:
```
/**
* Plugin Name: Testing ctrl+s and ctrl+p for saving and publishing posts.
* Plugin URI: https://wordpress.stackexchange.com/a/199411/26350
*/
add_action( 'after_wp_tiny_mce', function()
{?><script>
( function ( $ ) {
'use strict';
$( window ).load( function () {
wpse.init();
});
var wpse = {
keydown : function (e) {
if( e.ctrlKey && 83 === e.which ) {
// ctrl+s for "Save Draft"
e.preventDefault();
$( '#save-post' ).trigger( 'click' );
} else if ( e.ctrlKey && 80 === e.which ) {
// ctrl+p for "Publish" or "Update"
e.preventDefault();
$( '#publish' ).trigger( 'click' );
}
},
set_keydown_for_document : function() {
$(document).on( 'keydown', wpse.keydown );
},
set_keydown_for_tinymce : function() {
if( typeof tinymce == 'undefined' )
return;
for (var i = 0; i < tinymce.editors.length; i++)
tinymce.editors[i].on( 'keydown', wpse.keydown );
},
init : function() {
wpse.set_keydown_for_document();
wpse.set_keydown_for_tinymce();
}
}
} ( jQuery ) );
</script><?php });
```
I added the *wpse.keydown* event-callback to every *tinymce* editor on the page, so the shortcuts would be available from there too.
Note that I use the `after_wp_tiny_mce` hook, as a convinient test-hook on a **vanilla** install, since we're dealing with the *tinymce* javascript object.
When we ship such a plugin, we should enqueue it from a .js file, as usual.
We could also use the `SetupEditor` event of *tinymce*, as mentioned [here](https://wordpress.stackexchange.com/a/192931/26350) by @bonger, but here I've added an extra check to see if *tinymce* is defined, to avoid javascript error on pages where it's not defined:
```
// Keydown for tinymce
if( typeof tinymce != 'undefined' )
{
tinymce.on( 'SetupEditor', function (editor) {
wpse.set_keydown_for_tinymce();
});
}
// Keydown for document
wpse.set_keydown_for_document();
```
We could probably setup native *tinymce* shortcuts as well.
This might need some testing & adjustments, but it seems to work on my install.
|
199,419 |
<p>I'm fine with <code>P</code> tags for most of the content, since it makes styling easier. However I'd like to have <code>span</code> <code>div</code> <code>iframe</code> and possibly other HTML tags to not be placed inside of a <code>p</code> for post.</p>
<p>I saw <a href="https://wordpress.stackexchange.com/questions/7090/stop-wordpress-wrapping-images-in-a-p-tag?rq=1">this question</a> but it doesn't quite solve it. Also, I saw the <a href="https://css-tricks.com/snippets/wordpress/remove-paragraph-tags-from-around-images/" rel="nofollow noreferrer">linked CSSTricks article</a>, and tried a sample code that used iFrame on it for my <code>spans</code>. Am I doing something wrong with the code? Or what should I do to remove the <code>p</code> tags from html tags in my post.</p>
<p>Here's my code that isn't working:</p>
<pre><code>function filter_ptags_on_images($content) {
$content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
return preg_replace('/<p>\s*(<span .*>*.<\/span>)\s*<\/p>/iU', '\1', $content);
} add_filter('the_content', 'filter_ptags_on_images');
</code></pre>
|
[
{
"answer_id": 199540,
"author": "Huginn",
"author_id": 70043,
"author_profile": "https://wordpress.stackexchange.com/users/70043",
"pm_score": -1,
"selected": false,
"text": "<p>Try this. Open your <code>functions.php</code> file and add the following PHP snippet</p>\n\n<pre><code>remove_filter('the_content', 'wpautop');\n</code></pre>\n"
},
{
"answer_id": 199553,
"author": "tam",
"author_id": 18668,
"author_profile": "https://wordpress.stackexchange.com/users/18668",
"pm_score": 0,
"selected": false,
"text": "<p>To me you code looks good, I would recommend adding priority as high as 9999\nHeres how :</p>\n\n<pre><code>add_filter('the_content', 'filter_ptags_on_images', '9999');\n</code></pre>\n"
}
] |
2015/08/23
|
[
"https://wordpress.stackexchange.com/questions/199419",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35801/"
] |
I'm fine with `P` tags for most of the content, since it makes styling easier. However I'd like to have `span` `div` `iframe` and possibly other HTML tags to not be placed inside of a `p` for post.
I saw [this question](https://wordpress.stackexchange.com/questions/7090/stop-wordpress-wrapping-images-in-a-p-tag?rq=1) but it doesn't quite solve it. Also, I saw the [linked CSSTricks article](https://css-tricks.com/snippets/wordpress/remove-paragraph-tags-from-around-images/), and tried a sample code that used iFrame on it for my `spans`. Am I doing something wrong with the code? Or what should I do to remove the `p` tags from html tags in my post.
Here's my code that isn't working:
```
function filter_ptags_on_images($content) {
$content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
return preg_replace('/<p>\s*(<span .*>*.<\/span>)\s*<\/p>/iU', '\1', $content);
} add_filter('the_content', 'filter_ptags_on_images');
```
|
To me you code looks good, I would recommend adding priority as high as 9999
Heres how :
```
add_filter('the_content', 'filter_ptags_on_images', '9999');
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.